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
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/cammeta.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import type { CamMetaResult } from './cammeta-decode.js';
2
+ import type { CamMetaStream } from './ffmpeg.js';
2
3
  import type { FfmpegToolPaths } from './ffmpeg-tools.js';
3
4
  export declare function parseCamMeta(tools: FfmpegToolPaths, videoPath: string, durationSec: number, opts?: {
4
5
  keepAll?: boolean;
6
+ stream?: CamMetaStream | null;
7
+ signal?: AbortSignal;
5
8
  }): Promise<CamMetaResult | null>;
package/dist/cammeta.js CHANGED
@@ -1,33 +1,26 @@
1
- import fs from 'node:fs';
2
- import os from 'node:os';
3
- import path from 'node:path';
1
+ import { constants } from 'node:buffer';
4
2
  import { decodePacketSamples, scanBufferForGpsPairs, spreadSampleTimes, } from './cammeta-decode.js';
5
- import { runTool } from './exec-tool.js';
6
- import { ffprobeJson } from './ffmpeg.js';
7
- const FFMPEG_MAX_BUFFER = 64 * 1024 * 1024;
8
- async function findCamMetaIndex(tools, videoPath) {
3
+ import { runToolBinary } from './exec-tool.js';
4
+ import { ffprobeJson, findCamMetaStream } from './ffmpeg.js';
5
+ import { readCamMetaTrack } from './mp4-cammeta.js';
6
+ async function probeCamMetaStream(tools, videoPath, signal) {
9
7
  let probe;
10
8
  try {
11
9
  probe = await ffprobeJson(tools, videoPath, [
12
10
  '-select_streams',
13
11
  'd',
14
12
  '-show_entries',
15
- 'stream=index:stream_tags=handler_name',
13
+ 'stream=index,id:stream_tags=handler_name',
16
14
  '-of',
17
15
  'json',
18
- ]);
16
+ ], signal);
19
17
  }
20
18
  catch (e) {
21
19
  throw new Error('ffprobe failed while probing the cam meta stream', { cause: e });
22
20
  }
23
- const streams = (probe['streams'] ?? []);
24
- for (const stream of streams) {
25
- if (stream.tags && stream.tags.handler_name === 'CAM meta')
26
- return stream.index;
27
- }
28
- return null;
21
+ return findCamMetaStream(probe);
29
22
  }
30
- async function listCamMetaPackets(tools, videoPath, streamIndex) {
23
+ async function listCamMetaPackets(tools, videoPath, streamIndex, signal) {
31
24
  let probe;
32
25
  try {
33
26
  probe = await ffprobeJson(tools, videoPath, [
@@ -38,7 +31,7 @@ async function listCamMetaPackets(tools, videoPath, streamIndex) {
38
31
  'packet=pts_time,size',
39
32
  '-of',
40
33
  'json',
41
- ]);
34
+ ], signal);
42
35
  }
43
36
  catch (e) {
44
37
  throw new Error('ffprobe failed while listing the cam meta packets', { cause: e });
@@ -48,33 +41,28 @@ async function listCamMetaPackets(tools, videoPath, streamIndex) {
48
41
  size: Number.parseInt(packet.size, 10),
49
42
  }));
50
43
  }
51
- async function dumpCamMetaStream(tools, videoPath, streamIndex) {
52
- const tmp = path.join(os.tmpdir(), `cammeta_${process.pid}_${Date.now().toString(36)}.bin`);
44
+ async function dumpCamMetaStream(tools, videoPath, streamIndex, signal) {
53
45
  try {
54
- try {
55
- await runTool(tools.ffmpeg, [
56
- '-v', 'error', '-y', '-i', videoPath,
57
- '-map', `0:${streamIndex}`, '-c', 'copy', '-f', 'rawvideo', tmp,
58
- ], { maxBuffer: FFMPEG_MAX_BUFFER });
59
- }
60
- catch (e) {
61
- throw new Error('ffmpeg failed while dumping the cam meta stream', { cause: e });
62
- }
63
- return fs.readFileSync(tmp);
46
+ return await runToolBinary(tools.ffmpeg, [
47
+ '-v', 'error', '-i', videoPath,
48
+ '-map', `0:${streamIndex}`, '-c', 'copy', '-f', 'rawvideo', 'pipe:1',
49
+ ], { maxBuffer: constants.MAX_LENGTH, signal });
64
50
  }
65
- finally {
66
- fs.rmSync(tmp, { force: true });
51
+ catch (e) {
52
+ throw new Error('ffmpeg failed while dumping the cam meta stream', { cause: e });
67
53
  }
68
54
  }
69
55
  // Resolves to null only when the video carries no CAM meta stream at all; a
70
56
  // present stream that yields nothing decodable resolves to empty samples so
71
57
  // callers can tell absence from a stream without GPS fix pairs.
72
58
  export async function parseCamMeta(tools, videoPath, durationSec, opts = {}) {
73
- const streamIndex = await findCamMetaIndex(tools, videoPath);
74
- if (streamIndex === null)
59
+ opts.signal?.throwIfAborted();
60
+ const stream = opts.stream === undefined ? await probeCamMetaStream(tools, videoPath, opts.signal) : opts.stream;
61
+ if (stream === null)
75
62
  return null;
76
- const packets = await listCamMetaPackets(tools, videoPath, streamIndex);
77
- const buf = await dumpCamMetaStream(tools, videoPath, streamIndex);
63
+ const direct = stream.trackId === undefined ? null : await readCamMetaTrack(videoPath, stream.trackId, opts.signal);
64
+ const packets = direct?.packets ?? await listCamMetaPackets(tools, videoPath, stream.index, opts.signal);
65
+ const buf = direct?.buffer ?? await dumpCamMetaStream(tools, videoPath, stream.index, opts.signal);
78
66
  const sizeSum = packets.reduce((sum, packet) => sum + (Number.isFinite(packet.size) ? packet.size : 0), 0);
79
67
  if (buf.length > 0 && packets.length > 0 && sizeSum === buf.length) {
80
68
  const { samples, noLock, provenance } = decodePacketSamples(buf, packets, opts.keepAll === true);
@@ -0,0 +1,11 @@
1
+ export interface DecimatedTrack {
2
+ lat: number[];
3
+ lon: number[];
4
+ frame: number[];
5
+ }
6
+ interface DecimateOptions {
7
+ epsilonPx?: number;
8
+ maxPoints?: number;
9
+ }
10
+ export declare function decimateTrack(lat: readonly number[], lon: readonly number[], zoom: number, options?: DecimateOptions): DecimatedTrack;
11
+ export {};
@@ -0,0 +1,84 @@
1
+ import { project } from './geo.js';
2
+ const DEFAULT_EPSILON_PX = 1;
3
+ const DEFAULT_MAX_POINTS = 3000;
4
+ export function decimateTrack(lat, lon, zoom, options = {}) {
5
+ const epsilonPx = options.epsilonPx ?? DEFAULT_EPSILON_PX;
6
+ const maxPoints = options.maxPoints ?? DEFAULT_MAX_POINTS;
7
+ if (!(epsilonPx >= 0))
8
+ throw new Error('epsilon must be >= 0');
9
+ if (!Number.isInteger(maxPoints) || maxPoints < 2) {
10
+ throw new Error('maxPoints must be an integer >= 2');
11
+ }
12
+ if (lat.length !== lon.length) {
13
+ throw new Error('lat and lon must have the same length');
14
+ }
15
+ const n = lat.length;
16
+ if (n === 0)
17
+ return { lat: [], lon: [], frame: [] };
18
+ if (n === 1)
19
+ return { lat: [lat[0]], lon: [lon[0]], frame: [0] };
20
+ const px = new Array(n);
21
+ for (let i = 0; i < n; i++)
22
+ px[i] = project(lon[i], lat[i], zoom);
23
+ let keep = douglasPeucker(px, epsilonPx);
24
+ if (keep.length > maxPoints) {
25
+ let hi = epsilonPx > 0 ? epsilonPx * 2 : 1;
26
+ let hiKeep = douglasPeucker(px, hi);
27
+ while (hiKeep.length > maxPoints) {
28
+ hi *= 2;
29
+ hiKeep = douglasPeucker(px, hi);
30
+ }
31
+ keep = hiKeep;
32
+ }
33
+ const track = { lat: [], lon: [], frame: [] };
34
+ for (const i of keep) {
35
+ track.lat.push(lat[i]);
36
+ track.lon.push(lon[i]);
37
+ track.frame.push(i);
38
+ }
39
+ return track;
40
+ }
41
+ function douglasPeucker(px, epsilon) {
42
+ const n = px.length;
43
+ const keep = new Uint8Array(n);
44
+ keep[0] = 1;
45
+ keep[n - 1] = 1;
46
+ const stack = [0, n - 1];
47
+ while (stack.length > 0) {
48
+ const end = stack.pop();
49
+ const start = stack.pop();
50
+ if (end - start < 2)
51
+ continue;
52
+ const a = px[start];
53
+ const b = px[end];
54
+ const mid = (start + end) / 2;
55
+ let maxDist = -1;
56
+ let maxIdx = -1;
57
+ for (let i = start + 1; i < end; i++) {
58
+ const d = distanceToSegment(px[i], a, b);
59
+ if (d > maxDist ||
60
+ (d === maxDist && Math.abs(i - mid) < Math.abs(maxIdx - mid))) {
61
+ maxDist = d;
62
+ maxIdx = i;
63
+ }
64
+ }
65
+ if (maxDist > epsilon) {
66
+ keep[maxIdx] = 1;
67
+ stack.push(start, maxIdx, maxIdx, end);
68
+ }
69
+ }
70
+ const indices = [];
71
+ for (let i = 0; i < n; i++)
72
+ if (keep[i])
73
+ indices.push(i);
74
+ return indices;
75
+ }
76
+ function distanceToSegment(p, a, b) {
77
+ const dx = b.x - a.x;
78
+ const dy = b.y - a.y;
79
+ const lenSq = dx * dx + dy * dy;
80
+ if (lenSq === 0)
81
+ return Math.sqrt((p.x - a.x) ** 2 + (p.y - a.y) ** 2);
82
+ const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq));
83
+ return Math.sqrt((p.x - (a.x + t * dx)) ** 2 + (p.y - (a.y + t * dy)) ** 2);
84
+ }
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) {
@@ -4,4 +4,5 @@ interface ToolOutput {
4
4
  stderr: string;
5
5
  }
6
6
  export declare function runTool(command: string, args: readonly string[], opts?: ExecFileOptions): Promise<ToolOutput>;
7
+ export declare function runToolBinary(command: string, args: readonly string[], opts?: ExecFileOptions): Promise<Buffer>;
7
8
  export {};
package/dist/exec-tool.js CHANGED
@@ -3,7 +3,7 @@ import { promisify } from 'node:util';
3
3
  const execFileAsync = promisify(execFile);
4
4
  // One child-process seam for src/: command, argv and buffer budget pass
5
5
  // through untouched, and the spawned error propagates unwrapped so each
6
- // caller keeps its own { cause } wording. Tool output is text (utf8).
6
+ // caller keeps its own { cause } wording.
7
7
  // Hide the console window on Windows so GUI callers do not flash a terminal.
8
8
  export async function runTool(command, args, opts) {
9
9
  const result = await execFileAsync(command, args, { windowsHide: true, ...opts });
@@ -12,3 +12,7 @@ export async function runTool(command, args, opts) {
12
12
  stderr: String(result?.stderr ?? ''),
13
13
  };
14
14
  }
15
+ export async function runToolBinary(command, args, opts) {
16
+ const { stdout } = await execFileAsync(command, args, { windowsHide: true, ...opts, encoding: 'buffer' });
17
+ return stdout;
18
+ }
package/dist/ffmpeg.d.ts CHANGED
@@ -6,10 +6,23 @@ export interface VideoProbe {
6
6
  durationSec: number;
7
7
  width: number;
8
8
  height: number;
9
+ /** Original camera metadata. Its accuracy and time zone are unverified. */
10
+ creationTime?: string;
11
+ camMeta?: CamMetaStream | null;
9
12
  }
10
- export declare function requireFfmpegTools(tools: FfmpegToolPaths): Promise<void>;
11
- export declare function ffprobeJson(tools: FfmpegToolPaths, videoPath: string, args: string[]): Promise<Record<string, unknown>>;
13
+ export interface CamMetaStream {
14
+ index: number;
15
+ trackId?: number;
16
+ }
17
+ export declare function requireFfmpegTools(tools: FfmpegToolPaths, signal?: AbortSignal): Promise<void>;
18
+ export declare function ffprobeJson(tools: FfmpegToolPaths, videoPath: string, args: string[], signal?: AbortSignal): Promise<Record<string, unknown>>;
12
19
  interface ProbeStream {
20
+ index?: number;
21
+ id?: string;
22
+ codec_type?: string;
23
+ tags?: {
24
+ handler_name?: string;
25
+ };
13
26
  r_frame_rate?: string;
14
27
  avg_frame_rate?: string;
15
28
  nb_frames?: string;
@@ -17,5 +30,6 @@ interface ProbeStream {
17
30
  height?: number;
18
31
  }
19
32
  export declare function firstVideoStream(j: Record<string, unknown>): ProbeStream;
20
- export declare function probeVideo(tools: FfmpegToolPaths, videoPath: string, log?: (msg: string) => void): Promise<VideoProbe>;
33
+ export declare function findCamMetaStream(probe: Record<string, unknown>): CamMetaStream | null;
34
+ export declare function probeVideo(tools: FfmpegToolPaths, videoPath: string, log?: (msg: string) => void, signal?: AbortSignal): Promise<VideoProbe>;
21
35
  export {};
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';
@@ -7,37 +7,49 @@ const INSTALL_HINT = 'point --ffmpeg/--ffprobe at your executables, or install f
7
7
  '(Windows), "brew install ffmpeg" (macOS) or "apt install ffmpeg" (Linux)';
8
8
  const FFPROBE_MAX_BUFFER = 64 * 1024 * 1024;
9
9
  const TOOL_VERSION_MAX_BUFFER = 1 << 20;
10
- export async function requireFfmpegTools(tools) {
10
+ export async function requireFfmpegTools(tools, signal) {
11
11
  for (const tool of FFMPEG_TOOL_NAMES) {
12
12
  const command = tools[tool];
13
13
  try {
14
- await runTool(command, ['-version'], { maxBuffer: TOOL_VERSION_MAX_BUFFER });
14
+ await runTool(command, ['-version'], { maxBuffer: TOOL_VERSION_MAX_BUFFER, signal });
15
15
  }
16
16
  catch (e) {
17
17
  throw new Error(`${tool} is required but could not be run (${command}) - ${INSTALL_HINT}`, { cause: e });
18
18
  }
19
19
  }
20
20
  }
21
- export async function ffprobeJson(tools, videoPath, args) {
22
- const { stdout } = await runTool(tools.ffprobe, ['-v', 'error', ...args, videoPath], { maxBuffer: FFPROBE_MAX_BUFFER });
21
+ export async function ffprobeJson(tools, videoPath, args, signal) {
22
+ const { stdout } = await runTool(tools.ffprobe, ['-v', 'error', ...args, videoPath], { maxBuffer: FFPROBE_MAX_BUFFER, signal });
23
23
  return JSON.parse(stdout || '{}');
24
24
  }
25
25
  export function firstVideoStream(j) {
26
26
  return (j['streams'] ?? [])[0] ?? {};
27
27
  }
28
- export async function probeVideo(tools, videoPath, log = () => { }) {
28
+ export function findCamMetaStream(probe) {
29
+ const streams = (probe['streams'] ?? []);
30
+ const stream = streams.find(({ index, codec_type, tags }) => typeof index === 'number' && (codec_type === undefined || codec_type === 'data') &&
31
+ tags?.handler_name === 'CAM meta');
32
+ if (stream?.index === undefined)
33
+ return null;
34
+ const trackId = Number(stream.id);
35
+ return Number.isSafeInteger(trackId) && trackId > 0
36
+ ? { index: stream.index, trackId }
37
+ : { index: stream.index };
38
+ }
39
+ export async function probeVideo(tools, videoPath, log = () => { }, signal) {
29
40
  const j = await ffprobeJson(tools, videoPath, [
30
- '-select_streams', 'v:0',
31
41
  '-show_entries',
32
- 'stream=r_frame_rate,avg_frame_rate,nb_frames,width,height:format=duration',
42
+ 'stream=index,id,codec_type,r_frame_rate,avg_frame_rate,nb_frames,width,height' +
43
+ ':stream_tags=handler_name:format=duration:format_tags=creation_time',
33
44
  '-of', 'json',
34
- ]);
35
- const stream = firstVideoStream(j);
45
+ ], signal);
46
+ const streams = (j['streams'] ?? []);
47
+ const stream = streams.find(({ codec_type }) => codec_type === 'video') ?? {};
36
48
  const format = j['format'] ?? {};
37
49
  const fps = parseFpsRate(stream.r_frame_rate) ??
38
50
  parseFpsRate(stream.avg_frame_rate);
39
51
  if (!fps)
40
- throw new Error(ERR_NO_FRAME_RATE);
52
+ throw codedError(ERR_NO_FRAME_RATE, { code: 'NO_FRAME_RATE' });
41
53
  const durationSec = Number.parseFloat(format.duration ?? '');
42
54
  let frames = Number.parseInt(stream.nb_frames ?? '', 10);
43
55
  if (!Number.isFinite(frames) || frames <= 0) {
@@ -54,5 +66,7 @@ export async function probeVideo(tools, videoPath, log = () => { }) {
54
66
  durationSec,
55
67
  width: stream.width ?? 0,
56
68
  height: stream.height ?? 0,
69
+ creationTime: format.tags?.creation_time,
70
+ camMeta: findCamMetaStream(j),
57
71
  };
58
72
  }
@@ -0,0 +1,21 @@
1
+ import type { LatLon } from './geo.js';
2
+ interface TimedFix extends LatLon {
3
+ tSec: number;
4
+ }
5
+ export interface FlightClip {
6
+ key: string;
7
+ size: number;
8
+ startMs: number | null;
9
+ durationSec: number | null;
10
+ firstFix?: TimedFix;
11
+ lastFix?: TimedFix;
12
+ }
13
+ export interface FlightMembership {
14
+ key: string;
15
+ flightId: string;
16
+ order: number;
17
+ splitFromKey: string | null;
18
+ }
19
+ /** Infer flights from the available camera tags and GPS fixes in one library snapshot. */
20
+ export declare function groupFlights(clips: readonly FlightClip[]): FlightMembership[];
21
+ export {};
@@ -0,0 +1,104 @@
1
+ import { createHash } from 'node:crypto';
2
+ import path from 'node:path';
3
+ import { haversineM } from './geo.js';
4
+ const SPLIT_MIN_BYTES = 3_800_000_000;
5
+ const SPLIT_MAX_BYTES = 4_300_000_000;
6
+ // MP4 creation tags may have only whole-second precision.
7
+ const CLOCK_TOLERANCE_MS = 1000;
8
+ function groupableClip(clip) {
9
+ const { key, startMs, durationSec } = clip;
10
+ if (startMs === null || durationSec === null || !Number.isFinite(startMs) ||
11
+ !Number.isFinite(durationSec) || durationSec <= 0)
12
+ return null;
13
+ const name = path.basename(key);
14
+ const legacy = /^DJI_(\d{4})\.mp4$/iu.exec(name);
15
+ const fly = /^dji_fly_\d{8}_\d{6}_(\d{4})_\d+_video\.mp4$/iu.exec(name);
16
+ const match = legacy ?? fly;
17
+ if (!match)
18
+ return null;
19
+ return {
20
+ ...clip, startMs, endMs: startMs + durationSec * 1000,
21
+ sequence: Number(match[1]),
22
+ stream: JSON.stringify([path.dirname(key), legacy ? 'dji' : 'dji_fly']),
23
+ };
24
+ }
25
+ function newFlight(key) {
26
+ const id = createHash('sha256').update(key).digest('hex');
27
+ return { key, flightId: id, order: 0, splitFromKey: null };
28
+ }
29
+ function continuation(previous, next, launch) {
30
+ const { firstFix: previousStart, lastFix } = previous;
31
+ const { firstFix: nextStart } = next;
32
+ const remainingSec = (previous.endMs - previous.startMs) / 1000 - (lastFix?.tSec ?? 0);
33
+ if (!launch || !previousStart || !lastFix || !nextStart ||
34
+ previousStart.tSec > 5 || nextStart.tSec > 5 || remainingSec < -1 || remainingSec > 5)
35
+ return null;
36
+ const gap = next.startMs - previous.endMs;
37
+ if (gap < -CLOCK_TOLERANCE_MS || next.startMs === previous.startMs ||
38
+ next.sequence !== (previous.sequence + 1) % 10_000)
39
+ return null;
40
+ const distance = haversineM(lastFix, nextStart);
41
+ if (previous.size >= SPLIT_MIN_BYTES && previous.size <= SPLIT_MAX_BYTES &&
42
+ gap <= 3000 && distance <= 30 && remainingSec <= 2 && nextStart.tSec <= 2)
43
+ return 'split';
44
+ // A return to the first clip's start can mark a landing or battery change.
45
+ if (gap <= 45_000 && distance <= 100 && haversineM(launch, lastFix) > 12 &&
46
+ (gap <= 10_000 || haversineM(launch, nextStart) <= 150))
47
+ return 'flight';
48
+ return null;
49
+ }
50
+ function competingClips(clips) {
51
+ const competing = new Set();
52
+ let latestEnding = clips[0];
53
+ for (const clip of clips.slice(1)) {
54
+ if (clip.startMs === latestEnding.startMs || clip.startMs < latestEnding.endMs - CLOCK_TOLERANCE_MS) {
55
+ competing.add(clip.key);
56
+ competing.add(latestEnding.key);
57
+ }
58
+ if (clip.endMs > latestEnding.endMs)
59
+ latestEnding = clip;
60
+ }
61
+ return competing;
62
+ }
63
+ function groupStream(clips, memberships) {
64
+ clips.sort((a, b) => a.startMs - b.startMs || compareKeys(a.key, b.key));
65
+ const competing = competingClips(clips);
66
+ let launch = clips[0].firstFix;
67
+ for (const [index, clip] of clips.entries()) {
68
+ const previous = clips[index - 1];
69
+ const link = previous && !competing.has(previous.key) && !competing.has(clip.key)
70
+ ? continuation(previous, clip, launch)
71
+ : null;
72
+ if (link) {
73
+ const prior = memberships.get(previous.key);
74
+ memberships.set(clip.key, {
75
+ key: clip.key, flightId: prior.flightId, order: prior.order + 1,
76
+ splitFromKey: link === 'split' ? previous.key : null,
77
+ });
78
+ }
79
+ else {
80
+ launch = clip.firstFix;
81
+ }
82
+ }
83
+ }
84
+ function compareKeys(a, b) {
85
+ return a < b ? -1 : a > b ? 1 : 0;
86
+ }
87
+ /** Infer flights from the available camera tags and GPS fixes in one library snapshot. */
88
+ export function groupFlights(clips) {
89
+ const memberships = new Map(clips.map(({ key }) => [key, newFlight(key)]));
90
+ const streams = new Map();
91
+ for (const clip of clips) {
92
+ const candidate = groupableClip(clip);
93
+ if (!candidate)
94
+ continue;
95
+ const stream = streams.get(candidate.stream);
96
+ if (stream)
97
+ stream.push(candidate);
98
+ else
99
+ streams.set(candidate.stream, [candidate]);
100
+ }
101
+ for (const stream of streams.values())
102
+ groupStream(stream, memberships);
103
+ return [...memberships.values()].sort((a, b) => compareKeys(a.key, b.key));
104
+ }
package/dist/geo.d.ts CHANGED
@@ -12,6 +12,9 @@ export interface MercatorPixel {
12
12
  x: number;
13
13
  y: number;
14
14
  }
15
+ export declare const EARTH_RADIUS_M = 6371008.8;
16
+ export declare const DEG_TO_RAD: number;
17
+ export declare const RAD_TO_DEG: number;
15
18
  export declare function isGpsFix(lat: number, lon: number): boolean;
16
19
  export declare function gpsFixOrNull(lat: number | null, lon: number | null): LatLon | null;
17
20
  export declare function haversineM(a: LatLon, b: LatLon): number;
package/dist/geo.js CHANGED
@@ -1,6 +1,6 @@
1
- const EARTH_RADIUS_M = 6371008.8;
2
- const DEG_TO_RAD = Math.PI / 180;
3
- const RAD_TO_DEG = 180 / Math.PI;
1
+ export const EARTH_RADIUS_M = 6371008.8;
2
+ export const DEG_TO_RAD = Math.PI / 180;
3
+ export const RAD_TO_DEG = 180 / Math.PI;
4
4
  // (0, 0) is DJI's "no GPS lock" placeholder before the first fix, not a real fix.
5
5
  export function isGpsFix(lat, lon) {
6
6
  return (Number.isFinite(lat) &&
@@ -0,0 +1,18 @@
1
+ import type { Bbox, LatLon } from './geo.js';
2
+ export declare const DEFAULT_CAMERA_FOV: {
3
+ readonly horizontalDeg: 75;
4
+ readonly verticalDeg: 50;
5
+ };
6
+ export interface GroundCamera extends LatLon {
7
+ altitudeM: number;
8
+ pitchDeg: number;
9
+ yawDeg: number;
10
+ rollDeg?: number;
11
+ }
12
+ export type GroundFootprint = LatLon[];
13
+ export declare function projectGroundFootprint(camera: GroundCamera, fov?: {
14
+ horizontalDeg: number;
15
+ verticalDeg: number;
16
+ }): GroundFootprint | null;
17
+ export declare function footprintBbox(polygon: readonly LatLon[]): Bbox;
18
+ export declare function footprintContains(polygon: GroundFootprint, point: LatLon): boolean;