drone-path-core 1.0.0 → 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.
package/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  # drone-path-core
2
2
 
3
- Extract telemetry from DJI CAM-meta streams and SRT sidecars. This package
4
- also owns the telemetry document, frame ranges, and track export formats.
3
+ Extract telemetry from DJI CAM-meta streams and SRT sidecars. This package also
4
+ owns the telemetry document, frame ranges, spatial and camera-footprint math,
5
+ flight grouping, kinematic shot segmentation, launch redaction, track export
6
+ formats (`.gpx`, `.geojson`, `.kml`, `.kmz`, `.json`), and NLE timeline markers.
5
7
 
6
8
  ```sh
7
9
  npm install drone-path-core
@@ -29,6 +31,7 @@ Install `@types/node` for your Node.js major version. In TypeScript 6, list
29
31
  }
30
32
  ```
31
33
 
32
- Use `drone-path-engine` for render planning and video export.
34
+ Use `drone-path-archive` for library indexing and spatial search, and
35
+ `drone-path-engine` for render planning and video export.
33
36
  See the [project manual](https://github.com/MrManny/drone-path/tree/main/docs/user)
34
37
  for DJI input formats and telemetry details.
package/dist/errors.d.ts CHANGED
@@ -1,18 +1,14 @@
1
1
  export declare const ERROR_PREFIX = "[drone-path] ERROR: ";
2
2
  export declare function errorMessage(error: unknown): string;
3
- export declare const ERR_NO_RECORDING = "no recording loaded";
4
- export declare const ERR_EXPORT_ALREADY_RUNNING = "an export is already running";
5
- export declare const ERR_EXPORT_COULD_NOT_START = "export could not start";
6
- export declare const ERR_EXPORT_COULD_NOT_BE_CANCELED = "export could not be canceled";
7
- export declare const ERR_OUTPUT_OVERWRITES_SOURCE = "the output must not overwrite the source recording";
8
- export declare const ERR_OUTPUT_PATH_ABSOLUTE = "output path must be absolute: ";
9
- export declare const ERR_APP_BRIDGE_UNAVAILABLE = "app bridge unavailable";
3
+ export type ErrorParams = Readonly<Record<string, string | number>>;
4
+ export interface CodedErrorOptions {
5
+ code: string;
6
+ params?: ErrorParams;
7
+ cause?: unknown;
8
+ }
9
+ export declare function codedError(message: string, options: CodedErrorOptions): Error;
10
10
  export declare const ERR_RENDER_CANCELED = "render canceled";
11
- export declare const ERR_NOT_READABLE_MP4 = "not a readable .mp4 file: ";
12
11
  export declare const ERR_NO_TELEMETRY = "no telemetry found: ";
13
12
  export declare const ERR_OUTPUT_VERIFICATION = "output verification failed: ";
14
- export declare const ERR_COULD_NOT_REPLACE = "could not replace ";
15
- export declare const ERR_RENDER_KEPT_AT = "the finished render is at ";
16
13
  export declare const ERR_NO_FRAME_RATE = "could not determine the frame rate of the video";
17
- export declare const ERR_UNKNOWN = "unknown error";
18
14
  export declare function runToolMain(fn: () => void | Promise<void>): Promise<void>;
package/dist/errors.js CHANGED
@@ -2,25 +2,19 @@ export const ERROR_PREFIX = '[drone-path] ERROR: ';
2
2
  export function errorMessage(error) {
3
3
  return error instanceof Error ? error.message : String(error);
4
4
  }
5
- // The backend-to-UI error protocol: ui/lib/errortext.ts builds its sentence
6
- // patterns from these exact strings, so every producer spells its message
7
- // through here — rewording one is greppable and cannot silently downgrade
8
- // its UI sentence.
9
- export const ERR_NO_RECORDING = 'no recording loaded';
10
- export const ERR_EXPORT_ALREADY_RUNNING = 'an export is already running';
11
- export const ERR_EXPORT_COULD_NOT_START = 'export could not start';
12
- export const ERR_EXPORT_COULD_NOT_BE_CANCELED = 'export could not be canceled';
13
- export const ERR_OUTPUT_OVERWRITES_SOURCE = 'the output must not overwrite the source recording';
14
- export const ERR_OUTPUT_PATH_ABSOLUTE = 'output path must be absolute: ';
15
- export const ERR_APP_BRIDGE_UNAVAILABLE = 'app bridge unavailable';
5
+ export function codedError(message, options) {
6
+ const error = new Error(message, options.cause !== undefined ? { cause: options.cause } : undefined);
7
+ error.code = options.code;
8
+ if (options.params !== undefined)
9
+ error.params = options.params;
10
+ return error;
11
+ }
12
+ // Core and engine domain error messages shared with CLI and desktop wrappers;
13
+ // desktop-only IPC/UI error codes live in apps/desktop/shared/errors.ts.
16
14
  export const ERR_RENDER_CANCELED = 'render canceled';
17
- export const ERR_NOT_READABLE_MP4 = 'not a readable .mp4 file: ';
18
15
  export const ERR_NO_TELEMETRY = 'no telemetry found: ';
19
16
  export const ERR_OUTPUT_VERIFICATION = 'output verification failed: ';
20
- export const ERR_COULD_NOT_REPLACE = 'could not replace ';
21
- export const ERR_RENDER_KEPT_AT = 'the finished render is at ';
22
17
  export const ERR_NO_FRAME_RATE = 'could not determine the frame rate of the video';
23
- export const ERR_UNKNOWN = 'unknown error';
24
18
  // The mandated failure shell for generated-art tool entries (AGENTS.md): one
25
19
  // ERROR line on stderr and process.exitCode = 1, never a mid-flow exit.
26
20
  export async function runToolMain(fn) {
package/dist/ffmpeg.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ERR_NO_FRAME_RATE } from './errors.js';
1
+ import { ERR_NO_FRAME_RATE, codedError } from './errors.js';
2
2
  import { runTool } from './exec-tool.js';
3
3
  import { framesForSeconds, parseFpsRate } from './frametime.js';
4
4
  import { FFMPEG_TOOL_NAMES } from './ffmpeg-tools.js';
@@ -49,7 +49,7 @@ export async function probeVideo(tools, videoPath, log = () => { }, signal) {
49
49
  const fps = parseFpsRate(stream.r_frame_rate) ??
50
50
  parseFpsRate(stream.avg_frame_rate);
51
51
  if (!fps)
52
- throw new Error(ERR_NO_FRAME_RATE);
52
+ throw codedError(ERR_NO_FRAME_RATE, { code: 'NO_FRAME_RATE' });
53
53
  const durationSec = Number.parseFloat(format.duration ?? '');
54
54
  let frames = Number.parseInt(stream.nb_frames ?? '', 10);
55
55
  if (!Number.isFinite(frames) || frames <= 0) {
@@ -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,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;
@@ -0,0 +1,208 @@
1
+ import path from 'node:path';
2
+ import { pathToFileURL } from 'node:url';
3
+ const RESOLVE_CSV_HEADER = '#,Clip Name,In,Out,Duration,Marker Color,Marker Name,Notes';
4
+ const DEFAULT_MARKER_COLOR = 'Blue';
5
+ const DEFAULT_FPS = { num: 30, den: 1, value: 30, str: '30' };
6
+ export function markerFormatOf(filePath) {
7
+ const match = /\.([^.\\/]+)$/u.exec(filePath);
8
+ const ext = match ? match[1].toLowerCase() : '';
9
+ if (ext === 'csv')
10
+ return 'csv';
11
+ if (ext === 'fcpxml')
12
+ return 'fcpxml';
13
+ throw new Error('expected a .csv or .fcpxml output file');
14
+ }
15
+ function validateMarkerRange(marker) {
16
+ if (marker.clipPath.trim() === '') {
17
+ throw new Error('marker clipPath must not be empty');
18
+ }
19
+ if (marker.label.trim() === '') {
20
+ throw new Error('marker label must not be empty');
21
+ }
22
+ if (!Number.isFinite(marker.durationSec) || marker.durationSec <= 0) {
23
+ throw new Error('marker durationSec must be positive');
24
+ }
25
+ if (!Number.isFinite(marker.fps.value) ||
26
+ marker.fps.value <= 0 ||
27
+ !Number.isInteger(marker.fps.num) ||
28
+ marker.fps.num <= 0 ||
29
+ !Number.isInteger(marker.fps.den) ||
30
+ marker.fps.den <= 0) {
31
+ throw new Error('marker fps must be positive');
32
+ }
33
+ if (!Number.isFinite(marker.startSec) ||
34
+ !Number.isFinite(marker.endSec) ||
35
+ marker.startSec < 0 ||
36
+ marker.startSec > marker.endSec ||
37
+ marker.endSec > marker.durationSec) {
38
+ throw new Error('marker range must satisfy 0 <= startSec <= endSec <= durationSec');
39
+ }
40
+ }
41
+ function clipNameOf(marker) {
42
+ const trimmed = marker.clipName?.trim();
43
+ if (trimmed)
44
+ return trimmed;
45
+ const base = marker.clipPath.split(/[\\/]/u).at(-1);
46
+ return base && base.length > 0 ? base : marker.clipPath;
47
+ }
48
+ function nonEmptyOr(value, fallback) {
49
+ const trimmed = value?.trim();
50
+ return trimmed && trimmed.length > 0 ? trimmed : fallback;
51
+ }
52
+ function pad2(value) {
53
+ return String(value).padStart(2, '0');
54
+ }
55
+ function framesToSmpte(frames, tcBase) {
56
+ const ff = frames % tcBase;
57
+ const totalSec = Math.floor(frames / tcBase);
58
+ const ss = totalSec % 60;
59
+ const totalMin = Math.floor(totalSec / 60);
60
+ const mm = totalMin % 60;
61
+ const hh = Math.floor(totalMin / 60);
62
+ return `${pad2(hh)}:${pad2(mm)}:${pad2(ss)}:${pad2(ff)}`;
63
+ }
64
+ function escapeCsvCell(raw, guardFormula) {
65
+ // Prefix spreadsheet formula triggers with an apostrophe to neutralize CSV formula injection.
66
+ const safe = guardFormula && /^[=+\-@\t\r]/u.test(raw) ? `'${raw}` : raw;
67
+ if (!/[",\r\n]/u.test(safe))
68
+ return safe;
69
+ return `"${safe.replaceAll('"', '""')}"`;
70
+ }
71
+ export function serializeDaVinciResolveCsv(markers) {
72
+ const lines = [RESOLVE_CSV_HEADER];
73
+ for (let i = 0; i < markers.length; i++) {
74
+ const marker = markers[i];
75
+ validateMarkerRange(marker);
76
+ const tcBase = Math.max(1, Math.round(marker.fps.value));
77
+ const inFrames = Math.round(marker.startSec * marker.fps.value);
78
+ const outFrames = Math.round(marker.endSec * marker.fps.value);
79
+ const durFrames = Math.max(0, outFrames - inFrames);
80
+ const row = [
81
+ escapeCsvCell(String(i + 1), false),
82
+ escapeCsvCell(clipNameOf(marker), true),
83
+ escapeCsvCell(framesToSmpte(inFrames, tcBase), false),
84
+ escapeCsvCell(framesToSmpte(outFrames, tcBase), false),
85
+ escapeCsvCell(framesToSmpte(durFrames, tcBase), false),
86
+ escapeCsvCell(nonEmptyOr(marker.color, DEFAULT_MARKER_COLOR), true),
87
+ escapeCsvCell(marker.label, true),
88
+ escapeCsvCell(marker.note ?? '', true),
89
+ ];
90
+ lines.push(row.join(','));
91
+ }
92
+ return lines.join('\n') + '\n';
93
+ }
94
+ function gcd(a, b) {
95
+ let x = Math.abs(a);
96
+ let y = Math.abs(b);
97
+ while (y !== 0) {
98
+ const t = x % y;
99
+ x = y;
100
+ y = t;
101
+ }
102
+ return x || 1;
103
+ }
104
+ function rationalTime(frames, fps) {
105
+ if (frames === 0)
106
+ return '0s';
107
+ const num = frames * fps.den;
108
+ const den = fps.num;
109
+ const factor = gcd(num, den);
110
+ return `${num / factor}/${den / factor}s`;
111
+ }
112
+ function frameDurationAttr(fps) {
113
+ const factor = gcd(fps.den, fps.num);
114
+ return `${fps.den / factor}/${fps.num / factor}s`;
115
+ }
116
+ function escapeXml(raw) {
117
+ // Strip ASCII control characters disallowed by XML 1.0 before entity escaping.
118
+ let clean = '';
119
+ for (const ch of raw) {
120
+ const code = ch.charCodeAt(0);
121
+ if (code === 0x09 || code === 0x0a || code === 0x0d || code >= 0x20) {
122
+ clean += ch;
123
+ }
124
+ }
125
+ return clean
126
+ .replaceAll('&', '&amp;')
127
+ .replaceAll('<', '&lt;')
128
+ .replaceAll('>', '&gt;')
129
+ .replaceAll('"', '&quot;')
130
+ .replaceAll("'", '&apos;');
131
+ }
132
+ function fileUrlOf(clipPath) {
133
+ return pathToFileURL(path.resolve(clipPath)).href;
134
+ }
135
+ export function serializeFcpxmlMarkers(markers) {
136
+ for (const marker of markers)
137
+ validateMarkerRange(marker);
138
+ const formatIds = new Map();
139
+ const assetIds = new Map();
140
+ let nextId = 1;
141
+ const allocId = () => `r${nextId++}`;
142
+ const ensureFormat = (fps) => {
143
+ const frameDuration = frameDurationAttr(fps);
144
+ const existing = formatIds.get(frameDuration);
145
+ if (existing)
146
+ return existing.id;
147
+ const id = allocId();
148
+ formatIds.set(frameDuration, { id, fps, frameDuration });
149
+ return id;
150
+ };
151
+ if (markers.length === 0) {
152
+ ensureFormat(DEFAULT_FPS);
153
+ }
154
+ else {
155
+ for (const marker of markers)
156
+ ensureFormat(marker.fps);
157
+ }
158
+ for (const marker of markers) {
159
+ const formatId = ensureFormat(marker.fps);
160
+ const resolvedKey = path.resolve(marker.clipPath);
161
+ if (!assetIds.has(resolvedKey)) {
162
+ const assetFrames = Math.max(1, Math.round(marker.durationSec * marker.fps.value));
163
+ assetIds.set(resolvedKey, {
164
+ id: allocId(),
165
+ name: clipNameOf(marker),
166
+ src: fileUrlOf(marker.clipPath),
167
+ duration: rationalTime(assetFrames, marker.fps),
168
+ formatId,
169
+ });
170
+ }
171
+ }
172
+ const seqFps = markers[0]?.fps ?? DEFAULT_FPS;
173
+ const seqFormatId = ensureFormat(seqFps);
174
+ const lines = [
175
+ '<?xml version="1.0" encoding="UTF-8"?>',
176
+ '<!DOCTYPE fcpxml>',
177
+ '<fcpxml version="1.10">',
178
+ ' <resources>',
179
+ ];
180
+ for (const fmt of formatIds.values()) {
181
+ lines.push(` <format id="${fmt.id}" name="FFVideoFormatRateUndefined" frameDuration="${fmt.frameDuration}"/>`);
182
+ }
183
+ for (const asset of assetIds.values()) {
184
+ lines.push(` <asset id="${asset.id}" name="${escapeXml(asset.name)}" src="${escapeXml(asset.src)}" start="0s" duration="${asset.duration}" hasVideo="1" format="${asset.formatId}"/>`);
185
+ }
186
+ const spineLines = [];
187
+ let timelineOffsetFrames = 0;
188
+ for (const marker of markers) {
189
+ const formatId = ensureFormat(marker.fps);
190
+ const asset = assetIds.get(path.resolve(marker.clipPath));
191
+ const inFrames = Math.round(marker.startSec * marker.fps.value);
192
+ const outFrames = Math.round(marker.endSec * marker.fps.value);
193
+ const clipFrames = Math.max(1, outFrames - inFrames);
194
+ const startAttr = rationalTime(inFrames, marker.fps);
195
+ const clipDurAttr = rationalTime(clipFrames, marker.fps);
196
+ const markerDurAttr = rationalTime(Math.max(0, outFrames - inFrames), marker.fps);
197
+ const offsetAttr = rationalTime(timelineOffsetFrames, seqFps);
198
+ const noteAttr = marker.note ? ` note="${escapeXml(marker.note)}"` : '';
199
+ spineLines.push(` <asset-clip ref="${asset.id}" offset="${offsetAttr}" name="${escapeXml(clipNameOf(marker))}" start="${startAttr}" duration="${clipDurAttr}" format="${formatId}">`, ` <marker start="${startAttr}" duration="${markerDurAttr}" value="${escapeXml(marker.label)}"${noteAttr}/>`, ' </asset-clip>');
200
+ const seqAdvance = frameDurationAttr(marker.fps) === frameDurationAttr(seqFps)
201
+ ? clipFrames
202
+ : Math.max(1, Math.round((clipFrames / marker.fps.value) * seqFps.value));
203
+ timelineOffsetFrames += seqAdvance;
204
+ }
205
+ const seqDurationAttr = rationalTime(timelineOffsetFrames, seqFps);
206
+ lines.push(' </resources>', ' <library>', ' <event name="drone-path">', ' <project name="drone-path-markers">', ` <sequence format="${seqFormatId}" duration="${seqDurationAttr}">`, ' <spine>', ...spineLines, ' </spine>', ' </sequence>', ' </project>', ' </event>', ' </library>', '</fcpxml>', '');
207
+ return lines.join('\n');
208
+ }
@@ -0,0 +1,17 @@
1
+ import type { TrackRecord } from './track.js';
2
+ export declare const SHOT_TYPES: readonly ["takeoff", "landing", "hover", "smooth-glide", "orbit", "gimbal-reveal", "reposition"];
3
+ export type ShotType = (typeof SHOT_TYPES)[number];
4
+ export interface KinematicShot {
5
+ type: ShotType;
6
+ startSec: number;
7
+ endSec: number;
8
+ durationSec: number;
9
+ smoothness: number;
10
+ exposureStable: boolean;
11
+ meanSpeedMps: number;
12
+ meanYawRateDegPerSec: number;
13
+ }
14
+ /**
15
+ * Classifies a clip's telemetry records into contiguous deterministic kinematic shot segments.
16
+ */
17
+ export declare function segmentFlightShots(records: readonly TrackRecord[]): KinematicShot[];
@@ -0,0 +1,428 @@
1
+ import { bearingDeg, gpsFixOrNull, haversineM } from './geo.js';
2
+ export const SHOT_TYPES = [
3
+ 'takeoff',
4
+ 'landing',
5
+ 'hover',
6
+ 'smooth-glide',
7
+ 'orbit',
8
+ 'gimbal-reveal',
9
+ 'reposition',
10
+ ];
11
+ const MAX_INTERPOLATION_GAP_S = 3;
12
+ const EDGE_SNAP_GAP_S = 0.5;
13
+ const MIN_WINDOW_REMAINDER_S = 0.5;
14
+ const TERMINAL_PHASE_WINDOW_S = 15;
15
+ const EXPOSURE_REL_THRESHOLD = 0.25;
16
+ const EXPOSURE_CCT_THRESHOLD_K = 200;
17
+ const SHORT_CLIP_MAX_S = 4;
18
+ const BLIP_MAX_DURATION_S = 2;
19
+ function roundTo(value, decimals) {
20
+ const factor = 10 ** decimals;
21
+ const rounded = Math.round(value * factor) / factor;
22
+ return rounded === 0 ? 0 : rounded;
23
+ }
24
+ function shortestAngleDiffDeg(fromDeg, toDeg) {
25
+ return ((((toDeg - fromDeg + 540) % 360) + 360) % 360) - 180;
26
+ }
27
+ function normalizeDeg(deg) {
28
+ return ((deg % 360) + 360) % 360;
29
+ }
30
+ function altitudeOf(record) {
31
+ if (typeof record.altRel === 'number' && Number.isFinite(record.altRel))
32
+ return record.altRel;
33
+ if (typeof record.altAbs === 'number' && Number.isFinite(record.altAbs))
34
+ return record.altAbs;
35
+ if (typeof record.gpsAltMm === 'number' && Number.isFinite(record.gpsAltMm))
36
+ return record.gpsAltMm / 1000;
37
+ return null;
38
+ }
39
+ function fixOf(record) {
40
+ return gpsFixOrNull(record.lat ?? null, record.lng ?? null);
41
+ }
42
+ function finiteOrNull(value) {
43
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
44
+ }
45
+ function lowerBoundTime(records, targetT) {
46
+ let lo = 0;
47
+ let hi = records.length;
48
+ while (lo < hi) {
49
+ const mid = (lo + hi) >> 1;
50
+ if (records[mid].tSec < targetT)
51
+ lo = mid + 1;
52
+ else
53
+ hi = mid;
54
+ }
55
+ return lo;
56
+ }
57
+ function bracketValue(records, targetT, read) {
58
+ const idx = lowerBoundTime(records, targetT);
59
+ let before = null;
60
+ for (let i = Math.min(idx, records.length - 1); i >= 0; i--) {
61
+ if (records[i].tSec > targetT)
62
+ continue;
63
+ const value = read(records[i]);
64
+ if (value !== null) {
65
+ before = { tSec: records[i].tSec, value };
66
+ break;
67
+ }
68
+ }
69
+ let after = null;
70
+ for (let i = idx; i < records.length; i++) {
71
+ if (records[i].tSec < targetT)
72
+ continue;
73
+ const value = read(records[i]);
74
+ if (value !== null) {
75
+ after = { tSec: records[i].tSec, value };
76
+ break;
77
+ }
78
+ }
79
+ return { before, after };
80
+ }
81
+ function sampleFixAt(records, targetT) {
82
+ const { before, after } = bracketValue(records, targetT, fixOf);
83
+ if (before && after) {
84
+ if (before.tSec === targetT)
85
+ return before.value;
86
+ if (after.tSec === targetT)
87
+ return after.value;
88
+ const span = after.tSec - before.tSec;
89
+ if (span <= MAX_INTERPOLATION_GAP_S && Math.abs(after.value.lon - before.value.lon) <= 180) {
90
+ const fraction = (targetT - before.tSec) / span;
91
+ return {
92
+ lat: before.value.lat + (after.value.lat - before.value.lat) * fraction,
93
+ lon: before.value.lon + (after.value.lon - before.value.lon) * fraction,
94
+ };
95
+ }
96
+ }
97
+ if (before && targetT - before.tSec <= EDGE_SNAP_GAP_S)
98
+ return before.value;
99
+ if (after && after.tSec - targetT <= EDGE_SNAP_GAP_S)
100
+ return after.value;
101
+ return null;
102
+ }
103
+ function sampleScalarAt(records, targetT, read) {
104
+ const { before, after } = bracketValue(records, targetT, read);
105
+ if (before && after) {
106
+ if (before.tSec === targetT)
107
+ return before.value;
108
+ if (after.tSec === targetT)
109
+ return after.value;
110
+ const span = after.tSec - before.tSec;
111
+ if (span <= MAX_INTERPOLATION_GAP_S) {
112
+ const fraction = (targetT - before.tSec) / span;
113
+ return before.value + (after.value - before.value) * fraction;
114
+ }
115
+ }
116
+ if (before && targetT - before.tSec <= EDGE_SNAP_GAP_S)
117
+ return before.value;
118
+ if (after && after.tSec - targetT <= EDGE_SNAP_GAP_S)
119
+ return after.value;
120
+ return null;
121
+ }
122
+ function sampleAngleAt(records, targetT, read) {
123
+ const { before, after } = bracketValue(records, targetT, read);
124
+ if (before && after) {
125
+ if (before.tSec === targetT)
126
+ return normalizeDeg(before.value);
127
+ if (after.tSec === targetT)
128
+ return normalizeDeg(after.value);
129
+ const span = after.tSec - before.tSec;
130
+ if (span <= MAX_INTERPOLATION_GAP_S) {
131
+ const fraction = (targetT - before.tSec) / span;
132
+ return normalizeDeg(before.value + shortestAngleDiffDeg(before.value, after.value) * fraction);
133
+ }
134
+ }
135
+ if (before && targetT - before.tSec <= EDGE_SNAP_GAP_S)
136
+ return normalizeDeg(before.value);
137
+ if (after && after.tSec - targetT <= EDGE_SNAP_GAP_S)
138
+ return normalizeDeg(after.value);
139
+ return null;
140
+ }
141
+ function buildWindowBounds(minT, maxT) {
142
+ const bounds = [];
143
+ let cursor = minT;
144
+ while (cursor < maxT) {
145
+ const remaining = maxT - cursor;
146
+ // Fold a tiny trailing sliver into the previous window so every window spans at least 0.5 s.
147
+ if (remaining < MIN_WINDOW_REMAINDER_S && bounds.length > 0) {
148
+ bounds[bounds.length - 1].endSec = maxT;
149
+ break;
150
+ }
151
+ const endSec = Math.min(maxT, cursor + 1);
152
+ bounds.push({ startSec: cursor, endSec });
153
+ cursor = endSec;
154
+ }
155
+ return bounds;
156
+ }
157
+ function hasRelativeJump(a, b, threshold) {
158
+ const lo = Math.min(a, b);
159
+ const hi = Math.max(a, b);
160
+ if (lo <= 0)
161
+ return hi !== lo;
162
+ return (hi - lo) / lo > threshold;
163
+ }
164
+ function channelStable(samples, isJump) {
165
+ let prev = null;
166
+ let min = Infinity;
167
+ let max = -Infinity;
168
+ for (const value of samples) {
169
+ if (value === null)
170
+ continue;
171
+ if (prev !== null && isJump(prev, value))
172
+ return false;
173
+ prev = value;
174
+ min = Math.min(min, value);
175
+ max = Math.max(max, value);
176
+ }
177
+ return !Number.isFinite(min) || !isJump(min, max);
178
+ }
179
+ function isWindowExposureStable(records, wStart, wEnd) {
180
+ const firstIdx = lowerBoundTime(records, wStart);
181
+ const slice = [];
182
+ // Include the preceding sample only when no record sits on wStart so an exposure step before wStart does not bleed into the next window.
183
+ if (firstIdx > 0 &&
184
+ (firstIdx >= records.length || records[firstIdx].tSec > wStart) &&
185
+ wStart - records[firstIdx - 1].tSec <= MAX_INTERPOLATION_GAP_S) {
186
+ slice.push(records[firstIdx - 1]);
187
+ }
188
+ for (let i = firstIdx; i < records.length && records[i].tSec <= wEnd; i++) {
189
+ slice.push(records[i]);
190
+ }
191
+ if (slice.length < 2)
192
+ return true;
193
+ const isoStable = channelStable(slice.map((r) => finiteOrNull(r.iso)), (a, b) => hasRelativeJump(a, b, EXPOSURE_REL_THRESHOLD));
194
+ const shutterStable = channelStable(slice.map((r) => finiteOrNull(r.shutterTime)), (a, b) => hasRelativeJump(a, b, EXPOSURE_REL_THRESHOLD));
195
+ const wbStable = channelStable(slice.map((r) => finiteOrNull(r.whiteBalanceCctK)), (a, b) => Math.abs(b - a) > EXPOSURE_CCT_THRESHOLD_K || hasRelativeJump(a, b, EXPOSURE_REL_THRESHOLD));
196
+ return isoStable && shutterStable && wbStable;
197
+ }
198
+ function classifyWindow(window, minT, maxT) {
199
+ const { hasFix, speedMps, signedAccelMps2, yawRateDegPerSec, signedGimbalPitchRate, altRateMps, startSec, endSec } = window;
200
+ const absAccel = Math.abs(signedAccelMps2);
201
+ const absYawRate = Math.abs(yawRateDegPerSec);
202
+ const absGimbalPitchRate = signedGimbalPitchRate === null ? null : Math.abs(signedGimbalPitchRate);
203
+ const absAltRate = Math.abs(altRateMps ?? 0);
204
+ if (endSec - minT <= TERMINAL_PHASE_WINDOW_S && altRateMps !== null && altRateMps >= 0.8) {
205
+ return 'takeoff';
206
+ }
207
+ if (maxT - startSec <= TERMINAL_PHASE_WINDOW_S && altRateMps !== null && altRateMps <= -0.8) {
208
+ return 'landing';
209
+ }
210
+ if (hasFix && speedMps < 0.8 && absAltRate < 0.5 && (absGimbalPitchRate === null || absGimbalPitchRate < 3)) {
211
+ return 'hover';
212
+ }
213
+ if (absGimbalPitchRate !== null && absGimbalPitchRate >= 4 && absAccel < 3) {
214
+ return 'gimbal-reveal';
215
+ }
216
+ if (speedMps >= 1.0 && absYawRate >= 4 && absYawRate <= 45) {
217
+ return 'orbit';
218
+ }
219
+ if (speedMps >= 1.0 && absYawRate < 4 && absAccel < 2.0 && absAltRate < 1.0) {
220
+ return 'smooth-glide';
221
+ }
222
+ return 'reposition';
223
+ }
224
+ function buildWindows(records, minT, maxT) {
225
+ const bounds = buildWindowBounds(minT, maxT);
226
+ const raw = bounds.map(({ startSec, endSec }) => {
227
+ const dt = endSec - startSec;
228
+ const fixStart = sampleFixAt(records, startSec);
229
+ const fixMid = sampleFixAt(records, (startSec + endSec) / 2);
230
+ const fixEnd = sampleFixAt(records, endSec);
231
+ let speedMps = 0;
232
+ const hasFix = Boolean(fixStart && fixEnd);
233
+ if (fixStart && fixEnd) {
234
+ const distM = fixMid
235
+ ? haversineM(fixStart, fixMid) + haversineM(fixMid, fixEnd)
236
+ : haversineM(fixStart, fixEnd);
237
+ speedMps = distM / dt;
238
+ }
239
+ const altStart = sampleScalarAt(records, startSec, altitudeOf);
240
+ const altEnd = sampleScalarAt(records, endSec, altitudeOf);
241
+ const altRateMps = altStart !== null && altEnd !== null ? (altEnd - altStart) / dt : null;
242
+ const yawStart = sampleAngleAt(records, startSec, (r) => finiteOrNull(r.yawDeg));
243
+ const yawEnd = sampleAngleAt(records, endSec, (r) => finiteOrNull(r.yawDeg));
244
+ const directYawRate = yawStart !== null && yawEnd !== null
245
+ ? shortestAngleDiffDeg(yawStart, yawEnd) / dt
246
+ : null;
247
+ const cogHeading = fixStart && fixEnd && speedMps >= 0.5 ? bearingDeg(fixStart, fixEnd) : null;
248
+ const gimbalPitchStart = sampleScalarAt(records, startSec, (r) => finiteOrNull(r.gimbalPitchDeg));
249
+ const gimbalPitchEnd = sampleScalarAt(records, endSec, (r) => finiteOrNull(r.gimbalPitchDeg));
250
+ const signedGimbalPitchRate = gimbalPitchStart !== null && gimbalPitchEnd !== null
251
+ ? (gimbalPitchEnd - gimbalPitchStart) / dt
252
+ : null;
253
+ const gimbalYawStart = sampleAngleAt(records, startSec, (r) => finiteOrNull(r.gimbalYawDeg));
254
+ const gimbalYawEnd = sampleAngleAt(records, endSec, (r) => finiteOrNull(r.gimbalYawDeg));
255
+ const signedGimbalYawRate = gimbalYawStart !== null && gimbalYawEnd !== null
256
+ ? shortestAngleDiffDeg(gimbalYawStart, gimbalYawEnd) / dt
257
+ : null;
258
+ return {
259
+ startSec,
260
+ endSec,
261
+ centerSec: (startSec + endSec) / 2,
262
+ hasFix,
263
+ speedMps,
264
+ directYawRate,
265
+ cogHeading,
266
+ signedGimbalPitchRate,
267
+ signedGimbalYawRate,
268
+ altRateMps,
269
+ exposureStable: isWindowExposureStable(records, startSec, endSec),
270
+ };
271
+ });
272
+ return raw.map((w, i) => {
273
+ let yawRateDegPerSec = w.directYawRate;
274
+ if (yawRateDegPerSec === null) {
275
+ const prev = i > 0 ? raw[i - 1] : undefined;
276
+ const next = i === 0 ? raw[1] : undefined;
277
+ if (prev && w.cogHeading !== null && prev.cogHeading !== null) {
278
+ yawRateDegPerSec = shortestAngleDiffDeg(prev.cogHeading, w.cogHeading) /
279
+ (w.centerSec - prev.centerSec);
280
+ }
281
+ else if (next && w.cogHeading !== null && next.cogHeading !== null) {
282
+ yawRateDegPerSec = shortestAngleDiffDeg(w.cogHeading, next.cogHeading) /
283
+ (next.centerSec - w.centerSec);
284
+ }
285
+ else {
286
+ yawRateDegPerSec = 0;
287
+ }
288
+ }
289
+ const signedAccelMps2 = i > 0
290
+ ? (w.speedMps - raw[i - 1].speedMps) / (w.centerSec - raw[i - 1].centerSec)
291
+ : 0;
292
+ const partial = {
293
+ startSec: w.startSec,
294
+ endSec: w.endSec,
295
+ centerSec: w.centerSec,
296
+ hasFix: w.hasFix,
297
+ speedMps: w.speedMps,
298
+ signedAccelMps2,
299
+ yawRateDegPerSec,
300
+ signedGimbalPitchRate: w.signedGimbalPitchRate,
301
+ signedGimbalYawRate: w.signedGimbalYawRate,
302
+ altRateMps: w.altRateMps,
303
+ exposureStable: w.exposureStable,
304
+ };
305
+ return { ...partial, type: classifyWindow(partial, minT, maxT) };
306
+ });
307
+ }
308
+ function runDuration(run) {
309
+ return run.windows[run.windows.length - 1].endSec - run.windows[0].startSec;
310
+ }
311
+ function mergeSameTypeRuns(runs) {
312
+ const merged = [];
313
+ for (const run of runs) {
314
+ const prev = merged.at(-1);
315
+ if (prev && prev.type === run.type) {
316
+ prev.windows.push(...run.windows);
317
+ }
318
+ else {
319
+ merged.push({ type: run.type, windows: [...run.windows] });
320
+ }
321
+ }
322
+ return merged;
323
+ }
324
+ function coalesceRuns(windows, totalDuration) {
325
+ let runs = mergeSameTypeRuns(windows.map((w) => ({ type: w.type, windows: [w] })));
326
+ if (runs.length <= 1 || totalDuration < SHORT_CLIP_MAX_S)
327
+ return runs;
328
+ // Absorb transient <2 s blips into flanking runs when sandwiched by the same type,
329
+ // or into the longer neighbor when not an intentional terminal takeoff/landing phase.
330
+ let changed = true;
331
+ while (changed && runs.length > 1) {
332
+ changed = false;
333
+ for (let i = 0; i < runs.length; i++) {
334
+ const run = runs[i];
335
+ if (runDuration(run) >= BLIP_MAX_DURATION_S)
336
+ continue;
337
+ const prev = i > 0 ? runs[i - 1] : null;
338
+ const next = i < runs.length - 1 ? runs[i + 1] : null;
339
+ if (prev && next && prev.type === next.type) {
340
+ prev.windows.push(...run.windows, ...next.windows);
341
+ runs.splice(i, 2);
342
+ changed = true;
343
+ break;
344
+ }
345
+ const isTerminalPhase = (i === 0 && run.type === 'takeoff') || (i === runs.length - 1 && run.type === 'landing');
346
+ if (isTerminalPhase)
347
+ continue;
348
+ if (prev && (!next || runDuration(prev) >= runDuration(next))) {
349
+ prev.windows.push(...run.windows);
350
+ runs.splice(i, 1);
351
+ }
352
+ else if (next) {
353
+ next.windows.unshift(...run.windows);
354
+ runs.splice(i, 1);
355
+ }
356
+ runs = mergeSameTypeRuns(runs);
357
+ changed = true;
358
+ break;
359
+ }
360
+ }
361
+ return runs;
362
+ }
363
+ function variance(values) {
364
+ if (values.length < 2)
365
+ return 0;
366
+ let sum = 0;
367
+ for (const v of values)
368
+ sum += v;
369
+ const mean = sum / values.length;
370
+ let sq = 0;
371
+ for (const v of values)
372
+ sq += (v - mean) ** 2;
373
+ return sq / values.length;
374
+ }
375
+ function mean(values) {
376
+ if (values.length === 0)
377
+ return 0;
378
+ let sum = 0;
379
+ for (const v of values)
380
+ sum += v;
381
+ return sum / values.length;
382
+ }
383
+ function computeSmoothness(windows) {
384
+ const accels = windows.map((w) => w.signedAccelMps2);
385
+ const yawRates = windows.map((w) => w.yawRateDegPerSec);
386
+ const gimbalPitches = windows.flatMap((w) => (w.signedGimbalPitchRate === null ? [] : [w.signedGimbalPitchRate]));
387
+ const gimbalYaws = windows.flatMap((w) => (w.signedGimbalYawRate === null ? [] : [w.signedGimbalYawRate]));
388
+ const accelVar = variance(accels);
389
+ const meanAbsAccel = mean(accels.map(Math.abs));
390
+ const yawVar = variance(yawRates);
391
+ const excessYaw = Math.max(0, mean(yawRates.map(Math.abs)) - 45);
392
+ const gimbalVar = variance(gimbalPitches) + variance(gimbalYaws);
393
+ const penalty = accelVar / 4 + meanAbsAccel / 5 + yawVar / 100 + excessYaw / 30 + gimbalVar / 100;
394
+ const score = Math.min(1, Math.max(0, Math.exp(-penalty)));
395
+ return roundTo(score, 3);
396
+ }
397
+ /**
398
+ * Classifies a clip's telemetry records into contiguous deterministic kinematic shot segments.
399
+ */
400
+ export function segmentFlightShots(records) {
401
+ const valid = records.filter((r) => Number.isFinite(r.tSec));
402
+ if (valid.length < 2)
403
+ return [];
404
+ const sorted = [...valid].sort((a, b) => a.tSec - b.tSec);
405
+ const minT = sorted[0].tSec;
406
+ const maxT = sorted[sorted.length - 1].tSec;
407
+ const totalDuration = maxT - minT;
408
+ if (!Number.isFinite(totalDuration) || totalDuration < 1)
409
+ return [];
410
+ const windows = buildWindows(sorted, minT, maxT);
411
+ if (windows.length === 0)
412
+ return [];
413
+ const runs = coalesceRuns(windows, totalDuration);
414
+ return runs.map(({ type, windows: runWindows }) => {
415
+ const startSec = roundTo(runWindows[0].startSec, 3);
416
+ const endSec = roundTo(runWindows[runWindows.length - 1].endSec, 3);
417
+ return {
418
+ type,
419
+ startSec,
420
+ endSec,
421
+ durationSec: roundTo(endSec - startSec, 3),
422
+ smoothness: computeSmoothness(runWindows),
423
+ exposureStable: runWindows.every((w) => w.exposureStable),
424
+ meanSpeedMps: roundTo(mean(runWindows.map((w) => w.speedMps)), 2),
425
+ meanYawRateDegPerSec: roundTo(mean(runWindows.map((w) => w.yawRateDegPerSec)), 2),
426
+ };
427
+ });
428
+ }
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';
@@ -77,11 +77,14 @@ export async function loadTelemetrySamples(tools, videoPath, durationSec, camMet
77
77
  }
78
78
  export async function loadTelemetry(videoPath, { frames, fpsValue, durationSec, tools, camMeta, }) {
79
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`);
80
+ if (!loaded) {
81
+ throw codedError(`${ERR_NO_TELEMETRY}no CAM meta (DVTM) stream and no .SRT sidecar`, {
82
+ code: 'NO_TELEMETRY',
83
+ });
84
+ }
82
85
  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');
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' });
85
88
  }
86
89
  const { frameValues, trackValues, protoFile, gimbalDevice, ...samples } = loaded;
87
90
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-core",
3
- "version": "1.0.0",
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": {