drone-path-archive 1.0.0 → 1.1.1

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.
@@ -8,5 +8,7 @@ interface MapClip {
8
8
  export interface MapFlight {
9
9
  clips: MapClip[];
10
10
  }
11
- export declare function archiveMapHtml(flights: readonly MapFlight[]): string;
11
+ export declare function archiveMapHtml(flights: readonly MapFlight[], { offline }?: {
12
+ offline?: boolean;
13
+ }): string;
12
14
  export {};
@@ -2,6 +2,23 @@ import fs from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import path from 'node:path';
4
4
  const require = createRequire(import.meta.url);
5
+ // The video renderer has a self-contained module graph and serves tiles through its local cache.
6
+ const BASEMAPS = {
7
+ satellite: {
8
+ url: 'https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
9
+ subdomains: [''],
10
+ attribution: '<a href="https://www.esri.com/">Powered by Esri</a> | Imagery &copy; Esri, Vantor, Earthstar Geographics, and the GIS User Community',
11
+ maxZoom: 19,
12
+ },
13
+ topo: {
14
+ url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
15
+ subdomains: ['a', 'b', 'c'],
16
+ attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, SRTM | Style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (CC-BY-SA)',
17
+ maxZoom: 19,
18
+ maxNativeZoom: 17,
19
+ },
20
+ };
21
+ const tileOrigins = [...new Set(Object.values(BASEMAPS).flatMap(({ url, subdomains }) => subdomains.map((subdomain) => new URL(url.replace('{s}', subdomain)).origin)))].join(' ');
5
22
  function leafletAssets() {
6
23
  const root = path.dirname(require.resolve('leaflet/package.json'));
7
24
  const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
@@ -11,11 +28,42 @@ function leafletAssets() {
11
28
  const css = read('dist/leaflet.css').replace(/url\([^)]*\)/gu, 'none');
12
29
  return { script, css, license: read('LICENSE') };
13
30
  }
14
- function mapClient() {
31
+ function basemapClient() {
32
+ return String.raw `
33
+ const { satellite, topo } = ${JSON.stringify(BASEMAPS)};
34
+ const { url: topoUrl, ...topoOptions } = topo;
35
+ const { url: imageryUrl, ...imageryOptions } = satellite;
36
+ const imagery = L.layerGroup();
37
+ const baseLayers = {
38
+ Topographic: L.tileLayer(topoUrl, topoOptions).addTo(map),
39
+ 'Esri imagery': imagery,
40
+ 'No basemap': L.layerGroup(),
41
+ };
42
+ const credentials = document.querySelector('#esri-credentials');
43
+ const apiKey = document.querySelector('#esri-key');
44
+ const tileError = document.querySelector('#esri-tile-error');
45
+ map.on('baselayerchange', ({ layer }) => {
46
+ credentials.hidden = layer !== imagery;
47
+ });
48
+ credentials.addEventListener('submit', (event) => {
49
+ event.preventDefault();
50
+ const key = apiKey.value.trim();
51
+ if (!key || !map.hasLayer(imagery)) return;
52
+ apiKey.value = '';
53
+ tileError.hidden = true;
54
+ imagery.clearLayers();
55
+ L.tileLayer(imageryUrl + '?token=' + encodeURIComponent(key), imageryOptions)
56
+ .on('tileerror', () => { tileError.hidden = false; })
57
+ .addTo(imagery);
58
+ });
59
+ `;
60
+ }
61
+ function mapClient(offline) {
15
62
  // Kept separate from export data: popup text is only assigned to DOM nodes.
16
63
  return String.raw `
17
64
  const flights = JSON.parse(document.querySelector('#archive-data').textContent);
18
- const map = L.map('map', { attributionControl: false });
65
+ const map = L.map('map');
66
+ ${offline ? 'const baseLayers = {};' : basemapClient()}
19
67
  const bounds = L.latLngBounds([]);
20
68
  const colors = ['#1565c0', '#a33e00', '#00736e', '#a12466', '#613aa1', '#537421'];
21
69
  const anchor = flights.flatMap((flight) => flight.clips)
@@ -55,7 +103,10 @@ for (const [index, flight] of flights.entries()) {
55
103
  }
56
104
  }
57
105
  }
58
- if (hasGaze) L.control.layers({}, { 'Camera footprints': footprints.addTo(map) }, { collapsed: false }).addTo(map);
106
+ const overlays = hasGaze ? { 'Camera footprints': footprints.addTo(map) } : {};
107
+ if (Object.keys(baseLayers).length || hasGaze) {
108
+ L.control.layers(baseLayers, overlays, { collapsed: false }).addTo(map);
109
+ }
59
110
  if (bounds.isValid()) map.fitBounds(bounds, { padding: [24, 24], maxZoom: 17 });
60
111
  else {
61
112
  map.setView([0, 0], 2);
@@ -63,7 +114,7 @@ else {
63
114
  }
64
115
  `;
65
116
  }
66
- export function archiveMapHtml(flights) {
117
+ export function archiveMapHtml(flights, { offline = false } = {}) {
67
118
  const { script, css, license } = leafletAssets();
68
119
  const data = JSON.stringify(flights).replaceAll('<', '\\u003c');
69
120
  return `<!doctype html>
@@ -71,24 +122,31 @@ export function archiveMapHtml(flights) {
71
122
  <head>
72
123
  <meta charset="utf-8">
73
124
  <meta name="viewport" content="width=device-width, initial-scale=1">
74
- <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'">
125
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; form-action 'none'; img-src ${offline ? "'none'" : tileOrigins}">
75
126
  <title>Drone Path archive</title>
76
127
  <style>
77
128
  ${css}
78
129
  html,body,#map{height:100%;margin:0}
79
130
  #map{background:#f4f6f7}
80
131
  #empty{position:absolute;z-index:1000;left:50%;top:1rem;transform:translateX(-50%);padding:.6rem 1rem;background:white;border:1px solid #aeb6bd;font:1rem system-ui,sans-serif}
132
+ #esri-credentials{position:absolute;z-index:1000;right:10px;bottom:24px;padding:.6rem;background:white;font:.9rem system-ui,sans-serif}
81
133
  </style>
82
134
  </head>
83
135
  <body>
84
136
  <div id="map" aria-label="Flight map"></div>
85
137
  <div id="empty" hidden>No tracks match this export.</div>
138
+ ${offline ? '' : `<form id="esri-credentials" autocomplete="off" hidden>
139
+ <label for="esri-key">ArcGIS API key</label>
140
+ <input id="esri-key" type="password" required>
141
+ <button type="submit">Load Esri imagery</button>
142
+ <p id="esri-tile-error" role="status" hidden>Some Esri tiles could not load. Check your key and connection.</p>
143
+ </form>`}
86
144
  <script type="application/json" id="archive-data">${data}</script>
87
145
  <!--
88
146
  ${license}
89
147
  -->
90
148
  <script>${script}</script>
91
- <script>${mapClient()}</script>
149
+ <script>${mapClient(offline)}</script>
92
150
  </body>
93
151
  </html>
94
152
  `;
package/dist/export.d.ts CHANGED
@@ -4,6 +4,11 @@ interface ExportOptions {
4
4
  redactLaunchM?: number;
5
5
  includeGaze?: boolean;
6
6
  }
7
- export declare function exportArchiveMap(db: string, output: string, options?: ExportOptions): void;
7
+ export declare function exportArchiveMap(db: string, output: string, options?: ExportOptions & {
8
+ offline?: boolean;
9
+ }): void;
8
10
  export declare function exportArchiveTracks(db: string, output: string, options?: Omit<ExportOptions, 'includeGaze'>): void;
11
+ export declare function exportArchiveMarkers(db: string, output: string, options?: {
12
+ filters?: ListFilters;
13
+ }): void;
9
14
  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,15 +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 { listArchiveSegments, matchesMetadata, segmentFilterOf } from './query.js';
13
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;
20
+ const segmentFilter = segmentFilterOf(filters);
19
21
  return withArchiveStore(db, (store) => {
20
- const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record }) => matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact });
22
+ const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record }) => matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact }, segmentFilter);
21
23
  const redactTrack = launchRedactor(endpoints, redactLaunchM);
22
24
  const flights = groupFlightMembers(clips);
23
25
  return [...flights.values()].flatMap((members) => {
@@ -58,7 +60,7 @@ function writeExport(db, output, content) {
58
60
  export function exportArchiveMap(db, output, options = {}) {
59
61
  if (path.extname(output).toLowerCase() !== '.html')
60
62
  throw new Error('expected an .html output file');
61
- writeExport(db, output, archiveMapHtml(exportFlights(db, options)));
63
+ writeExport(db, output, archiveMapHtml(exportFlights(db, options), { offline: options.offline }));
62
64
  }
63
65
  export function exportArchiveTracks(db, output, options = {}) {
64
66
  const format = trackFormatOf(output);
@@ -72,3 +74,39 @@ export function exportArchiveTracks(db, output, options = {}) {
72
74
  case 'kmz': return writeExport(db, output, kmzBytes(serializeKmlTracks(tracks)));
73
75
  }
74
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>;
@@ -100,7 +100,8 @@ async function indexFolders(store, dirs, options) {
100
100
  seen.add(key);
101
101
  const prior = previous.get(key);
102
102
  const unchanged = prior && matches(current.fingerprint, prior.fingerprint);
103
- 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') {
104
105
  records.set(file, prior.record);
105
106
  onRecord?.(prior.record);
106
107
  if (prior.availability === 'offline')
@@ -108,7 +109,7 @@ async function indexFolders(store, dirs, options) {
108
109
  }
109
110
  else {
110
111
  pending.set(file, current);
111
- if (unchanged && prior.gazePending) {
112
+ if (unchanged && needsBackfill) {
112
113
  backfills.add(file);
113
114
  if (prior.availability === 'offline')
114
115
  online.push(key);
@@ -142,11 +143,13 @@ async function probeChanges(pending, { concurrency, signal, getTools, onRecord }
142
143
  return [];
143
144
  const tracks = new Map();
144
145
  const gaze = new Map();
146
+ const segmentsByFile = new Map();
145
147
  const tools = await getTools();
146
148
  const scanned = await scanRecordings([...pending.keys()], {
147
149
  tools, concurrency, signal, onRecord,
148
150
  sidecarFor: (file) => pending.get(file)?.sidecar,
149
151
  onGaze: (file, samples) => gaze.set(file, samples),
152
+ onSegments: (file, shots) => segmentsByFile.set(file, shots),
150
153
  onTrack: (file, segments) => {
151
154
  tracks.set(file, { overview: decimateSegments(segments, 60, 9), samples: sampleSegments(segments) });
152
155
  },
@@ -164,6 +167,7 @@ async function probeChanges(pending, { concurrency, signal, getTools, onRecord }
164
167
  key: clipKey(record.path), availability: 'online', fingerprint: original.fingerprint, record,
165
168
  ...tracks.get(record.path) ?? { overview: [], samples: [] },
166
169
  gaze: gaze.get(record.path),
170
+ segments: segmentsByFile.get(record.path),
167
171
  });
168
172
  }
169
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
@@ -6,6 +6,14 @@ import { groupSamples } from './scan-track.js';
6
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,7 +29,8 @@ function toClip({ record, availability }) {
21
29
  return { ...record, availability };
22
30
  }
23
31
  function matchingClips(db, filters) {
24
- return withArchiveStore(db, (store) => store.listClips(filters.bbox, filters.availability).flatMap((indexed) => {
32
+ const segmentFilter = segmentFilterOf(filters);
33
+ return withArchiveStore(db, (store) => store.listClips(filters.bbox, filters.availability, segmentFilter).flatMap((indexed) => {
25
34
  const clip = toClip(indexed);
26
35
  return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
27
36
  }));
@@ -35,6 +44,18 @@ export function listArchiveFlights(db, filters = {}) {
35
44
  flightId, clips: members.map(({ clip, flight }) => ({ ...clip, splitFromKey: flight.splitFromKey })),
36
45
  }));
37
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
+ }
38
59
  export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze = false) {
39
60
  return withArchiveStore(db, (store) => {
40
61
  const hits = [];
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,13 +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
  }
83
103
  export declare function withArchiveStore<T>(db: string, run: (store: ArchiveStore) => T): T;
84
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,35 +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));
184
+ }
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))]));
140
192
  }
141
- selectClipViewport(bbox, availability) {
142
- const clips = this.selectClips(bbox, availability, false);
193
+ selectClipViewport(bbox, availability, segmentFilter) {
194
+ const clips = this.selectClips(bbox, availability, false, segmentFilter);
143
195
  if (bbox === undefined)
144
196
  return clips;
145
- return clips.filter(({ key, record }) => {
146
- const raw = record.bbox;
147
- if (raw === null)
148
- return false;
149
- if (raw.maxLon - raw.minLon <= 180)
150
- return true;
151
- return bboxIntersects(bbox, resolveTrackBbox(raw, [...record.track, ...groupSamples(this.readSamples(key))]));
152
- });
197
+ return clips.filter(({ key, record }) => this.clipMatchesViewport(bbox, key, record));
153
198
  }
154
- readExportCandidates(bbox, availability, matches, options) {
199
+ readExportCandidates(bbox, availability, matches, options, segmentFilter) {
155
200
  return this.transaction('BEGIN', () => {
156
- const clips = this.selectClipViewport(bbox, availability).filter(matches);
201
+ const clips = this.selectClipViewport(bbox, availability, segmentFilter).filter(matches);
157
202
  const endpoints = options.redact ? this.readLaunchEndpoints(new Set(clips.map(({ flight }) => flight.flightId))) : [];
158
203
  const gaze = options.includeGaze ? this.db.prepare('SELECT samples_json FROM clip_gaze WHERE clip_key = ?') : undefined;
159
204
  return {
@@ -210,6 +255,52 @@ export class ArchiveStore {
210
255
  WHERE clip_key = ? ORDER BY segment, sample_index
211
256
  `).all(key);
212
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
+ }
213
304
  commit(expectedRevision, updates, online, offline, removed) {
214
305
  this.transaction('BEGIN IMMEDIATE', () => {
215
306
  if (this.revision() !== expectedRevision) {
@@ -235,32 +326,48 @@ export class ArchiveStore {
235
326
  revision() {
236
327
  return this.db.prepare('SELECT revision FROM archive_revision').get()?.revision;
237
328
  }
238
- selectClips(bbox, availability, includeArcs) {
329
+ clipFilterClauses(bbox, availability, includeArcs, segmentFilter) {
239
330
  const clauses = [];
240
331
  const values = [];
241
332
  if (availability !== undefined) {
242
- clauses.push('availability = ?');
333
+ clauses.push('clips.availability = ?');
243
334
  values.push(availability);
244
335
  }
245
336
  if (bbox !== undefined) {
246
337
  const ranges = longitudeRanges(bbox);
247
- const longitude = ranges.map(() => '(min_lon <= ? AND max_lon >= ?)').join(' OR ');
248
- 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 >= ?';
249
340
  if (includeArcs) {
250
341
  // An arc's length in degrees is at most the latitude difference plus the
251
342
  // longitude span. An excursion beyond either latitude endpoint adds
252
343
  // twice its height to that lower bound, so half the span covers it.
253
344
  // Wider raw longitude ranges may span the antimeridian or contain a pole-crossing arc.
254
- clauses.push(`(max_lon - min_lon >= 180 OR (
255
- 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 >= ?
256
347
  AND (${longitude})
257
348
  ))`);
258
349
  }
259
350
  else {
260
- 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}))`);
261
352
  }
262
353
  values.push(bbox.maxLat, bbox.minLat, ...ranges.flatMap(([west, east]) => [east, west]));
263
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);
264
371
  const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
265
372
  const rows = this.db.prepare(`
266
373
  SELECT * FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
@@ -304,14 +411,15 @@ export class ArchiveStore {
304
411
  throw error;
305
412
  }
306
413
  }
307
- writeClip({ key, availability, fingerprint, record, overview, samples, gaze }) {
414
+ writeClip({ key, availability, fingerprint, record, overview, samples, gaze, segments }) {
308
415
  const { size, mtimeMs, srtSize, srtMtimeMs, schemaVersion } = fingerprint;
309
416
  const bbox = record.bbox;
417
+ const segmentsIndexed = segments !== undefined ? 1 : 0;
310
418
  this.db.prepare(`
311
419
  INSERT INTO clips (
312
420
  clip_key, availability, size, mtime_ms, srt_size, srt_mtime_ms, schema_version,
313
- min_lat, min_lon, max_lat, max_lon, record_json, overview_json
314
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
421
+ min_lat, min_lon, max_lat, max_lon, record_json, overview_json, segments_indexed
422
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
315
423
  ON CONFLICT (clip_key) DO UPDATE SET
316
424
  availability = excluded.availability,
317
425
  size = excluded.size, mtime_ms = excluded.mtime_ms,
@@ -319,10 +427,12 @@ export class ArchiveStore {
319
427
  schema_version = excluded.schema_version,
320
428
  min_lat = excluded.min_lat, min_lon = excluded.min_lon,
321
429
  max_lat = excluded.max_lat, max_lon = excluded.max_lon,
322
- record_json = excluded.record_json, overview_json = excluded.overview_json
323
- `).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);
324
433
  this.db.prepare('DELETE FROM clip_samples WHERE clip_key = ?').run(key);
325
434
  this.writeGaze(key, gaze);
435
+ this.writeSegments(key, segments);
326
436
  const add = this.db.prepare('INSERT INTO clip_samples VALUES (?, ?, ?, ?, ?, ?)');
327
437
  for (const [index, sample] of samples.entries()) {
328
438
  add.run(key, sample.segment, index, sample.tSec, sample.lat, sample.lon);
@@ -335,6 +445,20 @@ export class ArchiveStore {
335
445
  const bbox = gazeBbox(gaze);
336
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));
337
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
+ }
338
462
  }
339
463
  export function withArchiveStore(db, run) {
340
464
  const store = new ArchiveStore(db);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-archive",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
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",
32
+ "drone-path-core": "~1.1.1",
33
33
  "leaflet": "~1.9.4",
34
34
  "p-queue": "~10.0.0"
35
35
  }