drone-path-archive 1.2.1 → 2.0.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.
@@ -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 & {
@@ -21,6 +21,10 @@ export interface ListFilters {
21
21
  afterMs?: number;
22
22
  beforeMs?: number;
23
23
  minDistanceM?: number;
24
+ minDurationSec?: number;
25
+ maxDurationSec?: number;
26
+ hasGps?: boolean;
27
+ query?: string;
24
28
  availability?: ArchiveAvailability;
25
29
  segmentType?: ShotType;
26
30
  minSmoothness?: number;
@@ -35,8 +39,14 @@ export interface NearHit {
35
39
  matchType: 'track' | 'gaze';
36
40
  }
37
41
  export declare function segmentFilterOf({ segmentType, minSmoothness }: ListFilters): SegmentFilter | undefined;
38
- 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;
39
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
+ }[];
40
50
  export declare function listArchiveFlights(db: string, filters?: ListFilters, options?: {
41
51
  overview?: boolean;
42
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);
@@ -29,6 +54,7 @@ function toClip({ record, availability }) {
29
54
  return { ...record, availability };
30
55
  }
31
56
  function matchingClips(store, filters, overview = false) {
57
+ validateDurationBounds(filters);
32
58
  const segmentFilter = segmentFilterOf(filters);
33
59
  const clips = overview
34
60
  ? store.listClipOverviews(filters.bbox, filters.availability, segmentFilter)
@@ -41,6 +67,18 @@ function matchingClips(store, filters, overview = false) {
41
67
  export function listArchive(db, filters = {}) {
42
68
  return withArchiveStore(db, (store) => matchingClips(store, filters).map(({ clip }) => clip));
43
69
  }
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]] : [];
77
+ }));
78
+ }
79
+ export function listArchiveVideos(db) {
80
+ return withArchiveStore(db, (store) => store.indexedVideos());
81
+ }
44
82
  export function listArchiveFlights(db, filters = {}, options = {}) {
45
83
  return withArchiveStore(db, (store) => {
46
84
  const flights = [...groupFlightMembers(matchingClips(store, filters, options.overview === true))];
@@ -64,6 +102,7 @@ export function listArchiveFlightOverviews(db, filters = {}) {
64
102
  return listArchiveFlights(db, filters, { overview: true });
65
103
  }
66
104
  export function listArchiveSegments(db, filters = {}) {
105
+ validateDurationBounds(filters);
67
106
  const segmentFilter = segmentFilterOf(filters);
68
107
  return withArchiveStore(db, (store) => store.listSegments({
69
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,10 +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);
65
- private ensureFlightStartIndex;
68
+ private ensureFlightIndexes;
66
69
  private schemaVersion;
67
70
  private migrate;
68
71
  close(): void;
@@ -73,11 +76,18 @@ export declare class ArchiveStore {
73
76
  segmentsPending: boolean;
74
77
  })[];
75
78
  };
79
+ currentRevision(): number;
80
+ availabilityOf(key: string): IndexedClip['availability'] | null;
81
+ indexedPaths(): string[];
82
+ indexedVideos(): {
83
+ path: string;
84
+ video: ScanRecord['video'];
85
+ }[];
76
86
  listClips(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
77
87
  listClipOverviews(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
78
88
  private clipMatchesViewport;
79
89
  private selectClipViewport;
80
- 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: {
81
91
  includeGaze: boolean;
82
92
  redact: boolean;
83
93
  }, segmentFilter?: SegmentFilter): {
@@ -111,14 +121,9 @@ export declare class ArchiveStore {
111
121
  readSamples(key: string): SparseSample[];
112
122
  readSegments(key: string): KinematicShot[];
113
123
  getClipByKey(key: string): IndexedClip | null;
124
+ readClipVideos(keys: readonly string[]): Map<string, ArchiveVideo>;
114
125
  getSharpnessRun(runId: number): SharpnessRunRecord | null;
115
- findSharpnessRun(query: {
116
- clipKey: string;
117
- fingerprintKey: string;
118
- method: string;
119
- version: string;
120
- settingsJson: string;
121
- }): SharpnessRunRecord | null;
126
+ findSharpnessRun(query: SharpnessRunKey): SharpnessRunRecord | null;
122
127
  latestSharpnessRun(clipKey: string, filter?: {
123
128
  fingerprintKey?: string;
124
129
  mode?: SharpnessAnalysisMode;
@@ -154,3 +159,4 @@ export declare class ArchiveStore {
154
159
  }
155
160
  export declare function withArchiveStore<T>(db: string, run: (store: ArchiveStore) => T): T;
156
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,18 +194,23 @@ export class ArchiveStore {
176
194
  this.db.exec('PRAGMA foreign_keys = ON');
177
195
  if (this.schemaVersion() !== ARCHIVE_SCHEMA_VERSION)
178
196
  this.migrate();
179
- this.ensureFlightStartIndex();
197
+ this.ensureFlightIndexes();
180
198
  }
181
199
  catch (error) {
182
200
  this.db.close();
183
201
  throw error;
184
202
  }
185
203
  }
186
- ensureFlightStartIndex() {
187
- // Older archive readers can still use the same schema after the index is added.
188
- const present = this.db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'index' AND name = 'clip_flight_starts'").get();
189
- if (!present) {
190
- this.db.exec('CREATE INDEX IF NOT EXISTS clip_flight_starts ON clip_flights (flight_id) WHERE flight_order = 0');
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}`);
191
214
  }
192
215
  }
193
216
  schemaVersion() {
@@ -248,6 +271,29 @@ export class ArchiveStore {
248
271
  })),
249
272
  }));
250
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
+ }
251
297
  listClips(bbox, availability, segmentFilter) {
252
298
  if (bbox === undefined)
253
299
  return this.selectClips(undefined, availability, false, segmentFilter);
@@ -290,9 +336,12 @@ export class ArchiveStore {
290
336
  const endpoints = [];
291
337
  for (const direction of ['ASC', 'DESC']) {
292
338
  const statement = this.db.prepare(`
293
- SELECT lat, lon FROM clip_flights JOIN clip_samples USING (clip_key)
294
- WHERE flight_id = ?
295
- 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
296
345
  `);
297
346
  for (const id of flightIds) {
298
347
  const point = statement.get(id);
@@ -333,8 +382,7 @@ export class ArchiveStore {
333
382
  }
334
383
  readSegments(key) {
335
384
  const rows = this.db.prepare(`
336
- SELECT segment_type, start_sec, end_sec, duration_sec, smoothness,
337
- exposure_stable, mean_speed_mps, mean_yaw_rate_deg_per_sec
385
+ SELECT ${SEGMENT_COLUMNS}
338
386
  FROM segments WHERE clip_key = ? ORDER BY segment_index
339
387
  `).all(key);
340
388
  return rows.map(decodeSegment);
@@ -343,9 +391,19 @@ export class ArchiveStore {
343
391
  const row = this.db.prepare('SELECT * FROM clips WHERE clip_key = ?').get(key);
344
392
  return row ? decodeClip(row) : null;
345
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
+ }
346
404
  getSharpnessRun(runId) {
347
405
  const row = this.db.prepare(`
348
- SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
406
+ SELECT ${SHARPNESS_RUN_COLUMNS}
349
407
  FROM sharpness_runs
350
408
  WHERE run_id = ?
351
409
  `).get(runId);
@@ -353,10 +411,10 @@ export class ArchiveStore {
353
411
  }
354
412
  findSharpnessRun(query) {
355
413
  const row = this.db.prepare(`
356
- SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
414
+ SELECT ${SHARPNESS_RUN_COLUMNS}
357
415
  FROM sharpness_runs
358
- WHERE clip_key = ? AND fingerprint_key = ? AND method = ? AND version = ? AND settings_json = ?
359
- `).get(query.clipKey, query.fingerprintKey, query.method, query.version, query.settingsJson);
416
+ WHERE ${SHARPNESS_RUN_KEY_WHERE}
417
+ `).get(...sharpnessRunKeyValues(query));
360
418
  return row ? decodeSharpnessRun(row) : null;
361
419
  }
362
420
  latestSharpnessRun(clipKey, filter) {
@@ -383,7 +441,7 @@ export class ArchiveStore {
383
441
  values.push(filter.settingsJson);
384
442
  }
385
443
  const row = this.db.prepare(`
386
- SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
444
+ SELECT ${SHARPNESS_RUN_COLUMNS}
387
445
  FROM sharpness_runs
388
446
  WHERE ${clauses.join(' AND ')}
389
447
  ORDER BY analyzed_at_ms DESC, run_id DESC
@@ -405,8 +463,8 @@ export class ArchiveStore {
405
463
  }
406
464
  this.db.prepare(`
407
465
  DELETE FROM sharpness_runs
408
- WHERE clip_key = ? AND fingerprint_key = ? AND method = ? AND version = ? AND settings_json = ?
409
- `).run(input.clipKey, input.fingerprintKey, input.method, input.version, input.settingsJson);
466
+ WHERE ${SHARPNESS_RUN_KEY_WHERE}
467
+ `).run(...sharpnessRunKeyValues(input));
410
468
  const inserted = this.db.prepare(`
411
469
  INSERT INTO sharpness_runs (
412
470
  clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
@@ -420,16 +478,11 @@ export class ArchiveStore {
420
478
  for (const sample of input.samples) {
421
479
  addSample.run(runId, sample.frameIndex, sample.tSec, sample.sharpnessScore, sample.edgeCoverage);
422
480
  }
423
- return {
424
- runId,
425
- clipKey: input.clipKey,
426
- fingerprintKey: input.fingerprintKey,
427
- method: input.method,
428
- version: input.version,
429
- settingsJson: input.settingsJson,
430
- sampleCount: input.samples.length,
431
- analyzedAtMs,
432
- };
481
+ const saved = this.getSharpnessRun(runId);
482
+ if (!saved) {
483
+ throw new Error(`sharpness run vanished after insert: ${runId}`);
484
+ }
485
+ return saved;
433
486
  });
434
487
  }
435
488
  sharpnessSampleWhere(runId, filter) {
@@ -477,19 +530,12 @@ export class ArchiveStore {
477
530
  listSegments(filters = {}) {
478
531
  return this.transaction('BEGIN', () => {
479
532
  const { clauses, values } = this.clipFilterClauses(filters.bbox, filters.availability, false);
480
- if (filters.segmentType !== undefined) {
481
- clauses.push('segments.segment_type = ?');
482
- values.push(filters.segmentType);
483
- }
484
- if (filters.minSmoothness !== undefined) {
485
- clauses.push('segments.smoothness >= ?');
486
- values.push(filters.minSmoothness);
487
- }
533
+ const segment = segmentFilterClauses(filters);
534
+ clauses.push(...segment.clauses);
535
+ values.push(...segment.values);
488
536
  const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
489
537
  const rows = this.db.prepare(`
490
- SELECT clips.*, segments.segment_type, segments.start_sec, segments.end_sec,
491
- segments.duration_sec, segments.smoothness, segments.exposure_stable,
492
- segments.mean_speed_mps, segments.mean_yaw_rate_deg_per_sec
538
+ SELECT clips.*, ${SEGMENT_COLUMNS}
493
539
  FROM segments JOIN clips USING (clip_key)
494
540
  ${where}
495
541
  ORDER BY segments.smoothness DESC, segments.clip_key ASC, segments.start_sec ASC
@@ -592,17 +638,11 @@ export class ArchiveStore {
592
638
  }
593
639
  values.push(bbox.maxLat, bbox.minLat, ...ranges.flatMap(([west, east]) => [east, west]));
594
640
  }
595
- if (segmentFilter?.segmentType !== undefined || segmentFilter?.minSmoothness !== undefined) {
596
- const segClauses = ['segments.clip_key = clips.clip_key'];
597
- if (segmentFilter.segmentType !== undefined) {
598
- segClauses.push('segments.segment_type = ?');
599
- values.push(segmentFilter.segmentType);
600
- }
601
- if (segmentFilter.minSmoothness !== undefined) {
602
- segClauses.push('segments.smoothness >= ?');
603
- values.push(segmentFilter.minSmoothness);
604
- }
605
- 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);
606
646
  }
607
647
  return { clauses, values };
608
648
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-archive",
3
- "version": "1.2.1",
3
+ "version": "2.0.1",
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.1",
44
- "leaflet": "~1.9.4",
45
- "p-queue": "~10.0.0"
43
+ "drone-path-core": "^2.0.1",
44
+ "leaflet": "^1.9.4",
45
+ "p-queue": "^10.0.0"
46
46
  }
47
47
  }