drone-path-archive 0.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 ADDED
@@ -0,0 +1,36 @@
1
+ # drone-path-archive
2
+
3
+ Index and query a local library of DJI drone recordings. This package owns
4
+ recording discovery, the SQLite archive store, flight grouping, spatial and
5
+ camera-gaze search, kinematic shot-segment queries, and combined HTML map and
6
+ track exports. It uses `drone-path-core` for telemetry extraction and spatial
7
+ math.
8
+
9
+ ```sh
10
+ npm install drone-path-archive
11
+ ```
12
+
13
+ Use the module subpaths in Node.js 24 or later.
14
+
15
+ ```js
16
+ import { scanArchive } from 'drone-path-archive/indexed-scan';
17
+ import { listArchive, nearArchive } from 'drone-path-archive/query';
18
+ ```
19
+
20
+ Each module ships TypeScript declarations.
21
+
22
+ Install `@types/node` for your Node.js major version. In TypeScript 6, list
23
+ `node` in `compilerOptions.types` to load the Node declarations.
24
+
25
+ ```json
26
+ {
27
+ "compilerOptions": {
28
+ "module": "NodeNext",
29
+ "types": ["node"]
30
+ }
31
+ }
32
+ ```
33
+
34
+ See the [project manual](https://github.com/MrManny/drone-path/tree/main/docs/user)
35
+ for archive indexing, search filters, and export formats. Install `drone-path`
36
+ for the command-line interface.
package/dist/export.d.ts CHANGED
@@ -6,4 +6,7 @@ interface ExportOptions {
6
6
  }
7
7
  export declare function exportArchiveMap(db: string, output: string, options?: ExportOptions): void;
8
8
  export declare function exportArchiveTracks(db: string, output: string, options?: Omit<ExportOptions, 'includeGaze'>): void;
9
+ export declare function exportArchiveMarkers(db: string, output: string, options?: {
10
+ filters?: ListFilters;
11
+ }): void;
9
12
  export {};
package/dist/export.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { launchRedactor } from 'drone-path-core/launch-redaction';
4
+ import { markerFormatOf, serializeDaVinciResolveCsv, serializeFcpxmlMarkers, } from 'drone-path-core/nle-markers';
4
5
  import { splitTrackAtAntimeridian } from 'drone-path-core/track-antimeridian';
5
6
  import { trackFormatOf } from 'drone-path-core/track-format';
6
7
  import { serializeGeoJsonTracks } from 'drone-path-core/track-geojson';
@@ -9,16 +10,16 @@ import { serializeKmlTracks } from 'drone-path-core/track-kml';
9
10
  import { kmzBytes } from 'drone-path-core/track-kmz';
10
11
  import { archiveMapHtml } from './export-map.js';
11
12
  import { groupFlightMembers } from './flight-members.js';
12
- import { matchesMetadata } from './query.js';
13
- import { ArchiveStore } from './store.js';
13
+ import { listArchiveSegments, matchesMetadata, segmentFilterOf } from './query.js';
14
+ import { withArchiveStore } from './store.js';
14
15
  function exportFlights(db, { filters = {}, redactLaunchM = 0, includeGaze = false }, splitDateline = false) {
15
16
  if (!Number.isFinite(redactLaunchM) || redactLaunchM < 0) {
16
17
  throw new Error('expected a nonnegative launch redaction radius in meters');
17
18
  }
18
19
  const redact = redactLaunchM > 0;
19
- const store = new ArchiveStore(db);
20
- try {
21
- const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record }) => matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact });
20
+ const segmentFilter = segmentFilterOf(filters);
21
+ return withArchiveStore(db, (store) => {
22
+ const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record }) => matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact }, segmentFilter);
22
23
  const redactTrack = launchRedactor(endpoints, redactLaunchM);
23
24
  const flights = groupFlightMembers(clips);
24
25
  return [...flights.values()].flatMap((members) => {
@@ -36,10 +37,7 @@ function exportFlights(db, { filters = {}, redactLaunchM = 0, includeGaze = fals
36
37
  });
37
38
  return selected.length > 0 ? [{ clips: selected }] : [];
38
39
  });
39
- }
40
- finally {
41
- store.close();
42
- }
40
+ });
43
41
  }
44
42
  function writeExport(db, output, content) {
45
43
  const resolved = (file) => fs.existsSync(file) ? fs.realpathSync(file) : path.resolve(file);
@@ -76,3 +74,39 @@ export function exportArchiveTracks(db, output, options = {}) {
76
74
  case 'kmz': return writeExport(db, output, kmzBytes(serializeKmlTracks(tracks)));
77
75
  }
78
76
  }
77
+ function segmentToMarkerRange(segment) {
78
+ const video = segment.clip.video;
79
+ if (!video ||
80
+ video.durationSec === null ||
81
+ !Number.isFinite(video.durationSec) ||
82
+ video.durationSec <= 0 ||
83
+ !Number.isFinite(video.fps.value) ||
84
+ video.fps.value <= 0) {
85
+ throw new Error(`clip ${segment.clip.path} is missing video timing metadata for marker export`);
86
+ }
87
+ const durationSec = video.durationSec;
88
+ const startSec = Math.max(0, Math.min(durationSec, segment.startSec));
89
+ const endSec = Math.max(startSec, Math.min(durationSec, segment.endSec));
90
+ const clipName = segment.clip.path.split(/[\\/]/u).at(-1);
91
+ return {
92
+ clipPath: segment.clip.path,
93
+ ...(clipName ? { clipName } : {}),
94
+ fps: video.fps,
95
+ durationSec,
96
+ startSec,
97
+ endSec,
98
+ label: segment.type,
99
+ note: `smoothness ${segment.smoothness.toFixed(3)}, ` +
100
+ `speed ${segment.meanSpeedMps.toFixed(2)} m/s, ` +
101
+ `yawRate ${segment.meanYawRateDegPerSec.toFixed(2)} deg/s`,
102
+ };
103
+ }
104
+ export function exportArchiveMarkers(db, output, options = {}) {
105
+ const format = markerFormatOf(output);
106
+ const segments = listArchiveSegments(db, options.filters);
107
+ const markers = segments.map(segmentToMarkerRange);
108
+ const content = format === 'csv'
109
+ ? serializeDaVinciResolveCsv(markers)
110
+ : serializeFcpxmlMarkers(markers);
111
+ writeExport(db, output, content);
112
+ }
@@ -1,6 +1,6 @@
1
1
  import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
2
2
  import type { ScanOptions, ScanRecord } from './scanner.js';
3
- export interface IndexedScanOptions extends Omit<ScanOptions, 'tools' | 'sidecarFor' | 'onTrack' | 'onGaze'> {
3
+ export interface IndexedScanOptions extends Omit<ScanOptions, 'tools' | 'sidecarFor' | 'onTrack' | 'onGaze' | 'onSegments'> {
4
4
  db: string;
5
5
  prune?: boolean;
6
6
  getTools: () => Promise<FfmpegToolPaths>;
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
  import { createSrtSidecarLookup } from 'drone-path-core/srt-sidecar';
4
4
  import { decimateSegments, sampleSegments } from './scan-track.js';
5
5
  import { discoverRecordings, scanRecordings } from './scanner.js';
6
- import { ArchiveStore, CLIP_FINGERPRINT_VERSION } from './store.js';
6
+ import { CLIP_FINGERPRINT_VERSION, withArchiveStoreAsync } from './store.js';
7
7
  function isMissing(error) {
8
8
  const code = error?.code;
9
9
  return code === 'ENOENT' || code === 'ENOTDIR';
@@ -75,13 +75,7 @@ async function scanRoots(dirs, indexedPaths, { prune, recurse, signal }) {
75
75
  return { roots, present };
76
76
  }
77
77
  export async function scanArchive(dirs, options) {
78
- const store = new ArchiveStore(options.db);
79
- try {
80
- return await indexFolders(store, dirs, options);
81
- }
82
- finally {
83
- store.close();
84
- }
78
+ return withArchiveStoreAsync(options.db, (store) => indexFolders(store, dirs, options));
85
79
  }
86
80
  async function indexFolders(store, dirs, options) {
87
81
  const { signal, recurse, prune, onRecord } = options;
@@ -106,7 +100,8 @@ async function indexFolders(store, dirs, options) {
106
100
  seen.add(key);
107
101
  const prior = previous.get(key);
108
102
  const unchanged = prior && matches(current.fingerprint, prior.fingerprint);
109
- if (unchanged && !prior.gazePending && prior.record.status !== 'error') {
103
+ const needsBackfill = prior !== undefined && (prior.gazePending || prior.segmentsPending);
104
+ if (unchanged && !needsBackfill && prior.record.status !== 'error') {
110
105
  records.set(file, prior.record);
111
106
  onRecord?.(prior.record);
112
107
  if (prior.availability === 'offline')
@@ -114,7 +109,7 @@ async function indexFolders(store, dirs, options) {
114
109
  }
115
110
  else {
116
111
  pending.set(file, current);
117
- if (unchanged && prior.gazePending) {
112
+ if (unchanged && needsBackfill) {
118
113
  backfills.add(file);
119
114
  if (prior.availability === 'offline')
120
115
  online.push(key);
@@ -148,11 +143,13 @@ async function probeChanges(pending, { concurrency, signal, getTools, onRecord }
148
143
  return [];
149
144
  const tracks = new Map();
150
145
  const gaze = new Map();
146
+ const segmentsByFile = new Map();
151
147
  const tools = await getTools();
152
148
  const scanned = await scanRecordings([...pending.keys()], {
153
149
  tools, concurrency, signal, onRecord,
154
150
  sidecarFor: (file) => pending.get(file)?.sidecar,
155
151
  onGaze: (file, samples) => gaze.set(file, samples),
152
+ onSegments: (file, shots) => segmentsByFile.set(file, shots),
156
153
  onTrack: (file, segments) => {
157
154
  tracks.set(file, { overview: decimateSegments(segments, 60, 9), samples: sampleSegments(segments) });
158
155
  },
@@ -170,6 +167,7 @@ async function probeChanges(pending, { concurrency, signal, getTools, onRecord }
170
167
  key: clipKey(record.path), availability: 'online', fingerprint: original.fingerprint, record,
171
168
  ...tracks.get(record.path) ?? { overview: [], samples: [] },
172
169
  gaze: gaze.get(record.path),
170
+ segments: segmentsByFile.get(record.path),
173
171
  });
174
172
  }
175
173
  return updates;
package/dist/query.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Bbox, LatLon } from 'drone-path-core/geo';
2
+ import type { KinematicShot, ShotType } from 'drone-path-core/shot-segmentation';
2
3
  import type { ScanRecord } from './scanner.js';
3
- import type { IndexedClip } from './store.js';
4
+ import type { IndexedClip, SegmentFilter } from './store.js';
4
5
  export { parseDateBound } from './camera-time.js';
5
6
  export declare const DEFAULT_RADIUS_M = 100;
6
7
  export type ArchiveAvailability = IndexedClip['availability'];
@@ -20,6 +21,11 @@ export interface ListFilters {
20
21
  beforeMs?: number;
21
22
  minDistanceM?: number;
22
23
  availability?: ArchiveAvailability;
24
+ segmentType?: ShotType;
25
+ minSmoothness?: number;
26
+ }
27
+ export interface ArchiveSegment extends KinematicShot {
28
+ clip: ArchiveClip;
23
29
  }
24
30
  export interface NearHit {
25
31
  clip: ArchiveClip;
@@ -27,7 +33,9 @@ export interface NearHit {
27
33
  distanceM: number;
28
34
  matchType: 'track' | 'gaze';
29
35
  }
36
+ export declare function segmentFilterOf({ segmentType, minSmoothness }: ListFilters): SegmentFilter | undefined;
30
37
  export declare function matchesMetadata(clip: ScanRecord, { afterMs, beforeMs, minDistanceM }: ListFilters): boolean;
31
38
  export declare function listArchive(db: string, filters?: ListFilters): ArchiveClip[];
32
39
  export declare function listArchiveFlights(db: string, filters?: ListFilters): ArchiveFlight[];
40
+ export declare function listArchiveSegments(db: string, filters?: ListFilters): ArchiveSegment[];
33
41
  export declare function nearArchive(db: string, point: LatLon, radiusM?: number, includeGaze?: boolean): NearHit[];
package/dist/query.js CHANGED
@@ -3,9 +3,17 @@ import { nearestOnTrack, radiusBbox } from 'drone-path-core/spatial';
3
3
  import { zonedTimeMs } from './camera-time.js';
4
4
  import { groupFlightMembers } from './flight-members.js';
5
5
  import { groupSamples } from './scan-track.js';
6
- import { ArchiveStore } from './store.js';
6
+ import { withArchiveStore } from './store.js';
7
7
  export { parseDateBound } from './camera-time.js';
8
8
  export const DEFAULT_RADIUS_M = 100;
9
+ export function segmentFilterOf({ segmentType, minSmoothness }) {
10
+ if (minSmoothness !== undefined && (!Number.isFinite(minSmoothness) || minSmoothness < 0 || minSmoothness > 1)) {
11
+ throw new Error('expected a smoothness score between 0 and 1');
12
+ }
13
+ if (segmentType === undefined && minSmoothness === undefined)
14
+ return undefined;
15
+ return { segmentType, minSmoothness };
16
+ }
9
17
  export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM }) {
10
18
  if (minDistanceM !== undefined &&
11
19
  (clip.telemetry === null || clip.telemetry.trackDistanceM < minDistanceM))
@@ -21,16 +29,11 @@ function toClip({ record, availability }) {
21
29
  return { ...record, availability };
22
30
  }
23
31
  function matchingClips(db, filters) {
24
- const store = new ArchiveStore(db);
25
- try {
26
- return store.listClips(filters.bbox, filters.availability).flatMap((indexed) => {
27
- const clip = toClip(indexed);
28
- return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
29
- });
30
- }
31
- finally {
32
- store.close();
33
- }
32
+ const segmentFilter = segmentFilterOf(filters);
33
+ return withArchiveStore(db, (store) => store.listClips(filters.bbox, filters.availability, segmentFilter).flatMap((indexed) => {
34
+ const clip = toClip(indexed);
35
+ return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
36
+ }));
34
37
  }
35
38
  export function listArchive(db, filters = {}) {
36
39
  return matchingClips(db, filters).map(({ clip }) => clip);
@@ -41,9 +44,20 @@ export function listArchiveFlights(db, filters = {}) {
41
44
  flightId, clips: members.map(({ clip, flight }) => ({ ...clip, splitFromKey: flight.splitFromKey })),
42
45
  }));
43
46
  }
47
+ export function listArchiveSegments(db, filters = {}) {
48
+ const segmentFilter = segmentFilterOf(filters);
49
+ return withArchiveStore(db, (store) => store.listSegments({
50
+ bbox: filters.bbox,
51
+ availability: filters.availability,
52
+ segmentType: segmentFilter?.segmentType,
53
+ minSmoothness: segmentFilter?.minSmoothness,
54
+ }).flatMap(({ clip: indexed, segment }) => {
55
+ const clip = toClip(indexed);
56
+ return matchesMetadata(clip, filters) ? [{ clip, ...segment }] : [];
57
+ }));
58
+ }
44
59
  export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze = false) {
45
- const store = new ArchiveStore(db);
46
- try {
60
+ return withArchiveStore(db, (store) => {
47
61
  const hits = [];
48
62
  const { tracks, gaze } = store.readNearCandidates(radiusBbox(point, radiusM), includeGaze ? point : undefined);
49
63
  for (const { clip, samples } of tracks) {
@@ -59,8 +73,5 @@ export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze =
59
73
  }
60
74
  // Stable sorting preserves clip-key order within each match type for equal distances.
61
75
  return hits.sort((a, b) => a.distanceM - b.distanceM);
62
- }
63
- finally {
64
- store.close();
65
- }
76
+ });
66
77
  }
package/dist/scanner.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { VideoProbe } from 'drone-path-core/ffmpeg';
2
2
  import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
3
3
  import type { Bbox } from 'drone-path-core/geo';
4
+ import type { KinematicShot } from 'drone-path-core/shot-segmentation';
4
5
  import type { SourceSamples } from 'drone-path-core/telemetry';
5
6
  import type { GazeSample } from './gaze.js';
6
7
  import type { ScanPoint } from './scan-track.js';
@@ -36,9 +37,10 @@ export interface ScanOptions {
36
37
  onRecord?: (record: ScanRecord) => void;
37
38
  onTrack?: (file: string, segments: ScanPoint[][]) => void;
38
39
  onGaze?: (file: string, samples: GazeSample[]) => void;
40
+ onSegments?: (file: string, segments: KinematicShot[]) => void;
39
41
  }
40
42
  export declare function discoverRecordings(dirs: readonly string[], { recurse, signal }?: Pick<ScanOptions, 'recurse' | 'signal'>): Promise<string[]>;
41
- export declare function scanRecording(file: string, { tools, signal, sidecarFor, onTrack, onGaze }: Pick<ScanOptions, 'tools' | 'signal' | 'sidecarFor' | 'onTrack' | 'onGaze'>): Promise<ScanRecord>;
43
+ export declare function scanRecording(file: string, { tools, signal, sidecarFor, onTrack, onGaze, onSegments }: Pick<ScanOptions, 'tools' | 'signal' | 'sidecarFor' | 'onTrack' | 'onGaze' | 'onSegments'>): Promise<ScanRecord>;
42
44
  export declare function scanFolders(dirs: readonly string[], options: ScanOptions): Promise<ScanRecord[]>;
43
45
  export declare function scanRecordings(files: readonly string[], options: ScanOptions): Promise<ScanRecord[]>;
44
46
  export {};
package/dist/scanner.js CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import PQueue from 'p-queue';
4
4
  import { errorMessage } from 'drone-path-core/errors';
5
5
  import { probeVideo } from 'drone-path-core/ffmpeg';
6
+ import { segmentFlightShots } from 'drone-path-core/shot-segmentation';
6
7
  import { loadTelemetrySamples } from 'drone-path-core/telemetry';
7
8
  import { sampleGaze } from './gaze.js';
8
9
  import { summarizeTrack } from './scan-track.js';
@@ -33,7 +34,7 @@ export async function discoverRecordings(dirs, { recurse, signal } = {}) {
33
34
  }
34
35
  return found.sort();
35
36
  }
36
- export async function scanRecording(file, { tools, signal, sidecarFor, onTrack, onGaze }) {
37
+ export async function scanRecording(file, { tools, signal, sidecarFor, onTrack, onGaze, onSegments }) {
37
38
  signal?.throwIfAborted();
38
39
  const record = {
39
40
  path: file, size: null, mtimeMs: null, status: 'error', video: null,
@@ -64,6 +65,8 @@ export async function scanRecording(file, { tools, signal, sidecarFor, onTrack,
64
65
  record.telemetry = { source: loaded.source, method: loaded.method, fixCount, noLock: loaded.noLock, trackDistanceM };
65
66
  if (onGaze && loaded.method === 'dvtm-packets')
66
67
  onGaze(file, sampleGaze(loaded.trackValues));
68
+ if (onSegments && fixCount > 0)
69
+ onSegments(file, segmentFlightShots(loaded.trackValues));
67
70
  record.status = fixCount > 0 ? 'ok' : 'no-gps';
68
71
  }
69
72
  catch (error) {
package/dist/store.d.ts CHANGED
@@ -1,10 +1,15 @@
1
1
  import type { FlightMembership } from 'drone-path-core/flight-grouping';
2
2
  import type { Bbox, LatLon } from 'drone-path-core/geo';
3
+ import type { KinematicShot, ShotType } from 'drone-path-core/shot-segmentation';
3
4
  import type { GazeSample } from './gaze.js';
4
5
  import type { ScanPoint, SparseSample } from './scan-track.js';
5
6
  import type { ScanRecord } from './scanner.js';
6
- export declare const ARCHIVE_SCHEMA_VERSION = 3;
7
+ export declare const ARCHIVE_SCHEMA_VERSION = 4;
7
8
  export declare const CLIP_FINGERPRINT_VERSION = 1;
9
+ export interface SegmentFilter {
10
+ segmentType?: ShotType;
11
+ minSmoothness?: number;
12
+ }
8
13
  export interface ClipFingerprint {
9
14
  size: number;
10
15
  mtimeMs: number;
@@ -22,6 +27,7 @@ export interface ClipUpdate extends IndexedClip {
22
27
  overview: ScanPoint[][];
23
28
  samples: SparseSample[];
24
29
  gaze?: GazeSample[];
30
+ segments?: KinematicShot[];
25
31
  }
26
32
  export interface IndexedFlightClip extends IndexedClip {
27
33
  flight: FlightMembership;
@@ -36,14 +42,16 @@ export declare class ArchiveStore {
36
42
  revision: number;
37
43
  clips: (IndexedClip & {
38
44
  gazePending: boolean;
45
+ segmentsPending: boolean;
39
46
  })[];
40
47
  };
41
- listClips(bbox?: Bbox, availability?: IndexedClip['availability']): IndexedFlightClip[];
48
+ listClips(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
49
+ private clipMatchesViewport;
42
50
  private selectClipViewport;
43
51
  readExportCandidates(bbox: Bbox | undefined, availability: IndexedClip['availability'] | undefined, matches: (clip: IndexedClip) => boolean, options: {
44
52
  includeGaze: boolean;
45
53
  redact: boolean;
46
- }): {
54
+ }, segmentFilter?: SegmentFilter): {
47
55
  endpoints: LatLon[];
48
56
  clips: {
49
57
  gaze: GazeSample[];
@@ -72,11 +80,25 @@ export declare class ArchiveStore {
72
80
  private selectGazeCandidates;
73
81
  readOverview(key: string): ScanPoint[][];
74
82
  readSamples(key: string): SparseSample[];
83
+ readSegments(key: string): KinematicShot[];
84
+ listSegments(filters?: {
85
+ bbox?: Bbox;
86
+ availability?: IndexedClip['availability'];
87
+ segmentType?: ShotType;
88
+ minSmoothness?: number;
89
+ }): {
90
+ clip: IndexedClip;
91
+ segment: KinematicShot;
92
+ }[];
75
93
  commit(expectedRevision: number, updates: readonly ClipUpdate[], online: readonly string[], offline: readonly string[], removed: readonly string[]): void;
76
94
  private revision;
95
+ private clipFilterClauses;
77
96
  private selectClips;
78
97
  private refreshFlights;
79
98
  private transaction;
80
99
  private writeClip;
81
100
  private writeGaze;
101
+ private writeSegments;
82
102
  }
103
+ export declare function withArchiveStore<T>(db: string, run: (store: ArchiveStore) => T): T;
104
+ export declare function withArchiveStoreAsync<T>(db: string, run: (store: ArchiveStore) => Promise<T>): Promise<T>;
package/dist/store.js CHANGED
@@ -6,7 +6,7 @@ import { bboxIntersects, longitudeRanges, resolveTrackBbox } from 'drone-path-co
6
6
  import { zonedTimeMs } from './camera-time.js';
7
7
  import { gazeBbox } from './gaze.js';
8
8
  import { groupSamples } from './scan-track.js';
9
- export const ARCHIVE_SCHEMA_VERSION = 3;
9
+ export const ARCHIVE_SCHEMA_VERSION = 4;
10
10
  export const CLIP_FINGERPRINT_VERSION = 1;
11
11
  function decodeClip(row) {
12
12
  return {
@@ -28,6 +28,18 @@ function decodeFlightClip(row) {
28
28
  },
29
29
  };
30
30
  }
31
+ function decodeSegment(row) {
32
+ return {
33
+ type: row.segment_type,
34
+ startSec: row.start_sec,
35
+ endSec: row.end_sec,
36
+ durationSec: row.duration_sec,
37
+ smoothness: row.smoothness,
38
+ exposureStable: row.exposure_stable === 1,
39
+ meanSpeedMps: row.mean_speed_mps,
40
+ meanYawRateDegPerSec: row.mean_yaw_rate_deg_per_sec,
41
+ };
42
+ }
31
43
  const SCHEMA = `
32
44
  CREATE TABLE archive_revision (revision INTEGER NOT NULL) STRICT;
33
45
  INSERT INTO archive_revision VALUES (0);
@@ -44,7 +56,8 @@ const SCHEMA = `
44
56
  max_lat REAL,
45
57
  max_lon REAL,
46
58
  record_json TEXT NOT NULL,
47
- overview_json TEXT NOT NULL
59
+ overview_json TEXT NOT NULL,
60
+ segments_indexed INTEGER NOT NULL DEFAULT 0
48
61
  ) STRICT;
49
62
  CREATE INDEX clips_bbox ON clips (min_lat, max_lat, min_lon, max_lon);
50
63
  CREATE TABLE clip_samples (
@@ -76,6 +89,22 @@ const GAZE_SCHEMA = `
76
89
  ) STRICT;
77
90
  CREATE INDEX clip_gaze_bbox ON clip_gaze (min_lat, max_lat, min_lon, max_lon);
78
91
  `;
92
+ const SEGMENTS_SCHEMA = `
93
+ CREATE TABLE IF NOT EXISTS segments (
94
+ clip_key TEXT NOT NULL REFERENCES clips (clip_key) ON DELETE CASCADE,
95
+ segment_index INTEGER NOT NULL,
96
+ segment_type TEXT NOT NULL,
97
+ start_sec REAL NOT NULL,
98
+ end_sec REAL NOT NULL,
99
+ duration_sec REAL NOT NULL,
100
+ smoothness REAL NOT NULL,
101
+ exposure_stable INTEGER NOT NULL,
102
+ mean_speed_mps REAL NOT NULL,
103
+ mean_yaw_rate_deg_per_sec REAL NOT NULL,
104
+ PRIMARY KEY (clip_key, segment_index)
105
+ ) STRICT;
106
+ CREATE INDEX IF NOT EXISTS segments_type_smoothness ON segments (segment_type, smoothness DESC);
107
+ `;
79
108
  export class ArchiveStore {
80
109
  db;
81
110
  constructor(file) {
@@ -101,20 +130,30 @@ export class ArchiveStore {
101
130
  const version = this.schemaVersion();
102
131
  if (version === ARCHIVE_SCHEMA_VERSION)
103
132
  return;
133
+ if (typeof version !== 'number' || !Number.isInteger(version) || version < 0 || version > ARCHIVE_SCHEMA_VERSION) {
134
+ throw new Error(`unsupported archive database schema version: ${String(version)}`);
135
+ }
104
136
  if (version === 0) {
105
137
  if (this.db.prepare('SELECT 1 FROM sqlite_schema LIMIT 1').get()) {
106
138
  throw new Error('existing database has no archive schema');
107
139
  }
108
140
  this.db.exec(SCHEMA);
109
141
  }
110
- else if (version !== 1 && version !== 2) {
111
- throw new Error(`unsupported archive database schema version: ${String(version)}`);
112
- }
113
- if (version === 0 || version === 1) {
142
+ if (version < 2) {
114
143
  this.db.exec(FLIGHT_SCHEMA);
115
- this.refreshFlights();
144
+ if (version === 1)
145
+ this.refreshFlights();
146
+ }
147
+ if (version < 3) {
148
+ this.db.exec(GAZE_SCHEMA);
149
+ }
150
+ if (version < 4) {
151
+ const columns = this.db.prepare('PRAGMA table_info(clips)').all();
152
+ if (!columns.some((col) => col.name === 'segments_indexed')) {
153
+ this.db.exec('ALTER TABLE clips ADD COLUMN segments_indexed INTEGER NOT NULL DEFAULT 0');
154
+ }
155
+ this.db.exec(SEGMENTS_SCHEMA);
116
156
  }
117
- this.db.exec(GAZE_SCHEMA);
118
157
  this.db.exec(`PRAGMA user_version = ${ARCHIVE_SCHEMA_VERSION}`);
119
158
  });
120
159
  }
@@ -125,33 +164,41 @@ export class ArchiveStore {
125
164
  return this.transaction('BEGIN', () => ({
126
165
  revision: this.revision(),
127
166
  clips: this.db.prepare(`
128
- SELECT clips.*, clip_gaze.clip_key IS NULL AND
129
- json_extract(record_json, '$.telemetry.method') IS 'dvtm-packets' AS gaze_pending
167
+ SELECT clips.*,
168
+ clip_gaze.clip_key IS NULL AND
169
+ json_extract(record_json, '$.telemetry.method') IS 'dvtm-packets' AS gaze_pending,
170
+ segments_indexed = 0 AND
171
+ json_extract(record_json, '$.status') IS 'ok' AS segments_pending
130
172
  FROM clips LEFT JOIN clip_gaze USING (clip_key) ORDER BY clip_key
131
173
  `).all().map((row) => ({
132
- ...decodeClip(row), gazePending: row.gaze_pending === 1,
174
+ ...decodeClip(row),
175
+ gazePending: row.gaze_pending === 1,
176
+ segmentsPending: row.segments_pending === 1,
133
177
  })),
134
178
  }));
135
179
  }
136
- listClips(bbox, availability) {
180
+ listClips(bbox, availability, segmentFilter) {
137
181
  if (bbox === undefined)
138
- return this.selectClips(undefined, availability, false);
139
- return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability));
182
+ return this.selectClips(undefined, availability, false, segmentFilter);
183
+ return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter));
140
184
  }
141
- selectClipViewport(bbox, availability) {
142
- return this.selectClips(bbox, availability, false).filter(({ key, record }) => {
143
- const raw = record.bbox;
144
- if (raw === null)
145
- return false;
146
- if (raw.maxLon - raw.minLon <= 180)
147
- return true;
148
- return bboxIntersects(bbox, resolveTrackBbox(raw, [...record.track, ...groupSamples(this.readSamples(key))]));
149
- });
185
+ clipMatchesViewport(bbox, key, record) {
186
+ const raw = record.bbox;
187
+ if (raw === null)
188
+ return false;
189
+ if (raw.maxLon - raw.minLon <= 180)
190
+ return true;
191
+ return bboxIntersects(bbox, resolveTrackBbox(raw, [...record.track, ...groupSamples(this.readSamples(key))]));
192
+ }
193
+ selectClipViewport(bbox, availability, segmentFilter) {
194
+ const clips = this.selectClips(bbox, availability, false, segmentFilter);
195
+ if (bbox === undefined)
196
+ return clips;
197
+ return clips.filter(({ key, record }) => this.clipMatchesViewport(bbox, key, record));
150
198
  }
151
- readExportCandidates(bbox, availability, matches, options) {
199
+ readExportCandidates(bbox, availability, matches, options, segmentFilter) {
152
200
  return this.transaction('BEGIN', () => {
153
- const clips = (bbox === undefined ? this.selectClips(undefined, availability, false) :
154
- this.selectClipViewport(bbox, availability)).filter(matches);
201
+ const clips = this.selectClipViewport(bbox, availability, segmentFilter).filter(matches);
155
202
  const endpoints = options.redact ? this.readLaunchEndpoints(new Set(clips.map(({ flight }) => flight.flightId))) : [];
156
203
  const gaze = options.includeGaze ? this.db.prepare('SELECT samples_json FROM clip_gaze WHERE clip_key = ?') : undefined;
157
204
  return {
@@ -208,6 +255,52 @@ export class ArchiveStore {
208
255
  WHERE clip_key = ? ORDER BY segment, sample_index
209
256
  `).all(key);
210
257
  }
258
+ readSegments(key) {
259
+ const rows = this.db.prepare(`
260
+ SELECT segment_type, start_sec, end_sec, duration_sec, smoothness,
261
+ exposure_stable, mean_speed_mps, mean_yaw_rate_deg_per_sec
262
+ FROM segments WHERE clip_key = ? ORDER BY segment_index
263
+ `).all(key);
264
+ return rows.map(decodeSegment);
265
+ }
266
+ listSegments(filters = {}) {
267
+ return this.transaction('BEGIN', () => {
268
+ const { clauses, values } = this.clipFilterClauses(filters.bbox, filters.availability, false);
269
+ if (filters.segmentType !== undefined) {
270
+ clauses.push('segments.segment_type = ?');
271
+ values.push(filters.segmentType);
272
+ }
273
+ if (filters.minSmoothness !== undefined) {
274
+ clauses.push('segments.smoothness >= ?');
275
+ values.push(filters.minSmoothness);
276
+ }
277
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
278
+ const rows = this.db.prepare(`
279
+ SELECT clips.*, segments.segment_type, segments.start_sec, segments.end_sec,
280
+ segments.duration_sec, segments.smoothness, segments.exposure_stable,
281
+ segments.mean_speed_mps, segments.mean_yaw_rate_deg_per_sec
282
+ FROM segments JOIN clips USING (clip_key)
283
+ ${where}
284
+ ORDER BY segments.smoothness DESC, segments.clip_key ASC, segments.start_sec ASC
285
+ `).all(...values);
286
+ const viewportCache = new Map();
287
+ const results = [];
288
+ for (const row of rows) {
289
+ const clip = decodeClip(row);
290
+ if (filters.bbox !== undefined) {
291
+ let matches = viewportCache.get(clip.key);
292
+ if (matches === undefined) {
293
+ matches = this.clipMatchesViewport(filters.bbox, clip.key, clip.record);
294
+ viewportCache.set(clip.key, matches);
295
+ }
296
+ if (!matches)
297
+ continue;
298
+ }
299
+ results.push({ clip, segment: decodeSegment(row) });
300
+ }
301
+ return results;
302
+ });
303
+ }
211
304
  commit(expectedRevision, updates, online, offline, removed) {
212
305
  this.transaction('BEGIN IMMEDIATE', () => {
213
306
  if (this.revision() !== expectedRevision) {
@@ -233,32 +326,48 @@ export class ArchiveStore {
233
326
  revision() {
234
327
  return this.db.prepare('SELECT revision FROM archive_revision').get()?.revision;
235
328
  }
236
- selectClips(bbox, availability, includeArcs) {
329
+ clipFilterClauses(bbox, availability, includeArcs, segmentFilter) {
237
330
  const clauses = [];
238
331
  const values = [];
239
332
  if (availability !== undefined) {
240
- clauses.push('availability = ?');
333
+ clauses.push('clips.availability = ?');
241
334
  values.push(availability);
242
335
  }
243
336
  if (bbox !== undefined) {
244
337
  const ranges = longitudeRanges(bbox);
245
- const longitude = ranges.map(() => '(min_lon <= ? AND max_lon >= ?)').join(' OR ');
246
- const latitude = 'min_lat <= ? AND max_lat >= ?';
338
+ const longitude = ranges.map(() => '(clips.min_lon <= ? AND clips.max_lon >= ?)').join(' OR ');
339
+ const latitude = 'clips.min_lat <= ? AND clips.max_lat >= ?';
247
340
  if (includeArcs) {
248
341
  // An arc's length in degrees is at most the latitude difference plus the
249
342
  // longitude span. An excursion beyond either latitude endpoint adds
250
343
  // twice its height to that lower bound, so half the span covers it.
251
344
  // Wider raw longitude ranges may span the antimeridian or contain a pole-crossing arc.
252
- clauses.push(`(max_lon - min_lon >= 180 OR (
253
- min_lat - (max_lon - min_lon) / 2 <= ? AND max_lat + (max_lon - min_lon) / 2 >= ?
345
+ clauses.push(`(clips.max_lon - clips.min_lon >= 180 OR (
346
+ clips.min_lat - (clips.max_lon - clips.min_lon) / 2 <= ? AND clips.max_lat + (clips.max_lon - clips.min_lon) / 2 >= ?
254
347
  AND (${longitude})
255
348
  ))`);
256
349
  }
257
350
  else {
258
- clauses.push(`(${latitude}) AND (max_lon - min_lon > 180 OR (${longitude}))`);
351
+ clauses.push(`(${latitude}) AND (clips.max_lon - clips.min_lon > 180 OR (${longitude}))`);
259
352
  }
260
353
  values.push(bbox.maxLat, bbox.minLat, ...ranges.flatMap(([west, east]) => [east, west]));
261
354
  }
355
+ if (segmentFilter?.segmentType !== undefined || segmentFilter?.minSmoothness !== undefined) {
356
+ const segClauses = ['segments.clip_key = clips.clip_key'];
357
+ if (segmentFilter.segmentType !== undefined) {
358
+ segClauses.push('segments.segment_type = ?');
359
+ values.push(segmentFilter.segmentType);
360
+ }
361
+ if (segmentFilter.minSmoothness !== undefined) {
362
+ segClauses.push('segments.smoothness >= ?');
363
+ values.push(segmentFilter.minSmoothness);
364
+ }
365
+ clauses.push(`EXISTS (SELECT 1 FROM segments WHERE ${segClauses.join(' AND ')})`);
366
+ }
367
+ return { clauses, values };
368
+ }
369
+ selectClips(bbox, availability, includeArcs, segmentFilter) {
370
+ const { clauses, values } = this.clipFilterClauses(bbox, availability, includeArcs, segmentFilter);
262
371
  const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
263
372
  const rows = this.db.prepare(`
264
373
  SELECT * FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
@@ -302,14 +411,15 @@ export class ArchiveStore {
302
411
  throw error;
303
412
  }
304
413
  }
305
- writeClip({ key, availability, fingerprint, record, overview, samples, gaze }) {
414
+ writeClip({ key, availability, fingerprint, record, overview, samples, gaze, segments }) {
306
415
  const { size, mtimeMs, srtSize, srtMtimeMs, schemaVersion } = fingerprint;
307
416
  const bbox = record.bbox;
417
+ const segmentsIndexed = segments !== undefined ? 1 : 0;
308
418
  this.db.prepare(`
309
419
  INSERT INTO clips (
310
420
  clip_key, availability, size, mtime_ms, srt_size, srt_mtime_ms, schema_version,
311
- min_lat, min_lon, max_lat, max_lon, record_json, overview_json
312
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
421
+ min_lat, min_lon, max_lat, max_lon, record_json, overview_json, segments_indexed
422
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
313
423
  ON CONFLICT (clip_key) DO UPDATE SET
314
424
  availability = excluded.availability,
315
425
  size = excluded.size, mtime_ms = excluded.mtime_ms,
@@ -317,10 +427,12 @@ export class ArchiveStore {
317
427
  schema_version = excluded.schema_version,
318
428
  min_lat = excluded.min_lat, min_lon = excluded.min_lon,
319
429
  max_lat = excluded.max_lat, max_lon = excluded.max_lon,
320
- record_json = excluded.record_json, overview_json = excluded.overview_json
321
- `).run(key, availability, size, mtimeMs, srtSize, srtMtimeMs, schemaVersion, bbox?.minLat ?? null, bbox?.minLon ?? null, bbox?.maxLat ?? null, bbox?.maxLon ?? null, JSON.stringify(record), JSON.stringify(overview));
430
+ record_json = excluded.record_json, overview_json = excluded.overview_json,
431
+ segments_indexed = excluded.segments_indexed
432
+ `).run(key, availability, size, mtimeMs, srtSize, srtMtimeMs, schemaVersion, bbox?.minLat ?? null, bbox?.minLon ?? null, bbox?.maxLat ?? null, bbox?.maxLon ?? null, JSON.stringify(record), JSON.stringify(overview), segmentsIndexed);
322
433
  this.db.prepare('DELETE FROM clip_samples WHERE clip_key = ?').run(key);
323
434
  this.writeGaze(key, gaze);
435
+ this.writeSegments(key, segments);
324
436
  const add = this.db.prepare('INSERT INTO clip_samples VALUES (?, ?, ?, ?, ?, ?)');
325
437
  for (const [index, sample] of samples.entries()) {
326
438
  add.run(key, sample.segment, index, sample.tSec, sample.lat, sample.lon);
@@ -333,4 +445,36 @@ export class ArchiveStore {
333
445
  const bbox = gazeBbox(gaze);
334
446
  this.db.prepare('INSERT INTO clip_gaze VALUES (?, ?, ?, ?, ?, ?)').run(key, bbox?.minLat ?? null, bbox?.maxLat ?? null, bbox?.minLon ?? null, bbox?.maxLon ?? null, JSON.stringify(gaze));
335
447
  }
448
+ writeSegments(key, segments) {
449
+ this.db.prepare('DELETE FROM segments WHERE clip_key = ?').run(key);
450
+ if (!segments)
451
+ return;
452
+ const add = this.db.prepare(`
453
+ INSERT INTO segments (
454
+ clip_key, segment_index, segment_type, start_sec, end_sec, duration_sec,
455
+ smoothness, exposure_stable, mean_speed_mps, mean_yaw_rate_deg_per_sec
456
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
457
+ `);
458
+ for (const [index, segment] of segments.entries()) {
459
+ add.run(key, index, segment.type, segment.startSec, segment.endSec, segment.durationSec, segment.smoothness, segment.exposureStable ? 1 : 0, segment.meanSpeedMps, segment.meanYawRateDegPerSec);
460
+ }
461
+ }
462
+ }
463
+ export function withArchiveStore(db, run) {
464
+ const store = new ArchiveStore(db);
465
+ try {
466
+ return run(store);
467
+ }
468
+ finally {
469
+ store.close();
470
+ }
471
+ }
472
+ export async function withArchiveStoreAsync(db, run) {
473
+ const store = new ArchiveStore(db);
474
+ try {
475
+ return await run(store);
476
+ }
477
+ finally {
478
+ store.close();
479
+ }
336
480
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-archive",
3
- "version": "0.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Scan a local library of drone recordings.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -29,7 +29,7 @@
29
29
  "directory": "packages/archive"
30
30
  },
31
31
  "dependencies": {
32
- "drone-path-core": "~1.0.0-rc1",
32
+ "drone-path-core": "~1.1.0",
33
33
  "leaflet": "~1.9.4",
34
34
  "p-queue": "~10.0.0"
35
35
  }