drone-path-archive 1.2.0 → 2.0.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.
@@ -1,2 +1,6 @@
1
1
  export declare function zonedTimeMs(time: string): number;
2
2
  export declare function parseDateBound(time: string): number;
3
+ export declare function dateRangeToBounds(fromDate?: string, toDate?: string): {
4
+ afterMs?: number;
5
+ beforeMs?: number;
6
+ };
@@ -1,5 +1,6 @@
1
1
  const ISO_ZONED_TIME = /^(\d{4}-\d{2}-\d{2})T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/u;
2
2
  const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
3
+ const DAY_MS = 86_400_000;
3
4
  function validCalendarDay(day) {
4
5
  const epoch = Date.parse(day);
5
6
  return Number.isFinite(epoch) && new Date(epoch).toISOString().slice(0, 10) === day;
@@ -14,3 +15,15 @@ export function parseDateBound(time) {
14
15
  throw new Error('expected an ISO date or timestamp with a time zone');
15
16
  return epoch;
16
17
  }
18
+ export function dateRangeToBounds(fromDate, toDate) {
19
+ const from = fromDate?.trim() ?? '';
20
+ const to = toDate?.trim() ?? '';
21
+ const afterMs = from ? parseDateBound(from) : undefined;
22
+ const beforeMs = to
23
+ ? (ISO_DAY.test(to) ? parseDateBound(to) + DAY_MS : parseDateBound(to))
24
+ : undefined;
25
+ return {
26
+ ...(afterMs !== undefined ? { afterMs } : {}),
27
+ ...(beforeMs !== undefined ? { beforeMs } : {}),
28
+ };
29
+ }
package/dist/export.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import type { ListFilters } from './query.js';
1
+ import type { MarkerRange } from 'drone-path-core/nle-markers';
2
+ import type { ArchiveSegment, ListFilters } from './query.js';
2
3
  interface ExportOptions {
3
4
  filters?: ListFilters;
5
+ flightIds?: readonly string[];
4
6
  redactLaunchM?: number;
5
7
  includeGaze?: boolean;
6
8
  }
@@ -8,7 +10,9 @@ export declare function exportArchiveMap(db: string, output: string, options?: E
8
10
  offline?: boolean;
9
11
  }): void;
10
12
  export declare function exportArchiveTracks(db: string, output: string, options?: Omit<ExportOptions, 'includeGaze'>): void;
13
+ export declare function segmentToMarkerRange(segment: ArchiveSegment): MarkerRange;
11
14
  export declare function exportArchiveMarkers(db: string, output: string, options?: {
12
15
  filters?: ListFilters;
13
16
  }): void;
17
+ export declare function serializeMarkers(format: 'csv' | 'fcpxml', markers: readonly MarkerRange[]): string;
14
18
  export {};
package/dist/export.js CHANGED
@@ -10,16 +10,18 @@ import { serializeKmlTracks } from 'drone-path-core/track-kml';
10
10
  import { kmzBytes } from 'drone-path-core/track-kmz';
11
11
  import { archiveMapHtml } from './export-map.js';
12
12
  import { groupFlightMembers } from './flight-members.js';
13
+ import { assertNotArchiveFiles } from './output-guard.js';
13
14
  import { listArchiveSegments, matchesMetadata, segmentFilterOf } from './query.js';
14
15
  import { withArchiveStore } from './store.js';
15
- function exportFlights(db, { filters = {}, redactLaunchM = 0, includeGaze = false }, splitDateline = false) {
16
+ function exportFlights(db, { filters = {}, flightIds, redactLaunchM = 0, includeGaze = false }, splitDateline = false) {
16
17
  if (!Number.isFinite(redactLaunchM) || redactLaunchM < 0) {
17
18
  throw new Error('expected a nonnegative launch redaction radius in meters');
18
19
  }
19
20
  const redact = redactLaunchM > 0;
20
21
  const segmentFilter = segmentFilterOf(filters);
22
+ const selectedFlightIds = flightIds === undefined ? undefined : new Set(flightIds);
21
23
  return withArchiveStore(db, (store) => {
22
- const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record }) => matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact }, segmentFilter);
24
+ const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record, flight }) => (selectedFlightIds === undefined || selectedFlightIds.has(flight.flightId)) && matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact }, segmentFilter);
23
25
  const redactTrack = launchRedactor(endpoints, redactLaunchM);
24
26
  const flights = groupFlightMembers(clips);
25
27
  return [...flights.values()].flatMap((members) => {
@@ -40,20 +42,7 @@ function exportFlights(db, { filters = {}, redactLaunchM = 0, includeGaze = fals
40
42
  });
41
43
  }
42
44
  function writeExport(db, output, content) {
43
- const resolved = (file) => fs.existsSync(file) ? fs.realpathSync(file) : path.resolve(file);
44
- const outputPath = resolved(output);
45
- const databasePath = resolved(db);
46
- const samePath = process.platform === 'win32' ?
47
- outputPath.toLowerCase() === databasePath.toLowerCase() : outputPath === databasePath;
48
- if (samePath)
49
- throw new Error('export file cannot overwrite the archive database');
50
- if (fs.existsSync(output) && fs.existsSync(db)) {
51
- const target = fs.statSync(output, { bigint: true });
52
- const database = fs.statSync(db, { bigint: true });
53
- if (target.dev === database.dev && target.ino === database.ino) {
54
- throw new Error('export file cannot overwrite the archive database');
55
- }
56
- }
45
+ assertNotArchiveFiles(output, db);
57
46
  fs.mkdirSync(path.dirname(output), { recursive: true });
58
47
  fs.writeFileSync(output, content);
59
48
  }
@@ -74,7 +63,7 @@ export function exportArchiveTracks(db, output, options = {}) {
74
63
  case 'kmz': return writeExport(db, output, kmzBytes(serializeKmlTracks(tracks)));
75
64
  }
76
65
  }
77
- function segmentToMarkerRange(segment) {
66
+ export function segmentToMarkerRange(segment) {
78
67
  const video = segment.clip.video;
79
68
  if (!video ||
80
69
  video.durationSec === null ||
@@ -105,8 +94,10 @@ export function exportArchiveMarkers(db, output, options = {}) {
105
94
  const format = markerFormatOf(output);
106
95
  const segments = listArchiveSegments(db, options.filters);
107
96
  const markers = segments.map(segmentToMarkerRange);
108
- const content = format === 'csv'
97
+ writeExport(db, output, serializeMarkers(format, markers));
98
+ }
99
+ export function serializeMarkers(format, markers) {
100
+ return format === 'csv'
109
101
  ? serializeDaVinciResolveCsv(markers)
110
102
  : serializeFcpxmlMarkers(markers);
111
- writeExport(db, output, content);
112
103
  }
@@ -1,8 +1,17 @@
1
1
  import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
2
+ import { createSrtSidecarLookup } from 'drone-path-core/srt-sidecar';
2
3
  import type { ScanOptions, ScanRecord } from './scanner.js';
4
+ import type { ClipFingerprint } from './store.js';
3
5
  export interface IndexedScanOptions extends Omit<ScanOptions, 'tools' | 'sidecarFor' | 'onTrack' | 'onGaze' | 'onSegments'> {
4
6
  db: string;
5
7
  prune?: boolean;
6
8
  getTools: () => Promise<FfmpegToolPaths>;
7
9
  }
10
+ export interface ClipInput {
11
+ fingerprint: ClipFingerprint;
12
+ sidecar: string | null;
13
+ }
14
+ /** Stat a recording and its SRT sidecar into the fingerprint that decides whether its index entry is current. */
15
+ export declare function inspectClipInput(file: string, sidecarFor: ReturnType<typeof createSrtSidecarLookup>): Promise<ClipInput | null>;
16
+ export declare function fingerprintsMatch(a: ClipFingerprint, b: ClipFingerprint | null | undefined): boolean;
8
17
  export declare function scanArchive(dirs: readonly string[], options: IndexedScanOptions): Promise<ScanRecord[]>;
@@ -1,16 +1,16 @@
1
1
  import { realpath, stat } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
+ import PQueue from 'p-queue';
3
4
  import { createSrtSidecarLookup } from 'drone-path-core/srt-sidecar';
4
5
  import { decimateSegments, sampleSegments } from './scan-track.js';
5
6
  import { discoverRecordings, scanRecordings } from './scanner.js';
6
- import { CLIP_FINGERPRINT_VERSION, withArchiveStoreAsync } from './store.js';
7
+ import { CLIP_FINGERPRINT_VERSION, archiveClipKey, withArchiveStoreAsync } from './store.js';
8
+ // Metadata reads are cheap but latency-bound on network and removable media.
9
+ const STAT_CONCURRENCY = 16;
7
10
  function isMissing(error) {
8
11
  const code = error?.code;
9
12
  return code === 'ENOENT' || code === 'ENOTDIR';
10
13
  }
11
- function clipKey(file) {
12
- return process.platform === 'win32' ? file.toLowerCase() : file;
13
- }
14
14
  function within(root, file, recurse) {
15
15
  const rel = path.relative(root, file);
16
16
  return rel !== '' && rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel)
@@ -27,7 +27,22 @@ async function fileStats(file) {
27
27
  return null;
28
28
  }
29
29
  }
30
- async function inspectInput(file, sidecarFor) {
30
+ async function settleBounded(items, task, signal) {
31
+ const queue = new PQueue({ concurrency: STAT_CONCURRENCY });
32
+ const results = await Promise.allSettled(items.map((item) => queue.add(() => {
33
+ signal?.throwIfAborted();
34
+ return task(item);
35
+ })));
36
+ signal?.throwIfAborted();
37
+ return results;
38
+ }
39
+ function settled(result) {
40
+ if (result.status === 'rejected')
41
+ throw result.reason;
42
+ return result.value;
43
+ }
44
+ /** Stat a recording and its SRT sidecar into the fingerprint that decides whether its index entry is current. */
45
+ export async function inspectClipInput(file, sidecarFor) {
31
46
  const video = await fileStats(file);
32
47
  if (!video)
33
48
  return null;
@@ -50,7 +65,7 @@ async function inspectInput(file, sidecarFor) {
50
65
  },
51
66
  };
52
67
  }
53
- function matches(a, b) {
68
+ export function fingerprintsMatch(a, b) {
54
69
  return !!b && a.size === b.size && a.mtimeMs === b.mtimeMs && a.srtSize === b.srtSize
55
70
  && a.srtMtimeMs === b.srtMtimeMs && a.schemaVersion === b.schemaVersion;
56
71
  }
@@ -89,17 +104,18 @@ async function indexFolders(store, dirs, options) {
89
104
  const seen = new Set();
90
105
  const backfills = new Set();
91
106
  const online = [];
92
- for (const file of files) {
107
+ const inspected = await settleBounded(files, (file) => inspectClipInput(file, sidecarFor), signal);
108
+ for (const [index, file] of files.entries()) {
93
109
  signal?.throwIfAborted();
94
- const key = clipKey(file);
110
+ const key = archiveClipKey(file);
95
111
  if (seen.has(key))
96
112
  continue;
97
- const current = await inspectInput(file, sidecarFor);
113
+ const current = settled(inspected[index]);
98
114
  if (!current)
99
115
  continue;
100
116
  seen.add(key);
101
117
  const prior = previous.get(key);
102
- const unchanged = prior && matches(current.fingerprint, prior.fingerprint);
118
+ const unchanged = prior && fingerprintsMatch(current.fingerprint, prior.fingerprint);
103
119
  const needsBackfill = prior !== undefined && (prior.gazePending || prior.segmentsPending);
104
120
  if (unchanged && !needsBackfill && prior.record.status !== 'error') {
105
121
  records.set(file, prior.record);
@@ -121,11 +137,11 @@ async function indexFolders(store, dirs, options) {
121
137
  records.set(update.record.path, update.record);
122
138
  const offline = [];
123
139
  const removed = [];
124
- for (const { key, record, availability } of clips) {
140
+ const unseen = clips.filter(({ key, record }) => !seen.has(key) && roots.some((root) => within(root, record.path, recurse)));
141
+ const existing = await settleBounded(unseen, ({ record }) => fileStats(record.path), signal);
142
+ for (const [index, { key, availability }] of unseen.entries()) {
125
143
  signal?.throwIfAborted();
126
- if (seen.has(key) || !roots.some((root) => within(root, record.path, recurse)))
127
- continue;
128
- if (await fileStats(record.path))
144
+ if (settled(existing[index]))
129
145
  continue;
130
146
  if (prune)
131
147
  removed.push(key);
@@ -156,15 +172,16 @@ async function probeChanges(pending, { concurrency, signal, getTools, onRecord }
156
172
  });
157
173
  const updates = [];
158
174
  const sidecarFor = createSrtSidecarLookup();
159
- for (const record of scanned) {
175
+ const rechecked = await settleBounded(scanned, ({ path: file }) => inspectClipInput(file, sidecarFor), signal);
176
+ for (const [index, record] of scanned.entries()) {
160
177
  signal?.throwIfAborted();
161
178
  const original = pending.get(record.path);
162
- const current = await inspectInput(record.path, sidecarFor);
163
- if (!current || original.sidecar !== current.sidecar || !matches(original.fingerprint, current.fingerprint)) {
179
+ const current = settled(rechecked[index]);
180
+ if (!current || original.sidecar !== current.sidecar || !fingerprintsMatch(original.fingerprint, current.fingerprint)) {
164
181
  throw new Error(`recording changed during scan, rerun the scan: ${record.path}`);
165
182
  }
166
183
  updates.push({
167
- key: clipKey(record.path), availability: 'online', fingerprint: original.fingerprint, record,
184
+ key: archiveClipKey(record.path), availability: 'online', fingerprint: original.fingerprint, record,
168
185
  ...tracks.get(record.path) ?? { overview: [], samples: [] },
169
186
  gaze: gaze.get(record.path),
170
187
  segments: segmentsByFile.get(record.path),
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Resolves a path the way the OS would when writing it (after a recursive mkdir):
3
+ * existing segments are followed through symlinks (including dangling ones) and
4
+ * missing ones are kept, so boundary checks defeat `..` and symlink escapes.
5
+ */
6
+ export declare function canonicalizePath(targetPath: string): string;
7
+ /** True when both paths name the same file: canonical path match (case-folded on Windows) or same dev/ino. */
8
+ export declare function isSamePath(a: string, b: string): boolean;
9
+ export declare function assertNotProtectedPath(outputPath: string, protectedPaths: readonly string[], message: string): void;
10
+ /** Rejects an output path that names the archive database or one of its SQLite sidecars. */
11
+ export declare function assertNotArchiveFiles(outputPath: string, archiveDb: string, message?: string): void;
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ const MAX_SYMLINK_DEPTH = 40;
4
+ const SQLITE_SIDECAR_SUFFIXES = ['', '-wal', '-shm', '-journal'];
5
+ function pathKey(filePath) {
6
+ return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
7
+ }
8
+ function isErrno(error, code) {
9
+ return error?.code === code;
10
+ }
11
+ // Joins without path.join so `..` is not collapsed before the symlinks before it are followed.
12
+ function joinUnnormalized(base, relative) {
13
+ return base.endsWith(path.sep) ? `${base}${relative}` : `${base}${path.sep}${relative}`;
14
+ }
15
+ // Windows normalizes `..` lexically before resolving links; POSIX kernels do not.
16
+ function absoluteForResolution(targetPath) {
17
+ if (process.platform === 'win32')
18
+ return path.resolve(targetPath);
19
+ return path.isAbsolute(targetPath) ? targetPath : joinUnnormalized(process.cwd(), targetPath);
20
+ }
21
+ function resolveSegments(targetPath, followed) {
22
+ const absolute = absoluteForResolution(targetPath);
23
+ const root = path.parse(absolute).root;
24
+ const segments = absolute.slice(root.length).split(process.platform === 'win32' ? /[\\/]+/u : /\/+/u);
25
+ let current = root;
26
+ for (const segment of segments) {
27
+ if (segment === '' || segment === '.')
28
+ continue;
29
+ if (segment === '..') {
30
+ current = path.dirname(current);
31
+ continue;
32
+ }
33
+ const next = path.join(current, segment);
34
+ let stat;
35
+ try {
36
+ stat = fs.lstatSync(next);
37
+ }
38
+ catch (err) {
39
+ if (!isErrno(err, 'ENOENT'))
40
+ throw err;
41
+ // A missing directory would be created by a recursive mkdir, so keep walking past it.
42
+ current = next;
43
+ continue;
44
+ }
45
+ if (!stat.isSymbolicLink()) {
46
+ current = fs.realpathSync(next);
47
+ continue;
48
+ }
49
+ if (++followed.count > MAX_SYMLINK_DEPTH) {
50
+ throw new Error(`symlink loop detected while resolving path: ${targetPath}`);
51
+ }
52
+ const linkTarget = fs.readlinkSync(next);
53
+ current = resolveSegments(path.isAbsolute(linkTarget) ? linkTarget : joinUnnormalized(current, linkTarget), followed);
54
+ }
55
+ return current;
56
+ }
57
+ /**
58
+ * Resolves a path the way the OS would when writing it (after a recursive mkdir):
59
+ * existing segments are followed through symlinks (including dangling ones) and
60
+ * missing ones are kept, so boundary checks defeat `..` and symlink escapes.
61
+ */
62
+ export function canonicalizePath(targetPath) {
63
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') {
64
+ throw new Error('path must not be empty');
65
+ }
66
+ if (targetPath.includes('\0')) {
67
+ throw new Error('path contains null byte');
68
+ }
69
+ return resolveSegments(targetPath, { count: 0 });
70
+ }
71
+ function sameInode(a, b) {
72
+ if (!fs.existsSync(a) || !fs.existsSync(b))
73
+ return false;
74
+ const statA = fs.statSync(a, { bigint: true });
75
+ const statB = fs.statSync(b, { bigint: true });
76
+ return statA.dev === statB.dev && statA.ino === statB.ino;
77
+ }
78
+ /** True when both paths name the same file: canonical path match (case-folded on Windows) or same dev/ino. */
79
+ export function isSamePath(a, b) {
80
+ const canonicalA = canonicalizePath(a);
81
+ const canonicalB = canonicalizePath(b);
82
+ if (pathKey(canonicalA) === pathKey(canonicalB))
83
+ return true;
84
+ return sameInode(canonicalA, canonicalB);
85
+ }
86
+ export function assertNotProtectedPath(outputPath, protectedPaths, message) {
87
+ if (protectedPaths.some((target) => isSamePath(outputPath, target))) {
88
+ throw new Error(message);
89
+ }
90
+ }
91
+ /** Rejects an output path that names the archive database or one of its SQLite sidecars. */
92
+ export function assertNotArchiveFiles(outputPath, archiveDb, message = 'export file cannot overwrite the archive database') {
93
+ // SQLite names the sidecars after the symlink-resolved database path.
94
+ const databases = [archiveDb, canonicalizePath(archiveDb)];
95
+ assertNotProtectedPath(outputPath, databases.flatMap((db) => SQLITE_SIDECAR_SUFFIXES.map((suffix) => `${db}${suffix}`)), message);
96
+ }
package/dist/query.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { Bbox, LatLon } from 'drone-path-core/geo';
2
2
  import type { KinematicShot, ShotType } from 'drone-path-core/shot-segmentation';
3
3
  import type { ScanRecord } from './scanner.js';
4
4
  import type { IndexedClip, SegmentFilter } from './store.js';
5
- export { parseDateBound } from './camera-time.js';
5
+ export { dateRangeToBounds, parseDateBound } from './camera-time.js';
6
6
  export declare const DEFAULT_RADIUS_M = 100;
7
7
  export type ArchiveAvailability = IndexedClip['availability'];
8
8
  export type ArchiveClip = ScanRecord & {
@@ -14,12 +14,17 @@ export type FlightListClip = ArchiveClip & {
14
14
  export interface ArchiveFlight {
15
15
  flightId: string;
16
16
  clips: FlightListClip[];
17
+ startMs?: number | null;
17
18
  }
18
19
  export interface ListFilters {
19
20
  bbox?: Bbox;
20
21
  afterMs?: number;
21
22
  beforeMs?: number;
22
23
  minDistanceM?: number;
24
+ minDurationSec?: number;
25
+ maxDurationSec?: number;
26
+ hasGps?: boolean;
27
+ query?: string;
23
28
  availability?: ArchiveAvailability;
24
29
  segmentType?: ShotType;
25
30
  minSmoothness?: number;
@@ -34,8 +39,14 @@ export interface NearHit {
34
39
  matchType: 'track' | 'gaze';
35
40
  }
36
41
  export declare function segmentFilterOf({ segmentType, minSmoothness }: ListFilters): SegmentFilter | undefined;
37
- export declare function matchesMetadata(clip: ScanRecord, { afterMs, beforeMs, minDistanceM }: ListFilters): boolean;
42
+ export declare function matchesMetadata(clip: ScanRecord, { afterMs, beforeMs, minDistanceM, minDurationSec, maxDurationSec, hasGps, query }: ListFilters): boolean;
38
43
  export declare function listArchive(db: string, filters?: ListFilters): ArchiveClip[];
44
+ /** Reads only the video metadata of the indexed clips at `paths`, keyed by the requested path. */
45
+ export declare function readArchiveVideos(db: string, paths: readonly string[]): Map<string, NonNullable<ScanRecord['video']>>;
46
+ export declare function listArchiveVideos(db: string): {
47
+ path: string;
48
+ video: ScanRecord['video'];
49
+ }[];
39
50
  export declare function listArchiveFlights(db: string, filters?: ListFilters, options?: {
40
51
  overview?: boolean;
41
52
  }): ArchiveFlight[];
package/dist/query.js CHANGED
@@ -3,8 +3,8 @@ 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 { withArchiveStore } from './store.js';
7
- export { parseDateBound } from './camera-time.js';
6
+ import { archiveClipKey, withArchiveStore } from './store.js';
7
+ export { dateRangeToBounds, parseDateBound } from './camera-time.js';
8
8
  export const DEFAULT_RADIUS_M = 100;
9
9
  export function segmentFilterOf({ segmentType, minSmoothness }) {
10
10
  if (minSmoothness !== undefined && (!Number.isFinite(minSmoothness) || minSmoothness < 0 || minSmoothness > 1)) {
@@ -14,10 +14,35 @@ export function segmentFilterOf({ segmentType, minSmoothness }) {
14
14
  return undefined;
15
15
  return { segmentType, minSmoothness };
16
16
  }
17
- export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM }) {
17
+ function validateDurationBounds({ minDurationSec, maxDurationSec }) {
18
+ if (minDurationSec !== undefined && (!Number.isFinite(minDurationSec) || minDurationSec < 0)) {
19
+ throw new Error('expected a nonnegative minimum duration in seconds');
20
+ }
21
+ if (maxDurationSec !== undefined && (!Number.isFinite(maxDurationSec) || maxDurationSec < 0)) {
22
+ throw new Error('expected a nonnegative maximum duration in seconds');
23
+ }
24
+ }
25
+ export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM, minDurationSec, maxDurationSec, hasGps, query }) {
18
26
  if (minDistanceM !== undefined &&
19
27
  (clip.telemetry === null || clip.telemetry.trackDistanceM < minDistanceM))
20
28
  return false;
29
+ if (hasGps !== undefined) {
30
+ const clipHasGps = (clip.telemetry?.fixCount ?? 0) > 0;
31
+ if (clipHasGps !== hasGps)
32
+ return false;
33
+ }
34
+ if (minDurationSec !== undefined || maxDurationSec !== undefined) {
35
+ const durationSec = clip.video?.durationSec;
36
+ if (durationSec === null || durationSec === undefined)
37
+ return false;
38
+ if (minDurationSec !== undefined && durationSec < minDurationSec)
39
+ return false;
40
+ if (maxDurationSec !== undefined && durationSec > maxDurationSec)
41
+ return false;
42
+ }
43
+ const needle = query?.trim().toLowerCase() ?? '';
44
+ if (needle.length > 0 && !clip.path.toLowerCase().includes(needle))
45
+ return false;
21
46
  if (afterMs === undefined && beforeMs === undefined)
22
47
  return true;
23
48
  const time = clip.cameraCreationTime === null ? NaN : zonedTimeMs(clip.cameraCreationTime);
@@ -28,31 +53,56 @@ export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM }) {
28
53
  function toClip({ record, availability }) {
29
54
  return { ...record, availability };
30
55
  }
31
- function matchingClips(db, filters, overview = false) {
56
+ function matchingClips(store, filters, overview = false) {
57
+ validateDurationBounds(filters);
32
58
  const segmentFilter = segmentFilterOf(filters);
33
- return withArchiveStore(db, (store) => {
34
- const clips = overview
35
- ? store.listClipOverviews(filters.bbox, filters.availability, segmentFilter)
36
- : store.listClips(filters.bbox, filters.availability, segmentFilter);
37
- return clips.flatMap((indexed) => {
38
- const clip = toClip(indexed);
39
- return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
40
- });
59
+ const clips = overview
60
+ ? store.listClipOverviews(filters.bbox, filters.availability, segmentFilter)
61
+ : store.listClips(filters.bbox, filters.availability, segmentFilter);
62
+ return clips.flatMap((indexed) => {
63
+ const clip = toClip(indexed);
64
+ return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
41
65
  });
42
66
  }
43
67
  export function listArchive(db, filters = {}) {
44
- return matchingClips(db, filters).map(({ clip }) => clip);
68
+ return withArchiveStore(db, (store) => matchingClips(store, filters).map(({ clip }) => clip));
45
69
  }
46
- export function listArchiveFlights(db, filters = {}, options = {}) {
47
- const flights = groupFlightMembers(matchingClips(db, filters, options.overview === true));
48
- return [...flights].map(([flightId, members]) => ({
49
- flightId, clips: members.map(({ clip, flight }) => ({ ...clip, splitFromKey: flight.splitFromKey })),
70
+ /** Reads only the video metadata of the indexed clips at `paths`, keyed by the requested path. */
71
+ export function readArchiveVideos(db, paths) {
72
+ const keys = [...new Set(paths.map(archiveClipKey))];
73
+ const videos = withArchiveStore(db, (store) => store.readClipVideos(keys));
74
+ return new Map(paths.flatMap((file) => {
75
+ const video = videos.get(archiveClipKey(file));
76
+ return video ? [[file, video]] : [];
50
77
  }));
51
78
  }
79
+ export function listArchiveVideos(db) {
80
+ return withArchiveStore(db, (store) => store.indexedVideos());
81
+ }
82
+ export function listArchiveFlights(db, filters = {}, options = {}) {
83
+ return withArchiveStore(db, (store) => {
84
+ const flights = [...groupFlightMembers(matchingClips(store, filters, options.overview === true))];
85
+ // Filters can omit the clip that started a flight.
86
+ const starts = options.overview
87
+ ? store.readFlightStartTimes(flights.flatMap(([id, members]) => members[0].flight.order === 0 ? [] : [id]))
88
+ : undefined;
89
+ return flights.map(([flightId, members]) => {
90
+ const clips = members.map(({ clip, flight }) => ({ ...clip, splitFromKey: flight.splitFromKey }));
91
+ if (!options.overview)
92
+ return { flightId, clips };
93
+ const start = members[0].flight.order === 0
94
+ ? clips[0].cameraCreationTime
95
+ : starts?.get(flightId);
96
+ const startMs = start ? zonedTimeMs(start) : NaN;
97
+ return { flightId, clips, startMs: Number.isFinite(startMs) ? startMs : null };
98
+ });
99
+ });
100
+ }
52
101
  export function listArchiveFlightOverviews(db, filters = {}) {
53
102
  return listArchiveFlights(db, filters, { overview: true });
54
103
  }
55
104
  export function listArchiveSegments(db, filters = {}) {
105
+ validateDurationBounds(filters);
56
106
  const segmentFilter = segmentFilterOf(filters);
57
107
  return withArchiveStore(db, (store) => store.listSegments({
58
108
  bbox: filters.bbox,
@@ -1,6 +1,7 @@
1
1
  import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
2
2
  import type { ClipSharpnessSample, SharpnessAnalysisMode } from 'drone-path-core/sharpness';
3
3
  import type { ArchiveAvailability, ArchiveClip } from './query.js';
4
+ export { archiveClipKey } from './store.js';
4
5
  export declare const DEFAULT_SHARPNESS_QUERY_LIMIT = 200;
5
6
  export declare const MAX_SHARPNESS_QUERY_LIMIT = 2000;
6
7
  export interface SharpnessSettings {
@@ -71,7 +72,6 @@ export interface ExportArchiveSharpnessNdjsonResult {
71
72
  count: number;
72
73
  ndjson: string;
73
74
  }
74
- export declare function archiveClipKey(filePath: string): string;
75
75
  export declare function sharpnessFingerprintKey(size: number, mtimeMs: number): string;
76
76
  export declare function serializeSharpnessSettings(settings: SharpnessSettings): string;
77
77
  /** Run or reuse opt-in clip-wide sharpness analysis and atomically persist the result in SQLite. */
package/dist/sharpness.js CHANGED
@@ -4,14 +4,14 @@ import path from 'node:path';
4
4
  import { probeVideo } from 'drone-path-core/ffmpeg';
5
5
  import { DEFAULT_MIN_EDGE_COVERAGE, SHARPNESS_ANALYSIS_WIDTH, SHARPNESS_ANALYZER_METHOD, SHARPNESS_ANALYZER_VERSION, analyzeClipSharpness, } from 'drone-path-core/sharpness';
6
6
  import { createSrtSidecarLookup } from 'drone-path-core/srt-sidecar';
7
+ import { fingerprintsMatch, inspectClipInput } from './indexed-scan.js';
8
+ import { assertNotArchiveFiles, assertNotProtectedPath } from './output-guard.js';
7
9
  import { decimateSegments, sampleSegments } from './scan-track.js';
8
10
  import { scanRecording } from './scanner.js';
9
- import { CLIP_FINGERPRINT_VERSION, withArchiveStore } from './store.js';
11
+ import { archiveClipKey, withArchiveStore } from './store.js';
12
+ export { archiveClipKey } from './store.js';
10
13
  export const DEFAULT_SHARPNESS_QUERY_LIMIT = 200;
11
14
  export const MAX_SHARPNESS_QUERY_LIMIT = 2000;
12
- export function archiveClipKey(filePath) {
13
- return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
14
- }
15
15
  export function sharpnessFingerprintKey(size, mtimeMs) {
16
16
  return JSON.stringify({ size, mtimeMs });
17
17
  }
@@ -111,33 +111,24 @@ function resolveRunForClip(store, clip, options) {
111
111
  ...(options?.mode ? { mode: options.mode } : {}),
112
112
  });
113
113
  }
114
- function assertNotProtectedTarget(output, protectedFiles, errorMessageText) {
115
- const resolveCandidate = (file) => (fs.existsSync(file) ? fs.realpathSync(file) : path.resolve(file));
116
- const outResolved = resolveCandidate(output);
117
- for (const protectedFile of protectedFiles) {
118
- const protectedResolved = resolveCandidate(protectedFile);
119
- const same = process.platform === 'win32'
120
- ? outResolved.toLowerCase() === protectedResolved.toLowerCase()
121
- : outResolved === protectedResolved;
122
- if (same) {
123
- throw new Error(errorMessageText);
124
- }
125
- if (fs.existsSync(output) && fs.existsSync(protectedFile)) {
126
- const targetStat = fs.statSync(output, { bigint: true });
127
- const protectedStat = fs.statSync(protectedFile, { bigint: true });
128
- if (targetStat.dev === protectedStat.dev && targetStat.ino === protectedStat.ino) {
129
- throw new Error(errorMessageText);
130
- }
131
- }
132
- }
133
- }
134
- async function indexSingleClip(db, resolvedPath, key, expectedSize, expectedMtimeMs, tools, signal, assertAllowedPath) {
135
- const { revision } = withArchiveStore(db, (store) => store.snapshot());
114
+ function allowedSidecarLookup(assertAllowedPath) {
136
115
  const sidecarFor = createSrtSidecarLookup();
137
- const sidecar = await sidecarFor(resolvedPath);
116
+ return async (videoPath) => {
117
+ const sidecar = await sidecarFor(videoPath);
118
+ if (sidecar !== null)
119
+ assertAllowedPath?.(sidecar);
120
+ return sidecar;
121
+ };
122
+ }
123
+ function recordingChanged(resolvedPath) {
124
+ return new Error(`recording changed during sharpness analysis, rerun: ${resolvedPath}`);
125
+ }
126
+ async function indexSingleClip(db, resolvedPath, key, input, tools, signal, assertAllowedPath) {
127
+ const revision = withArchiveStore(db, (store) => store.currentRevision());
128
+ const { sidecar, fingerprint } = input;
129
+ // Re-check right before the scan reads the sidecar: awaiting the tools widens the swap window.
138
130
  if (sidecar !== null)
139
131
  assertAllowedPath?.(sidecar);
140
- const srtStat = sidecar === null ? null : await stat(sidecar).catch(() => null);
141
132
  let overview = [];
142
133
  let samples = [];
143
134
  let gaze;
@@ -160,32 +151,14 @@ async function indexSingleClip(db, resolvedPath, key, expectedSize, expectedMtim
160
151
  if (record.status === 'error') {
161
152
  throw new Error(record.error ?? `failed to inspect video: ${resolvedPath}`);
162
153
  }
163
- const currentStat = await stat(resolvedPath);
164
- if (currentStat.size !== expectedSize || currentStat.mtimeMs !== expectedMtimeMs) {
165
- throw new Error(`recording changed during sharpness analysis, rerun: ${resolvedPath}`);
166
- }
167
- const currentSidecar = await sidecarFor(resolvedPath);
168
- if (currentSidecar !== sidecar) {
169
- throw new Error(`recording changed during sharpness analysis, rerun: ${resolvedPath}`);
170
- }
171
- const currentSrtStat = currentSidecar === null ? null : await stat(currentSidecar).catch(() => null);
172
- const priorSrtSize = srtStat?.isFile() ? srtStat.size : null;
173
- const priorSrtMtimeMs = srtStat?.isFile() ? srtStat.mtimeMs : null;
174
- const nextSrtSize = currentSrtStat?.isFile() ? currentSrtStat.size : null;
175
- const nextSrtMtimeMs = currentSrtStat?.isFile() ? currentSrtStat.mtimeMs : null;
176
- if (priorSrtSize !== nextSrtSize || priorSrtMtimeMs !== nextSrtMtimeMs) {
177
- throw new Error(`recording changed during sharpness analysis, rerun: ${resolvedPath}`);
154
+ const current = await inspectClipInput(resolvedPath, allowedSidecarLookup(assertAllowedPath));
155
+ if (!current || current.sidecar !== sidecar || !fingerprintsMatch(current.fingerprint, fingerprint)) {
156
+ throw recordingChanged(resolvedPath);
178
157
  }
179
158
  const update = {
180
159
  key,
181
160
  availability: 'online',
182
- fingerprint: {
183
- size: expectedSize,
184
- mtimeMs: expectedMtimeMs,
185
- srtSize: priorSrtSize,
186
- srtMtimeMs: priorSrtMtimeMs,
187
- schemaVersion: CLIP_FINGERPRINT_VERSION,
188
- },
161
+ fingerprint,
189
162
  record,
190
163
  overview,
191
164
  samples,
@@ -221,16 +194,18 @@ export async function analyzeArchiveSharpness(db, videoPath, options) {
221
194
  if (!fileStat.isFile()) {
222
195
  throw new Error(`video path is not a regular file: ${videoPath}`);
223
196
  }
197
+ const current = await inspectClipInput(resolvedPath, allowedSidecarLookup(options.assertAllowedPath));
198
+ if (!current) {
199
+ throw new Error(`video file is not accessible: ${videoPath}`);
200
+ }
201
+ const { size, mtimeMs } = current.fingerprint;
224
202
  const key = archiveClipKey(resolvedPath);
225
- const fingerprintKey = sharpnessFingerprintKey(fileStat.size, fileStat.mtimeMs);
203
+ const fingerprintKey = sharpnessFingerprintKey(size, mtimeMs);
226
204
  let indexed = withArchiveStore(db, (store) => store.getClipByKey(key));
227
205
  let tools;
228
- if (!indexed ||
229
- indexed.record.status === 'error' ||
230
- indexed.fingerprint.size !== fileStat.size ||
231
- indexed.fingerprint.mtimeMs !== fileStat.mtimeMs) {
206
+ if (!indexed || indexed.record.status === 'error' || !fingerprintsMatch(current.fingerprint, indexed.fingerprint)) {
232
207
  tools = await options.getTools();
233
- indexed = await indexSingleClip(db, resolvedPath, key, fileStat.size, fileStat.mtimeMs, tools, options.signal, options.assertAllowedPath);
208
+ indexed = await indexSingleClip(db, resolvedPath, key, current, tools, options.signal, options.assertAllowedPath);
234
209
  }
235
210
  let fps = indexed.record.video?.fps.value;
236
211
  if (fps === undefined || !Number.isFinite(fps) || fps <= 0) {
@@ -270,13 +245,13 @@ export async function analyzeArchiveSharpness(db, videoPath, options) {
270
245
  const postStat = await stat(resolvedPath).catch((error) => {
271
246
  throw new Error(`video file is not accessible: ${videoPath}`, { cause: error });
272
247
  });
273
- if (!postStat.isFile() || postStat.size !== fileStat.size || postStat.mtimeMs !== fileStat.mtimeMs) {
274
- throw new Error(`recording changed during sharpness analysis, rerun: ${resolvedPath}`);
248
+ if (!postStat.isFile() || postStat.size !== size || postStat.mtimeMs !== mtimeMs) {
249
+ throw recordingChanged(resolvedPath);
275
250
  }
276
251
  const saved = withArchiveStore(db, (store) => store.saveSharpnessRun({
277
252
  clipKey: key,
278
253
  fingerprintKey,
279
- expectedFingerprint: { size: fileStat.size, mtimeMs: fileStat.mtimeMs },
254
+ expectedFingerprint: { size, mtimeMs },
280
255
  method: analyzed.analyzer.method,
281
256
  version: analyzed.analyzer.version,
282
257
  settingsJson,
@@ -376,8 +351,8 @@ export function exportArchiveSharpnessNdjson(db, videoPath, options = {}) {
376
351
  };
377
352
  });
378
353
  if (options.outPath !== undefined) {
379
- assertNotProtectedTarget(options.outPath, [db, `${db}-wal`, `${db}-shm`, `${db}-journal`], 'export file cannot overwrite the archive database');
380
- assertNotProtectedTarget(options.outPath, [result.clipPath, videoPath], 'export file cannot overwrite the source recording');
354
+ assertNotArchiveFiles(options.outPath, db);
355
+ assertNotProtectedPath(options.outPath, [result.clipPath, videoPath], 'export file cannot overwrite the source recording');
381
356
  fs.mkdirSync(path.dirname(options.outPath), { recursive: true });
382
357
  try {
383
358
  fs.writeFileSync(options.outPath, result.ndjson, {
package/dist/store.d.ts CHANGED
@@ -5,8 +5,10 @@ import type { KinematicShot, ShotType } from 'drone-path-core/shot-segmentation'
5
5
  import type { GazeSample } from './gaze.js';
6
6
  import type { ScanPoint, SparseSample } from './scan-track.js';
7
7
  import type { ScanRecord } from './scanner.js';
8
+ type ArchiveVideo = NonNullable<ScanRecord['video']>;
8
9
  export declare const ARCHIVE_SCHEMA_VERSION = 5;
9
10
  export declare const CLIP_FINGERPRINT_VERSION = 1;
11
+ export declare function archiveClipKey(filePath: string): string;
10
12
  export interface SegmentFilter {
11
13
  segmentType?: ShotType;
12
14
  minSmoothness?: number;
@@ -59,9 +61,11 @@ export interface SharpnessSampleFilter {
59
61
  limit?: number;
60
62
  offset?: number;
61
63
  }
64
+ type SharpnessRunKey = Pick<SharpnessRunRecord, 'clipKey' | 'fingerprintKey' | 'method' | 'version' | 'settingsJson'>;
62
65
  export declare class ArchiveStore {
63
66
  private readonly db;
64
67
  constructor(file: string);
68
+ private ensureFlightIndexes;
65
69
  private schemaVersion;
66
70
  private migrate;
67
71
  close(): void;
@@ -72,11 +76,18 @@ export declare class ArchiveStore {
72
76
  segmentsPending: boolean;
73
77
  })[];
74
78
  };
79
+ currentRevision(): number;
80
+ availabilityOf(key: string): IndexedClip['availability'] | null;
81
+ indexedPaths(): string[];
82
+ indexedVideos(): {
83
+ path: string;
84
+ video: ScanRecord['video'];
85
+ }[];
75
86
  listClips(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
76
87
  listClipOverviews(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
77
88
  private clipMatchesViewport;
78
89
  private selectClipViewport;
79
- readExportCandidates(bbox: Bbox | undefined, availability: IndexedClip['availability'] | undefined, matches: (clip: IndexedClip) => boolean, options: {
90
+ readExportCandidates(bbox: Bbox | undefined, availability: IndexedClip['availability'] | undefined, matches: (clip: IndexedFlightClip) => boolean, options: {
80
91
  includeGaze: boolean;
81
92
  redact: boolean;
82
93
  }, segmentFilter?: SegmentFilter): {
@@ -110,14 +121,9 @@ export declare class ArchiveStore {
110
121
  readSamples(key: string): SparseSample[];
111
122
  readSegments(key: string): KinematicShot[];
112
123
  getClipByKey(key: string): IndexedClip | null;
124
+ readClipVideos(keys: readonly string[]): Map<string, ArchiveVideo>;
113
125
  getSharpnessRun(runId: number): SharpnessRunRecord | null;
114
- findSharpnessRun(query: {
115
- clipKey: string;
116
- fingerprintKey: string;
117
- method: string;
118
- version: string;
119
- settingsJson: string;
120
- }): SharpnessRunRecord | null;
126
+ findSharpnessRun(query: SharpnessRunKey): SharpnessRunRecord | null;
121
127
  latestSharpnessRun(clipKey: string, filter?: {
122
128
  fingerprintKey?: string;
123
129
  mode?: SharpnessAnalysisMode;
@@ -144,6 +150,7 @@ export declare class ArchiveStore {
144
150
  private revision;
145
151
  private clipFilterClauses;
146
152
  private selectClips;
153
+ readFlightStartTimes(flightIds: readonly string[]): Map<string, string | null>;
147
154
  private refreshFlights;
148
155
  private transaction;
149
156
  private writeClip;
@@ -152,3 +159,4 @@ export declare class ArchiveStore {
152
159
  }
153
160
  export declare function withArchiveStore<T>(db: string, run: (store: ArchiveStore) => T): T;
154
161
  export declare function withArchiveStoreAsync<T>(db: string, run: (store: ArchiveStore) => Promise<T>): Promise<T>;
162
+ export {};
package/dist/store.js CHANGED
@@ -2,12 +2,16 @@ import { mkdirSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { DatabaseSync } from 'node:sqlite';
4
4
  import { groupFlights } from 'drone-path-core/flight-grouping';
5
+ import { isWithinRoot } from 'drone-path-core/paths';
5
6
  import { bboxIntersects, longitudeRanges, resolveTrackBbox } from 'drone-path-core/spatial';
6
7
  import { zonedTimeMs } from './camera-time.js';
7
8
  import { gazeBbox } from './gaze.js';
8
9
  import { groupSamples } from './scan-track.js';
9
10
  export const ARCHIVE_SCHEMA_VERSION = 5;
10
11
  export const CLIP_FINGERPRINT_VERSION = 1;
12
+ export function archiveClipKey(filePath) {
13
+ return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
14
+ }
11
15
  function decodeClip(row) {
12
16
  return {
13
17
  key: row.clip_key,
@@ -35,6 +39,22 @@ function decodeClipOverview(row) {
35
39
  record: { ...clip.record, track: JSON.parse(row.overview_json) },
36
40
  };
37
41
  }
42
+ const SEGMENT_COLUMNS = `segments.segment_type, segments.start_sec, segments.end_sec,
43
+ segments.duration_sec, segments.smoothness, segments.exposure_stable,
44
+ segments.mean_speed_mps, segments.mean_yaw_rate_deg_per_sec`;
45
+ function segmentFilterClauses(filter) {
46
+ const clauses = [];
47
+ const values = [];
48
+ if (filter.segmentType !== undefined) {
49
+ clauses.push('segments.segment_type = ?');
50
+ values.push(filter.segmentType);
51
+ }
52
+ if (filter.minSmoothness !== undefined) {
53
+ clauses.push('segments.smoothness >= ?');
54
+ values.push(filter.minSmoothness);
55
+ }
56
+ return { clauses, values };
57
+ }
38
58
  function decodeSegment(row) {
39
59
  return {
40
60
  type: row.segment_type,
@@ -47,6 +67,12 @@ function decodeSegment(row) {
47
67
  meanYawRateDegPerSec: row.mean_yaw_rate_deg_per_sec,
48
68
  };
49
69
  }
70
+ const SHARPNESS_RUN_COLUMNS = 'run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms';
71
+ // Mirrors the sharpness_runs UNIQUE constraint; sharpnessRunKeyValues binds in the same order.
72
+ const SHARPNESS_RUN_KEY_WHERE = 'clip_key = ? AND fingerprint_key = ? AND method = ? AND version = ? AND settings_json = ?';
73
+ function sharpnessRunKeyValues(key) {
74
+ return [key.clipKey, key.fingerprintKey, key.method, key.version, key.settingsJson];
75
+ }
50
76
  function decodeSharpnessRun(row) {
51
77
  return {
52
78
  runId: row.run_id,
@@ -67,14 +93,6 @@ function decodeSharpnessSample(row) {
67
93
  edgeCoverage: row.edge_coverage,
68
94
  };
69
95
  }
70
- function normalizeForCompare(target) {
71
- const resolved = path.resolve(target);
72
- return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
73
- }
74
- function isWithinRoot(root, filePath) {
75
- const rel = path.relative(normalizeForCompare(root), normalizeForCompare(filePath));
76
- return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
77
- }
78
96
  const SCHEMA = `
79
97
  CREATE TABLE archive_revision (revision INTEGER NOT NULL) STRICT;
80
98
  INSERT INTO archive_revision VALUES (0);
@@ -176,12 +194,25 @@ export class ArchiveStore {
176
194
  this.db.exec('PRAGMA foreign_keys = ON');
177
195
  if (this.schemaVersion() !== ARCHIVE_SCHEMA_VERSION)
178
196
  this.migrate();
197
+ this.ensureFlightIndexes();
179
198
  }
180
199
  catch (error) {
181
200
  this.db.close();
182
201
  throw error;
183
202
  }
184
203
  }
204
+ ensureFlightIndexes() {
205
+ // Older archive readers can still use the same schema after the indexes are added.
206
+ const indexes = {
207
+ clip_flight_starts: 'clip_flights (flight_id) WHERE flight_order = 0',
208
+ clip_flights_flight: 'clip_flights (flight_id, flight_order)',
209
+ };
210
+ const present = this.db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'index' AND name = ?");
211
+ for (const [name, definition] of Object.entries(indexes)) {
212
+ if (!present.get(name))
213
+ this.db.exec(`CREATE INDEX IF NOT EXISTS ${name} ON ${definition}`);
214
+ }
215
+ }
185
216
  schemaVersion() {
186
217
  return this.db.prepare('PRAGMA user_version').get()?.user_version;
187
218
  }
@@ -240,6 +271,29 @@ export class ArchiveStore {
240
271
  })),
241
272
  }));
242
273
  }
274
+ currentRevision() {
275
+ return this.revision();
276
+ }
277
+ availabilityOf(key) {
278
+ const row = this.db.prepare('SELECT availability FROM clips WHERE clip_key = ?').get(key);
279
+ return row?.availability ?? null;
280
+ }
281
+ indexedPaths() {
282
+ const rows = this.db.prepare(`
283
+ SELECT json_extract(record_json, '$.path') AS clip_path FROM clips ORDER BY clip_key
284
+ `).all();
285
+ return rows.flatMap(({ clip_path }) => (typeof clip_path === 'string' ? [clip_path] : []));
286
+ }
287
+ indexedVideos() {
288
+ const rows = this.db.prepare(`
289
+ SELECT json_extract(record_json, '$.path') AS clip_path,
290
+ json_extract(record_json, '$.video') AS video_json
291
+ FROM clips ORDER BY clip_key
292
+ `).all();
293
+ return rows.flatMap(({ clip_path, video_json }) => (typeof clip_path === 'string'
294
+ ? [{ path: clip_path, video: video_json === null ? null : JSON.parse(video_json) }]
295
+ : []));
296
+ }
243
297
  listClips(bbox, availability, segmentFilter) {
244
298
  if (bbox === undefined)
245
299
  return this.selectClips(undefined, availability, false, segmentFilter);
@@ -282,9 +336,12 @@ export class ArchiveStore {
282
336
  const endpoints = [];
283
337
  for (const direction of ['ASC', 'DESC']) {
284
338
  const statement = this.db.prepare(`
285
- SELECT lat, lon FROM clip_flights JOIN clip_samples USING (clip_key)
286
- WHERE flight_id = ?
287
- ORDER BY flight_order ${direction}, segment ${direction}, sample_index ${direction} LIMIT 1
339
+ SELECT lat, lon FROM clip_samples WHERE clip_key = (
340
+ SELECT clip_key FROM clip_flights
341
+ WHERE flight_id = ? AND EXISTS (SELECT 1 FROM clip_samples WHERE clip_samples.clip_key = clip_flights.clip_key)
342
+ ORDER BY flight_order ${direction} LIMIT 1
343
+ )
344
+ ORDER BY segment ${direction}, sample_index ${direction} LIMIT 1
288
345
  `);
289
346
  for (const id of flightIds) {
290
347
  const point = statement.get(id);
@@ -325,8 +382,7 @@ export class ArchiveStore {
325
382
  }
326
383
  readSegments(key) {
327
384
  const rows = this.db.prepare(`
328
- SELECT segment_type, start_sec, end_sec, duration_sec, smoothness,
329
- exposure_stable, mean_speed_mps, mean_yaw_rate_deg_per_sec
385
+ SELECT ${SEGMENT_COLUMNS}
330
386
  FROM segments WHERE clip_key = ? ORDER BY segment_index
331
387
  `).all(key);
332
388
  return rows.map(decodeSegment);
@@ -335,9 +391,19 @@ export class ArchiveStore {
335
391
  const row = this.db.prepare('SELECT * FROM clips WHERE clip_key = ?').get(key);
336
392
  return row ? decodeClip(row) : null;
337
393
  }
394
+ readClipVideos(keys) {
395
+ if (keys.length === 0)
396
+ return new Map();
397
+ const rows = this.db.prepare(`
398
+ SELECT clip_key, json_extract(record_json, '$.video') AS video_json
399
+ FROM clips JOIN clip_flights USING (clip_key)
400
+ WHERE clip_key IN (SELECT value FROM json_each(?)) AND video_json IS NOT NULL
401
+ `).all(JSON.stringify(keys));
402
+ return new Map(rows.map((row) => [row.clip_key, JSON.parse(row.video_json)]));
403
+ }
338
404
  getSharpnessRun(runId) {
339
405
  const row = this.db.prepare(`
340
- SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
406
+ SELECT ${SHARPNESS_RUN_COLUMNS}
341
407
  FROM sharpness_runs
342
408
  WHERE run_id = ?
343
409
  `).get(runId);
@@ -345,10 +411,10 @@ export class ArchiveStore {
345
411
  }
346
412
  findSharpnessRun(query) {
347
413
  const row = this.db.prepare(`
348
- SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
414
+ SELECT ${SHARPNESS_RUN_COLUMNS}
349
415
  FROM sharpness_runs
350
- WHERE clip_key = ? AND fingerprint_key = ? AND method = ? AND version = ? AND settings_json = ?
351
- `).get(query.clipKey, query.fingerprintKey, query.method, query.version, query.settingsJson);
416
+ WHERE ${SHARPNESS_RUN_KEY_WHERE}
417
+ `).get(...sharpnessRunKeyValues(query));
352
418
  return row ? decodeSharpnessRun(row) : null;
353
419
  }
354
420
  latestSharpnessRun(clipKey, filter) {
@@ -375,7 +441,7 @@ export class ArchiveStore {
375
441
  values.push(filter.settingsJson);
376
442
  }
377
443
  const row = this.db.prepare(`
378
- SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
444
+ SELECT ${SHARPNESS_RUN_COLUMNS}
379
445
  FROM sharpness_runs
380
446
  WHERE ${clauses.join(' AND ')}
381
447
  ORDER BY analyzed_at_ms DESC, run_id DESC
@@ -397,8 +463,8 @@ export class ArchiveStore {
397
463
  }
398
464
  this.db.prepare(`
399
465
  DELETE FROM sharpness_runs
400
- WHERE clip_key = ? AND fingerprint_key = ? AND method = ? AND version = ? AND settings_json = ?
401
- `).run(input.clipKey, input.fingerprintKey, input.method, input.version, input.settingsJson);
466
+ WHERE ${SHARPNESS_RUN_KEY_WHERE}
467
+ `).run(...sharpnessRunKeyValues(input));
402
468
  const inserted = this.db.prepare(`
403
469
  INSERT INTO sharpness_runs (
404
470
  clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
@@ -412,16 +478,11 @@ export class ArchiveStore {
412
478
  for (const sample of input.samples) {
413
479
  addSample.run(runId, sample.frameIndex, sample.tSec, sample.sharpnessScore, sample.edgeCoverage);
414
480
  }
415
- return {
416
- runId,
417
- clipKey: input.clipKey,
418
- fingerprintKey: input.fingerprintKey,
419
- method: input.method,
420
- version: input.version,
421
- settingsJson: input.settingsJson,
422
- sampleCount: input.samples.length,
423
- analyzedAtMs,
424
- };
481
+ const saved = this.getSharpnessRun(runId);
482
+ if (!saved) {
483
+ throw new Error(`sharpness run vanished after insert: ${runId}`);
484
+ }
485
+ return saved;
425
486
  });
426
487
  }
427
488
  sharpnessSampleWhere(runId, filter) {
@@ -469,19 +530,12 @@ export class ArchiveStore {
469
530
  listSegments(filters = {}) {
470
531
  return this.transaction('BEGIN', () => {
471
532
  const { clauses, values } = this.clipFilterClauses(filters.bbox, filters.availability, false);
472
- if (filters.segmentType !== undefined) {
473
- clauses.push('segments.segment_type = ?');
474
- values.push(filters.segmentType);
475
- }
476
- if (filters.minSmoothness !== undefined) {
477
- clauses.push('segments.smoothness >= ?');
478
- values.push(filters.minSmoothness);
479
- }
533
+ const segment = segmentFilterClauses(filters);
534
+ clauses.push(...segment.clauses);
535
+ values.push(...segment.values);
480
536
  const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
481
537
  const rows = this.db.prepare(`
482
- SELECT clips.*, segments.segment_type, segments.start_sec, segments.end_sec,
483
- segments.duration_sec, segments.smoothness, segments.exposure_stable,
484
- segments.mean_speed_mps, segments.mean_yaw_rate_deg_per_sec
538
+ SELECT clips.*, ${SEGMENT_COLUMNS}
485
539
  FROM segments JOIN clips USING (clip_key)
486
540
  ${where}
487
541
  ORDER BY segments.smoothness DESC, segments.clip_key ASC, segments.start_sec ASC
@@ -584,17 +638,11 @@ export class ArchiveStore {
584
638
  }
585
639
  values.push(bbox.maxLat, bbox.minLat, ...ranges.flatMap(([west, east]) => [east, west]));
586
640
  }
587
- if (segmentFilter?.segmentType !== undefined || segmentFilter?.minSmoothness !== undefined) {
588
- const segClauses = ['segments.clip_key = clips.clip_key'];
589
- if (segmentFilter.segmentType !== undefined) {
590
- segClauses.push('segments.segment_type = ?');
591
- values.push(segmentFilter.segmentType);
592
- }
593
- if (segmentFilter.minSmoothness !== undefined) {
594
- segClauses.push('segments.smoothness >= ?');
595
- values.push(segmentFilter.minSmoothness);
596
- }
597
- clauses.push(`EXISTS (SELECT 1 FROM segments WHERE ${segClauses.join(' AND ')})`);
641
+ const segment = segmentFilterClauses(segmentFilter ?? {});
642
+ if (segment.clauses.length > 0) {
643
+ const segmentClauses = ['segments.clip_key = clips.clip_key', ...segment.clauses];
644
+ clauses.push(`EXISTS (SELECT 1 FROM segments WHERE ${segmentClauses.join(' AND ')})`);
645
+ values.push(...segment.values);
598
646
  }
599
647
  return { clauses, values };
600
648
  }
@@ -613,6 +661,16 @@ export class ArchiveStore {
613
661
  ? rows.map(decodeClipOverview)
614
662
  : rows.map(decodeFlightClip);
615
663
  }
664
+ readFlightStartTimes(flightIds) {
665
+ if (flightIds.length === 0)
666
+ return new Map();
667
+ const rows = this.db.prepare(`
668
+ SELECT flight_id, json_extract(record_json, '$.cameraCreationTime') AS camera_time
669
+ FROM clip_flights JOIN clips USING (clip_key)
670
+ WHERE flight_order = 0 AND flight_id IN (SELECT value FROM json_each(?))
671
+ `).all(JSON.stringify(flightIds));
672
+ return new Map(rows.map(({ flight_id, camera_time }) => [flight_id, camera_time]));
673
+ }
616
674
  refreshFlights() {
617
675
  const rows = this.db.prepare(`
618
676
  SELECT clip_key, size, json_extract(record_json, '$.cameraCreationTime') AS camera_time,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-archive",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "Scan a local library of drone recordings.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "author": "Manuel Warum",
25
25
  "license": "MIT",
26
- "homepage": "https://www.dronepath.dev",
26
+ "homepage": "https://dronepath.dev",
27
27
  "keywords": [
28
28
  "dji",
29
29
  "drone",
@@ -40,8 +40,8 @@
40
40
  "directory": "packages/archive"
41
41
  },
42
42
  "dependencies": {
43
- "drone-path-core": "~1.2.0",
44
- "leaflet": "~1.9.4",
45
- "p-queue": "~10.0.0"
43
+ "drone-path-core": "^2.0.0",
44
+ "leaflet": "^1.9.4",
45
+ "p-queue": "^10.0.0"
46
46
  }
47
47
  }