drone-path-archive 1.1.0 → 1.2.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.
@@ -8,5 +8,7 @@ interface MapClip {
8
8
  export interface MapFlight {
9
9
  clips: MapClip[];
10
10
  }
11
- export declare function archiveMapHtml(flights: readonly MapFlight[]): string;
11
+ export declare function archiveMapHtml(flights: readonly MapFlight[], { offline }?: {
12
+ offline?: boolean;
13
+ }): string;
12
14
  export {};
@@ -2,6 +2,23 @@ import fs from 'node:fs';
2
2
  import { createRequire } from 'node:module';
3
3
  import path from 'node:path';
4
4
  const require = createRequire(import.meta.url);
5
+ // The video renderer has a self-contained module graph and serves tiles through its local cache.
6
+ const BASEMAPS = {
7
+ satellite: {
8
+ url: 'https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
9
+ subdomains: [''],
10
+ attribution: '<a href="https://www.esri.com/">Powered by Esri</a> | Imagery &copy; Esri, Vantor, Earthstar Geographics, and the GIS User Community',
11
+ maxZoom: 19,
12
+ },
13
+ topo: {
14
+ url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
15
+ subdomains: ['a', 'b', 'c'],
16
+ attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, SRTM | Style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (CC-BY-SA)',
17
+ maxZoom: 19,
18
+ maxNativeZoom: 17,
19
+ },
20
+ };
21
+ const tileOrigins = [...new Set(Object.values(BASEMAPS).flatMap(({ url, subdomains }) => subdomains.map((subdomain) => new URL(url.replace('{s}', subdomain)).origin)))].join(' ');
5
22
  function leafletAssets() {
6
23
  const root = path.dirname(require.resolve('leaflet/package.json'));
7
24
  const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
@@ -11,11 +28,42 @@ function leafletAssets() {
11
28
  const css = read('dist/leaflet.css').replace(/url\([^)]*\)/gu, 'none');
12
29
  return { script, css, license: read('LICENSE') };
13
30
  }
14
- function mapClient() {
31
+ function basemapClient() {
32
+ return String.raw `
33
+ const { satellite, topo } = ${JSON.stringify(BASEMAPS)};
34
+ const { url: topoUrl, ...topoOptions } = topo;
35
+ const { url: imageryUrl, ...imageryOptions } = satellite;
36
+ const imagery = L.layerGroup();
37
+ const baseLayers = {
38
+ Topographic: L.tileLayer(topoUrl, topoOptions).addTo(map),
39
+ 'Esri imagery': imagery,
40
+ 'No basemap': L.layerGroup(),
41
+ };
42
+ const credentials = document.querySelector('#esri-credentials');
43
+ const apiKey = document.querySelector('#esri-key');
44
+ const tileError = document.querySelector('#esri-tile-error');
45
+ map.on('baselayerchange', ({ layer }) => {
46
+ credentials.hidden = layer !== imagery;
47
+ });
48
+ credentials.addEventListener('submit', (event) => {
49
+ event.preventDefault();
50
+ const key = apiKey.value.trim();
51
+ if (!key || !map.hasLayer(imagery)) return;
52
+ apiKey.value = '';
53
+ tileError.hidden = true;
54
+ imagery.clearLayers();
55
+ L.tileLayer(imageryUrl + '?token=' + encodeURIComponent(key), imageryOptions)
56
+ .on('tileerror', () => { tileError.hidden = false; })
57
+ .addTo(imagery);
58
+ });
59
+ `;
60
+ }
61
+ function mapClient(offline) {
15
62
  // Kept separate from export data: popup text is only assigned to DOM nodes.
16
63
  return String.raw `
17
64
  const flights = JSON.parse(document.querySelector('#archive-data').textContent);
18
- const map = L.map('map', { attributionControl: false });
65
+ const map = L.map('map');
66
+ ${offline ? 'const baseLayers = {};' : basemapClient()}
19
67
  const bounds = L.latLngBounds([]);
20
68
  const colors = ['#1565c0', '#a33e00', '#00736e', '#a12466', '#613aa1', '#537421'];
21
69
  const anchor = flights.flatMap((flight) => flight.clips)
@@ -55,7 +103,10 @@ for (const [index, flight] of flights.entries()) {
55
103
  }
56
104
  }
57
105
  }
58
- if (hasGaze) L.control.layers({}, { 'Camera footprints': footprints.addTo(map) }, { collapsed: false }).addTo(map);
106
+ const overlays = hasGaze ? { 'Camera footprints': footprints.addTo(map) } : {};
107
+ if (Object.keys(baseLayers).length || hasGaze) {
108
+ L.control.layers(baseLayers, overlays, { collapsed: false }).addTo(map);
109
+ }
59
110
  if (bounds.isValid()) map.fitBounds(bounds, { padding: [24, 24], maxZoom: 17 });
60
111
  else {
61
112
  map.setView([0, 0], 2);
@@ -63,7 +114,7 @@ else {
63
114
  }
64
115
  `;
65
116
  }
66
- export function archiveMapHtml(flights) {
117
+ export function archiveMapHtml(flights, { offline = false } = {}) {
67
118
  const { script, css, license } = leafletAssets();
68
119
  const data = JSON.stringify(flights).replaceAll('<', '\\u003c');
69
120
  return `<!doctype html>
@@ -71,24 +122,31 @@ export function archiveMapHtml(flights) {
71
122
  <head>
72
123
  <meta charset="utf-8">
73
124
  <meta name="viewport" content="width=device-width, initial-scale=1">
74
- <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'">
125
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; form-action 'none'; img-src ${offline ? "'none'" : tileOrigins}">
75
126
  <title>Drone Path archive</title>
76
127
  <style>
77
128
  ${css}
78
129
  html,body,#map{height:100%;margin:0}
79
130
  #map{background:#f4f6f7}
80
131
  #empty{position:absolute;z-index:1000;left:50%;top:1rem;transform:translateX(-50%);padding:.6rem 1rem;background:white;border:1px solid #aeb6bd;font:1rem system-ui,sans-serif}
132
+ #esri-credentials{position:absolute;z-index:1000;right:10px;bottom:24px;padding:.6rem;background:white;font:.9rem system-ui,sans-serif}
81
133
  </style>
82
134
  </head>
83
135
  <body>
84
136
  <div id="map" aria-label="Flight map"></div>
85
137
  <div id="empty" hidden>No tracks match this export.</div>
138
+ ${offline ? '' : `<form id="esri-credentials" autocomplete="off" hidden>
139
+ <label for="esri-key">ArcGIS API key</label>
140
+ <input id="esri-key" type="password" required>
141
+ <button type="submit">Load Esri imagery</button>
142
+ <p id="esri-tile-error" role="status" hidden>Some Esri tiles could not load. Check your key and connection.</p>
143
+ </form>`}
86
144
  <script type="application/json" id="archive-data">${data}</script>
87
145
  <!--
88
146
  ${license}
89
147
  -->
90
148
  <script>${script}</script>
91
- <script>${mapClient()}</script>
149
+ <script>${mapClient(offline)}</script>
92
150
  </body>
93
151
  </html>
94
152
  `;
package/dist/export.d.ts CHANGED
@@ -4,7 +4,9 @@ interface ExportOptions {
4
4
  redactLaunchM?: number;
5
5
  includeGaze?: boolean;
6
6
  }
7
- export declare function exportArchiveMap(db: string, output: string, options?: ExportOptions): void;
7
+ export declare function exportArchiveMap(db: string, output: string, options?: ExportOptions & {
8
+ offline?: boolean;
9
+ }): void;
8
10
  export declare function exportArchiveTracks(db: string, output: string, options?: Omit<ExportOptions, 'includeGaze'>): void;
9
11
  export declare function exportArchiveMarkers(db: string, output: string, options?: {
10
12
  filters?: ListFilters;
package/dist/export.js CHANGED
@@ -60,7 +60,7 @@ function writeExport(db, output, content) {
60
60
  export function exportArchiveMap(db, output, options = {}) {
61
61
  if (path.extname(output).toLowerCase() !== '.html')
62
62
  throw new Error('expected an .html output file');
63
- writeExport(db, output, archiveMapHtml(exportFlights(db, options)));
63
+ writeExport(db, output, archiveMapHtml(exportFlights(db, options), { offline: options.offline }));
64
64
  }
65
65
  export function exportArchiveTracks(db, output, options = {}) {
66
66
  const format = trackFormatOf(output);
package/dist/query.d.ts CHANGED
@@ -36,6 +36,10 @@ export interface NearHit {
36
36
  export declare function segmentFilterOf({ segmentType, minSmoothness }: ListFilters): SegmentFilter | undefined;
37
37
  export declare function matchesMetadata(clip: ScanRecord, { afterMs, beforeMs, minDistanceM }: ListFilters): boolean;
38
38
  export declare function listArchive(db: string, filters?: ListFilters): ArchiveClip[];
39
- export declare function listArchiveFlights(db: string, filters?: ListFilters): ArchiveFlight[];
39
+ export declare function listArchiveFlights(db: string, filters?: ListFilters, options?: {
40
+ overview?: boolean;
41
+ }): ArchiveFlight[];
42
+ export declare function listArchiveFlightOverviews(db: string, filters?: ListFilters): ArchiveFlight[];
40
43
  export declare function listArchiveSegments(db: string, filters?: ListFilters): ArchiveSegment[];
41
44
  export declare function nearArchive(db: string, point: LatLon, radiusM?: number, includeGaze?: boolean): NearHit[];
45
+ export declare function pruneArchiveOffline(db: string): number;
package/dist/query.js CHANGED
@@ -28,22 +28,30 @@ export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM }) {
28
28
  function toClip({ record, availability }) {
29
29
  return { ...record, availability };
30
30
  }
31
- function matchingClips(db, filters) {
31
+ function matchingClips(db, filters, overview = false) {
32
32
  const segmentFilter = segmentFilterOf(filters);
33
- return withArchiveStore(db, (store) => store.listClips(filters.bbox, filters.availability, segmentFilter).flatMap((indexed) => {
34
- const clip = toClip(indexed);
35
- return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
36
- }));
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
+ });
41
+ });
37
42
  }
38
43
  export function listArchive(db, filters = {}) {
39
44
  return matchingClips(db, filters).map(({ clip }) => clip);
40
45
  }
41
- export function listArchiveFlights(db, filters = {}) {
42
- const flights = groupFlightMembers(matchingClips(db, filters));
46
+ export function listArchiveFlights(db, filters = {}, options = {}) {
47
+ const flights = groupFlightMembers(matchingClips(db, filters, options.overview === true));
43
48
  return [...flights].map(([flightId, members]) => ({
44
49
  flightId, clips: members.map(({ clip, flight }) => ({ ...clip, splitFromKey: flight.splitFromKey })),
45
50
  }));
46
51
  }
52
+ export function listArchiveFlightOverviews(db, filters = {}) {
53
+ return listArchiveFlights(db, filters, { overview: true });
54
+ }
47
55
  export function listArchiveSegments(db, filters = {}) {
48
56
  const segmentFilter = segmentFilterOf(filters);
49
57
  return withArchiveStore(db, (store) => store.listSegments({
@@ -75,3 +83,6 @@ export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze =
75
83
  return hits.sort((a, b) => a.distanceM - b.distanceM);
76
84
  });
77
85
  }
86
+ export function pruneArchiveOffline(db) {
87
+ return withArchiveStore(db, (store) => store.pruneOffline());
88
+ }
@@ -0,0 +1,82 @@
1
+ import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
2
+ import type { ClipSharpnessSample, SharpnessAnalysisMode } from 'drone-path-core/sharpness';
3
+ import type { ArchiveAvailability, ArchiveClip } from './query.js';
4
+ export declare const DEFAULT_SHARPNESS_QUERY_LIMIT = 200;
5
+ export declare const MAX_SHARPNESS_QUERY_LIMIT = 2000;
6
+ export interface SharpnessSettings {
7
+ mode: SharpnessAnalysisMode;
8
+ stride: number;
9
+ analysisWidth: number;
10
+ minEdgeCoverage: number;
11
+ }
12
+ export interface ArchiveSharpnessRun {
13
+ runId: number;
14
+ clipKey: string;
15
+ fingerprintKey: string;
16
+ method: string;
17
+ version: string;
18
+ settings: SharpnessSettings;
19
+ sampleCount: number;
20
+ analyzedAtMs: number;
21
+ }
22
+ export interface AnalyzeArchiveSharpnessOptions {
23
+ mode?: SharpnessAnalysisMode;
24
+ analysisWidth?: number;
25
+ minEdgeCoverage?: number;
26
+ force?: boolean;
27
+ signal?: AbortSignal;
28
+ getTools: () => Promise<FfmpegToolPaths>;
29
+ assertAllowedPath?: (filePath: string) => void;
30
+ onSample?: (sample: ClipSharpnessSample) => void;
31
+ }
32
+ export interface AnalyzeArchiveSharpnessResult {
33
+ clip: ArchiveClip;
34
+ clipKey: string;
35
+ cached: boolean;
36
+ run: ArchiveSharpnessRun;
37
+ }
38
+ export interface GetArchiveSharpnessOptions {
39
+ mode?: SharpnessAnalysisMode;
40
+ runId?: number;
41
+ startSec?: number;
42
+ endSec?: number;
43
+ limit?: number;
44
+ offset?: number;
45
+ }
46
+ export interface ArchiveSharpnessTimeline {
47
+ clipPath: string;
48
+ clipKey: string;
49
+ availability: ArchiveAvailability;
50
+ analyzed: boolean;
51
+ run: ArchiveSharpnessRun | null;
52
+ totalSamples: number;
53
+ limit: number;
54
+ offset: number;
55
+ truncated: boolean;
56
+ samples: ClipSharpnessSample[];
57
+ }
58
+ export interface ExportArchiveSharpnessNdjsonOptions {
59
+ mode?: SharpnessAnalysisMode;
60
+ runId?: number;
61
+ startSec?: number;
62
+ endSec?: number;
63
+ outPath?: string;
64
+ overwrite?: boolean;
65
+ }
66
+ export interface ExportArchiveSharpnessNdjsonResult {
67
+ clipPath: string;
68
+ clipKey: string;
69
+ availability: ArchiveAvailability;
70
+ run: ArchiveSharpnessRun;
71
+ count: number;
72
+ ndjson: string;
73
+ }
74
+ export declare function archiveClipKey(filePath: string): string;
75
+ export declare function sharpnessFingerprintKey(size: number, mtimeMs: number): string;
76
+ export declare function serializeSharpnessSettings(settings: SharpnessSettings): string;
77
+ /** Run or reuse opt-in clip-wide sharpness analysis and atomically persist the result in SQLite. */
78
+ export declare function analyzeArchiveSharpness(db: string, videoPath: string, options: AnalyzeArchiveSharpnessOptions): Promise<AnalyzeArchiveSharpnessResult>;
79
+ /** Query stored sharpness samples offline with time-range filtering and bounded pagination. */
80
+ export declare function getArchiveSharpness(db: string, videoPath: string, options?: GetArchiveSharpnessOptions): ArchiveSharpnessTimeline;
81
+ /** Export the full matching sharpness timeline as NDJSON, optionally writing to a file. */
82
+ export declare function exportArchiveSharpnessNdjson(db: string, videoPath: string, options?: ExportArchiveSharpnessNdjsonOptions): ExportArchiveSharpnessNdjsonResult;
@@ -0,0 +1,396 @@
1
+ import fs from 'node:fs';
2
+ import { realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { probeVideo } from 'drone-path-core/ffmpeg';
5
+ import { DEFAULT_MIN_EDGE_COVERAGE, SHARPNESS_ANALYSIS_WIDTH, SHARPNESS_ANALYZER_METHOD, SHARPNESS_ANALYZER_VERSION, analyzeClipSharpness, } from 'drone-path-core/sharpness';
6
+ import { createSrtSidecarLookup } from 'drone-path-core/srt-sidecar';
7
+ import { decimateSegments, sampleSegments } from './scan-track.js';
8
+ import { scanRecording } from './scanner.js';
9
+ import { CLIP_FINGERPRINT_VERSION, withArchiveStore } from './store.js';
10
+ export const DEFAULT_SHARPNESS_QUERY_LIMIT = 200;
11
+ export const MAX_SHARPNESS_QUERY_LIMIT = 2000;
12
+ export function archiveClipKey(filePath) {
13
+ return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
14
+ }
15
+ export function sharpnessFingerprintKey(size, mtimeMs) {
16
+ return JSON.stringify({ size, mtimeMs });
17
+ }
18
+ export function serializeSharpnessSettings(settings) {
19
+ return JSON.stringify({
20
+ mode: settings.mode,
21
+ stride: settings.stride,
22
+ analysisWidth: settings.analysisWidth,
23
+ minEdgeCoverage: settings.minEdgeCoverage,
24
+ });
25
+ }
26
+ function decodeArchiveRun(row) {
27
+ return {
28
+ runId: row.runId,
29
+ clipKey: row.clipKey,
30
+ fingerprintKey: row.fingerprintKey,
31
+ method: row.method,
32
+ version: row.version,
33
+ settings: JSON.parse(row.settingsJson),
34
+ sampleCount: row.sampleCount,
35
+ analyzedAtMs: row.analyzedAtMs,
36
+ };
37
+ }
38
+ function validateMode(mode) {
39
+ const resolved = mode ?? 'sampled';
40
+ if (resolved !== 'sampled' && resolved !== 'every-frame') {
41
+ throw new Error(`invalid sharpness analysis mode: ${String(resolved)}`);
42
+ }
43
+ return resolved;
44
+ }
45
+ function validateTimeRange(startSec, endSec) {
46
+ if (startSec !== undefined && (!Number.isFinite(startSec) || startSec < 0)) {
47
+ throw new Error('expected a non-negative finite startSec');
48
+ }
49
+ if (endSec !== undefined && (!Number.isFinite(endSec) || endSec < 0)) {
50
+ throw new Error('expected a non-negative finite endSec');
51
+ }
52
+ if (startSec !== undefined && endSec !== undefined && startSec > endSec) {
53
+ throw new Error('expected startSec at or before endSec');
54
+ }
55
+ }
56
+ function validatePaging(limit, offset) {
57
+ const resolvedLimit = limit ?? DEFAULT_SHARPNESS_QUERY_LIMIT;
58
+ if (!Number.isInteger(resolvedLimit) || resolvedLimit < 1 || resolvedLimit > MAX_SHARPNESS_QUERY_LIMIT) {
59
+ throw new Error(`expected limit to be an integer between 1 and ${MAX_SHARPNESS_QUERY_LIMIT}`);
60
+ }
61
+ const resolvedOffset = offset ?? 0;
62
+ if (!Number.isInteger(resolvedOffset) || resolvedOffset < 0) {
63
+ throw new Error('expected offset to be a non-negative integer');
64
+ }
65
+ return { limit: resolvedLimit, offset: resolvedOffset };
66
+ }
67
+ function resolveClipInStore(store, videoPath) {
68
+ const candidates = [];
69
+ const addCandidate = (candidatePath) => {
70
+ const key = archiveClipKey(candidatePath);
71
+ if (!candidates.includes(key))
72
+ candidates.push(key);
73
+ };
74
+ try {
75
+ if (fs.existsSync(videoPath)) {
76
+ addCandidate(fs.realpathSync(videoPath));
77
+ }
78
+ }
79
+ catch {
80
+ // Fall through to directory / lexical candidates when offline or inaccessible.
81
+ }
82
+ try {
83
+ const dir = path.dirname(videoPath);
84
+ if (fs.existsSync(dir)) {
85
+ addCandidate(path.join(fs.realpathSync(dir), path.basename(videoPath)));
86
+ }
87
+ }
88
+ catch {
89
+ // Fall through to lexical candidates.
90
+ }
91
+ addCandidate(path.resolve(videoPath));
92
+ addCandidate(videoPath);
93
+ for (const key of candidates) {
94
+ const clip = store.getClipByKey(key);
95
+ if (clip)
96
+ return clip;
97
+ }
98
+ return null;
99
+ }
100
+ function resolveRunForClip(store, clip, options) {
101
+ if (options?.runId !== undefined) {
102
+ if (!Number.isInteger(options.runId) || options.runId < 1) {
103
+ throw new Error('expected a positive integer runId');
104
+ }
105
+ const run = store.getSharpnessRun(options.runId);
106
+ return run && run.clipKey === clip.key ? run : null;
107
+ }
108
+ const fingerprintKey = sharpnessFingerprintKey(clip.fingerprint.size, clip.fingerprint.mtimeMs);
109
+ return store.latestSharpnessRun(clip.key, {
110
+ fingerprintKey,
111
+ ...(options?.mode ? { mode: options.mode } : {}),
112
+ });
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());
136
+ const sidecarFor = createSrtSidecarLookup();
137
+ const sidecar = await sidecarFor(resolvedPath);
138
+ if (sidecar !== null)
139
+ assertAllowedPath?.(sidecar);
140
+ const srtStat = sidecar === null ? null : await stat(sidecar).catch(() => null);
141
+ let overview = [];
142
+ let samples = [];
143
+ let gaze;
144
+ let segments;
145
+ const record = await scanRecording(resolvedPath, {
146
+ tools,
147
+ signal,
148
+ sidecarFor: () => sidecar,
149
+ onGaze: (_file, g) => {
150
+ gaze = g;
151
+ },
152
+ onSegments: (_file, s) => {
153
+ segments = s;
154
+ },
155
+ onTrack: (_file, segs) => {
156
+ overview = decimateSegments(segs, 60, 9);
157
+ samples = sampleSegments(segs);
158
+ },
159
+ });
160
+ if (record.status === 'error') {
161
+ throw new Error(record.error ?? `failed to inspect video: ${resolvedPath}`);
162
+ }
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}`);
178
+ }
179
+ const update = {
180
+ key,
181
+ availability: 'online',
182
+ fingerprint: {
183
+ size: expectedSize,
184
+ mtimeMs: expectedMtimeMs,
185
+ srtSize: priorSrtSize,
186
+ srtMtimeMs: priorSrtMtimeMs,
187
+ schemaVersion: CLIP_FINGERPRINT_VERSION,
188
+ },
189
+ record,
190
+ overview,
191
+ samples,
192
+ gaze,
193
+ segments,
194
+ };
195
+ withArchiveStore(db, (store) => {
196
+ store.commit(revision, [update], [], [], []);
197
+ });
198
+ return update;
199
+ }
200
+ /** Run or reuse opt-in clip-wide sharpness analysis and atomically persist the result in SQLite. */
201
+ export async function analyzeArchiveSharpness(db, videoPath, options) {
202
+ const mode = validateMode(options.mode);
203
+ const analysisWidth = options.analysisWidth ?? SHARPNESS_ANALYSIS_WIDTH;
204
+ if (!Number.isInteger(analysisWidth) || analysisWidth < 1) {
205
+ throw new Error('sharpness analysis width must be a positive integer');
206
+ }
207
+ const minEdgeCoverage = options.minEdgeCoverage ?? DEFAULT_MIN_EDGE_COVERAGE;
208
+ if (!Number.isFinite(minEdgeCoverage) || minEdgeCoverage < 0 || minEdgeCoverage > 1) {
209
+ throw new Error(`invalid sharpness min-edge-coverage: ${minEdgeCoverage}`);
210
+ }
211
+ options.signal?.throwIfAborted();
212
+ let resolvedPath;
213
+ let fileStat;
214
+ try {
215
+ resolvedPath = await realpath(videoPath);
216
+ fileStat = await stat(resolvedPath);
217
+ }
218
+ catch (error) {
219
+ throw new Error(`video file is not accessible: ${videoPath}`, { cause: error });
220
+ }
221
+ if (!fileStat.isFile()) {
222
+ throw new Error(`video path is not a regular file: ${videoPath}`);
223
+ }
224
+ const key = archiveClipKey(resolvedPath);
225
+ const fingerprintKey = sharpnessFingerprintKey(fileStat.size, fileStat.mtimeMs);
226
+ let indexed = withArchiveStore(db, (store) => store.getClipByKey(key));
227
+ let tools;
228
+ if (!indexed ||
229
+ indexed.record.status === 'error' ||
230
+ indexed.fingerprint.size !== fileStat.size ||
231
+ indexed.fingerprint.mtimeMs !== fileStat.mtimeMs) {
232
+ tools = await options.getTools();
233
+ indexed = await indexSingleClip(db, resolvedPath, key, fileStat.size, fileStat.mtimeMs, tools, options.signal, options.assertAllowedPath);
234
+ }
235
+ let fps = indexed.record.video?.fps.value;
236
+ if (fps === undefined || !Number.isFinite(fps) || fps <= 0) {
237
+ tools ??= await options.getTools();
238
+ const probe = await probeVideo(tools, resolvedPath, undefined, options.signal);
239
+ fps = probe.fps.value;
240
+ }
241
+ const stride = mode === 'every-frame' ? 1 : Math.max(1, Math.round(fps));
242
+ const settings = { mode, stride, analysisWidth, minEdgeCoverage };
243
+ const settingsJson = serializeSharpnessSettings(settings);
244
+ if (!options.force) {
245
+ const cachedRun = withArchiveStore(db, (store) => store.findSharpnessRun({
246
+ clipKey: key,
247
+ fingerprintKey,
248
+ method: SHARPNESS_ANALYZER_METHOD,
249
+ version: SHARPNESS_ANALYZER_VERSION,
250
+ settingsJson,
251
+ }));
252
+ if (cachedRun) {
253
+ return {
254
+ clip: { ...indexed.record, availability: indexed.availability },
255
+ clipKey: key,
256
+ cached: true,
257
+ run: decodeArchiveRun(cachedRun),
258
+ };
259
+ }
260
+ }
261
+ tools ??= await options.getTools();
262
+ const analyzed = await analyzeClipSharpness(tools, resolvedPath, {
263
+ mode,
264
+ fps,
265
+ analysisWidth,
266
+ minEdgeCoverage,
267
+ signal: options.signal,
268
+ onSample: options.onSample,
269
+ });
270
+ const postStat = await stat(resolvedPath).catch((error) => {
271
+ throw new Error(`video file is not accessible: ${videoPath}`, { cause: error });
272
+ });
273
+ if (!postStat.isFile() || postStat.size !== fileStat.size || postStat.mtimeMs !== fileStat.mtimeMs) {
274
+ throw new Error(`recording changed during sharpness analysis, rerun: ${resolvedPath}`);
275
+ }
276
+ const saved = withArchiveStore(db, (store) => store.saveSharpnessRun({
277
+ clipKey: key,
278
+ fingerprintKey,
279
+ expectedFingerprint: { size: fileStat.size, mtimeMs: fileStat.mtimeMs },
280
+ method: analyzed.analyzer.method,
281
+ version: analyzed.analyzer.version,
282
+ settingsJson,
283
+ samples: analyzed.samples,
284
+ }));
285
+ return {
286
+ clip: { ...indexed.record, availability: indexed.availability },
287
+ clipKey: key,
288
+ cached: false,
289
+ run: decodeArchiveRun(saved),
290
+ };
291
+ }
292
+ /** Query stored sharpness samples offline with time-range filtering and bounded pagination. */
293
+ export function getArchiveSharpness(db, videoPath, options = {}) {
294
+ if (options.mode !== undefined)
295
+ validateMode(options.mode);
296
+ validateTimeRange(options.startSec, options.endSec);
297
+ const { limit, offset } = validatePaging(options.limit, options.offset);
298
+ return withArchiveStore(db, (store) => {
299
+ const clip = resolveClipInStore(store, videoPath);
300
+ if (!clip) {
301
+ throw new Error(`clip is not indexed in archive: ${videoPath}`);
302
+ }
303
+ const run = resolveRunForClip(store, clip, {
304
+ mode: options.mode,
305
+ runId: options.runId,
306
+ });
307
+ if (!run) {
308
+ return {
309
+ clipPath: clip.record.path,
310
+ clipKey: clip.key,
311
+ availability: clip.availability,
312
+ analyzed: false,
313
+ run: null,
314
+ totalSamples: 0,
315
+ limit,
316
+ offset,
317
+ truncated: false,
318
+ samples: [],
319
+ };
320
+ }
321
+ const totalSamples = store.countSharpnessSamples(run.runId, {
322
+ startSec: options.startSec,
323
+ endSec: options.endSec,
324
+ });
325
+ const samples = store.readSharpnessSamples(run.runId, {
326
+ startSec: options.startSec,
327
+ endSec: options.endSec,
328
+ limit,
329
+ offset,
330
+ });
331
+ return {
332
+ clipPath: clip.record.path,
333
+ clipKey: clip.key,
334
+ availability: clip.availability,
335
+ analyzed: true,
336
+ run: decodeArchiveRun(run),
337
+ totalSamples,
338
+ limit,
339
+ offset,
340
+ truncated: offset + samples.length < totalSamples,
341
+ samples,
342
+ };
343
+ });
344
+ }
345
+ /** Export the full matching sharpness timeline as NDJSON, optionally writing to a file. */
346
+ export function exportArchiveSharpnessNdjson(db, videoPath, options = {}) {
347
+ if (options.mode !== undefined)
348
+ validateMode(options.mode);
349
+ validateTimeRange(options.startSec, options.endSec);
350
+ const result = withArchiveStore(db, (store) => {
351
+ const clip = resolveClipInStore(store, videoPath);
352
+ if (!clip) {
353
+ throw new Error(`clip is not indexed in archive: ${videoPath}`);
354
+ }
355
+ const run = resolveRunForClip(store, clip, {
356
+ mode: options.mode,
357
+ runId: options.runId,
358
+ });
359
+ if (!run) {
360
+ throw new Error(`no sharpness analysis found for clip: ${clip.record.path}`);
361
+ }
362
+ const samples = store.readSharpnessSamples(run.runId, {
363
+ startSec: options.startSec,
364
+ endSec: options.endSec,
365
+ });
366
+ const ndjson = samples.length > 0
367
+ ? samples.map((sample) => JSON.stringify(sample)).join('\n') + '\n'
368
+ : '';
369
+ return {
370
+ clipPath: clip.record.path,
371
+ clipKey: clip.key,
372
+ availability: clip.availability,
373
+ run: decodeArchiveRun(run),
374
+ count: samples.length,
375
+ ndjson,
376
+ };
377
+ });
378
+ 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');
381
+ fs.mkdirSync(path.dirname(options.outPath), { recursive: true });
382
+ try {
383
+ fs.writeFileSync(options.outPath, result.ndjson, {
384
+ encoding: 'utf8',
385
+ flag: options.overwrite ? 'w' : 'wx',
386
+ });
387
+ }
388
+ catch (error) {
389
+ if (error?.code === 'EEXIST') {
390
+ throw new Error(`refusing to overwrite existing sharpness export file: ${options.outPath}`, { cause: error });
391
+ }
392
+ throw error;
393
+ }
394
+ }
395
+ return result;
396
+ }
package/dist/store.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import type { FlightMembership } from 'drone-path-core/flight-grouping';
2
2
  import type { Bbox, LatLon } from 'drone-path-core/geo';
3
+ import type { ClipSharpnessSample, SharpnessAnalysisMode } from 'drone-path-core/sharpness';
3
4
  import type { KinematicShot, ShotType } from 'drone-path-core/shot-segmentation';
4
5
  import type { GazeSample } from './gaze.js';
5
6
  import type { ScanPoint, SparseSample } from './scan-track.js';
6
7
  import type { ScanRecord } from './scanner.js';
7
- export declare const ARCHIVE_SCHEMA_VERSION = 4;
8
+ export declare const ARCHIVE_SCHEMA_VERSION = 5;
8
9
  export declare const CLIP_FINGERPRINT_VERSION = 1;
9
10
  export interface SegmentFilter {
10
11
  segmentType?: ShotType;
@@ -32,6 +33,32 @@ export interface ClipUpdate extends IndexedClip {
32
33
  export interface IndexedFlightClip extends IndexedClip {
33
34
  flight: FlightMembership;
34
35
  }
36
+ export interface SharpnessRunRecord {
37
+ runId: number;
38
+ clipKey: string;
39
+ fingerprintKey: string;
40
+ method: string;
41
+ version: string;
42
+ settingsJson: string;
43
+ sampleCount: number;
44
+ analyzedAtMs: number;
45
+ }
46
+ export interface SaveSharpnessRunInput {
47
+ clipKey: string;
48
+ fingerprintKey: string;
49
+ expectedFingerprint?: Pick<ClipFingerprint, 'size' | 'mtimeMs'>;
50
+ method: string;
51
+ version: string;
52
+ settingsJson: string;
53
+ analyzedAtMs?: number;
54
+ samples: readonly ClipSharpnessSample[];
55
+ }
56
+ export interface SharpnessSampleFilter {
57
+ startSec?: number;
58
+ endSec?: number;
59
+ limit?: number;
60
+ offset?: number;
61
+ }
35
62
  export declare class ArchiveStore {
36
63
  private readonly db;
37
64
  constructor(file: string);
@@ -46,6 +73,7 @@ export declare class ArchiveStore {
46
73
  })[];
47
74
  };
48
75
  listClips(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
76
+ listClipOverviews(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
49
77
  private clipMatchesViewport;
50
78
  private selectClipViewport;
51
79
  readExportCandidates(bbox: Bbox | undefined, availability: IndexedClip['availability'] | undefined, matches: (clip: IndexedClip) => boolean, options: {
@@ -81,6 +109,26 @@ export declare class ArchiveStore {
81
109
  readOverview(key: string): ScanPoint[][];
82
110
  readSamples(key: string): SparseSample[];
83
111
  readSegments(key: string): KinematicShot[];
112
+ getClipByKey(key: string): IndexedClip | null;
113
+ 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;
121
+ latestSharpnessRun(clipKey: string, filter?: {
122
+ fingerprintKey?: string;
123
+ mode?: SharpnessAnalysisMode;
124
+ method?: string;
125
+ version?: string;
126
+ settingsJson?: string;
127
+ }): SharpnessRunRecord | null;
128
+ saveSharpnessRun(input: SaveSharpnessRunInput): SharpnessRunRecord;
129
+ private sharpnessSampleWhere;
130
+ countSharpnessSamples(runId: number, filter?: Pick<SharpnessSampleFilter, 'startSec' | 'endSec'>): number;
131
+ readSharpnessSamples(runId: number, filter?: SharpnessSampleFilter): ClipSharpnessSample[];
84
132
  listSegments(filters?: {
85
133
  bbox?: Bbox;
86
134
  availability?: IndexedClip['availability'];
@@ -91,6 +139,8 @@ export declare class ArchiveStore {
91
139
  segment: KinematicShot;
92
140
  }[];
93
141
  commit(expectedRevision: number, updates: readonly ClipUpdate[], online: readonly string[], offline: readonly string[], removed: readonly string[]): void;
142
+ removeClipsUnder(root: string): number;
143
+ pruneOffline(): number;
94
144
  private revision;
95
145
  private clipFilterClauses;
96
146
  private selectClips;
package/dist/store.js CHANGED
@@ -6,7 +6,7 @@ import { bboxIntersects, longitudeRanges, resolveTrackBbox } from 'drone-path-co
6
6
  import { zonedTimeMs } from './camera-time.js';
7
7
  import { gazeBbox } from './gaze.js';
8
8
  import { groupSamples } from './scan-track.js';
9
- export const ARCHIVE_SCHEMA_VERSION = 4;
9
+ export const ARCHIVE_SCHEMA_VERSION = 5;
10
10
  export const CLIP_FINGERPRINT_VERSION = 1;
11
11
  function decodeClip(row) {
12
12
  return {
@@ -28,6 +28,13 @@ function decodeFlightClip(row) {
28
28
  },
29
29
  };
30
30
  }
31
+ function decodeClipOverview(row) {
32
+ const clip = decodeFlightClip(row);
33
+ return {
34
+ ...clip,
35
+ record: { ...clip.record, track: JSON.parse(row.overview_json) },
36
+ };
37
+ }
31
38
  function decodeSegment(row) {
32
39
  return {
33
40
  type: row.segment_type,
@@ -40,6 +47,34 @@ function decodeSegment(row) {
40
47
  meanYawRateDegPerSec: row.mean_yaw_rate_deg_per_sec,
41
48
  };
42
49
  }
50
+ function decodeSharpnessRun(row) {
51
+ return {
52
+ runId: row.run_id,
53
+ clipKey: row.clip_key,
54
+ fingerprintKey: row.fingerprint_key,
55
+ method: row.method,
56
+ version: row.version,
57
+ settingsJson: row.settings_json,
58
+ sampleCount: row.sample_count,
59
+ analyzedAtMs: row.analyzed_at_ms,
60
+ };
61
+ }
62
+ function decodeSharpnessSample(row) {
63
+ return {
64
+ frameIndex: row.frame_index,
65
+ tSec: row.t_sec,
66
+ sharpnessScore: row.sharpness_score,
67
+ edgeCoverage: row.edge_coverage,
68
+ };
69
+ }
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
+ }
43
78
  const SCHEMA = `
44
79
  CREATE TABLE archive_revision (revision INTEGER NOT NULL) STRICT;
45
80
  INSERT INTO archive_revision VALUES (0);
@@ -105,6 +140,31 @@ const SEGMENTS_SCHEMA = `
105
140
  ) STRICT;
106
141
  CREATE INDEX IF NOT EXISTS segments_type_smoothness ON segments (segment_type, smoothness DESC);
107
142
  `;
143
+ const SHARPNESS_SCHEMA = `
144
+ CREATE TABLE IF NOT EXISTS sharpness_runs (
145
+ run_id INTEGER PRIMARY KEY,
146
+ clip_key TEXT NOT NULL REFERENCES clips (clip_key) ON DELETE CASCADE,
147
+ fingerprint_key TEXT NOT NULL,
148
+ method TEXT NOT NULL,
149
+ version TEXT NOT NULL,
150
+ settings_json TEXT NOT NULL,
151
+ sample_count INTEGER NOT NULL,
152
+ analyzed_at_ms INTEGER NOT NULL,
153
+ UNIQUE (clip_key, fingerprint_key, method, version, settings_json)
154
+ ) STRICT;
155
+ CREATE INDEX IF NOT EXISTS sharpness_runs_clip_latest
156
+ ON sharpness_runs (clip_key, analyzed_at_ms DESC, run_id DESC);
157
+ CREATE TABLE IF NOT EXISTS sharpness_samples (
158
+ run_id INTEGER NOT NULL REFERENCES sharpness_runs (run_id) ON DELETE CASCADE,
159
+ frame_index INTEGER NOT NULL,
160
+ t_sec REAL NOT NULL,
161
+ sharpness_score REAL,
162
+ edge_coverage REAL NOT NULL,
163
+ PRIMARY KEY (run_id, frame_index)
164
+ ) STRICT;
165
+ CREATE INDEX IF NOT EXISTS sharpness_samples_run_time
166
+ ON sharpness_samples (run_id, t_sec, frame_index);
167
+ `;
108
168
  export class ArchiveStore {
109
169
  db;
110
170
  constructor(file) {
@@ -154,6 +214,9 @@ export class ArchiveStore {
154
214
  }
155
215
  this.db.exec(SEGMENTS_SCHEMA);
156
216
  }
217
+ if (version < 5) {
218
+ this.db.exec(SHARPNESS_SCHEMA);
219
+ }
157
220
  this.db.exec(`PRAGMA user_version = ${ARCHIVE_SCHEMA_VERSION}`);
158
221
  });
159
222
  }
@@ -182,6 +245,11 @@ export class ArchiveStore {
182
245
  return this.selectClips(undefined, availability, false, segmentFilter);
183
246
  return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter));
184
247
  }
248
+ listClipOverviews(bbox, availability, segmentFilter) {
249
+ if (bbox === undefined)
250
+ return this.selectClips(undefined, availability, false, segmentFilter, true);
251
+ return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter, true));
252
+ }
185
253
  clipMatchesViewport(bbox, key, record) {
186
254
  const raw = record.bbox;
187
255
  if (raw === null)
@@ -190,8 +258,8 @@ export class ArchiveStore {
190
258
  return true;
191
259
  return bboxIntersects(bbox, resolveTrackBbox(raw, [...record.track, ...groupSamples(this.readSamples(key))]));
192
260
  }
193
- selectClipViewport(bbox, availability, segmentFilter) {
194
- const clips = this.selectClips(bbox, availability, false, segmentFilter);
261
+ selectClipViewport(bbox, availability, segmentFilter, overviewOnly = false) {
262
+ const clips = this.selectClips(bbox, availability, false, segmentFilter, overviewOnly);
195
263
  if (bbox === undefined)
196
264
  return clips;
197
265
  return clips.filter(({ key, record }) => this.clipMatchesViewport(bbox, key, record));
@@ -263,6 +331,141 @@ export class ArchiveStore {
263
331
  `).all(key);
264
332
  return rows.map(decodeSegment);
265
333
  }
334
+ getClipByKey(key) {
335
+ const row = this.db.prepare('SELECT * FROM clips WHERE clip_key = ?').get(key);
336
+ return row ? decodeClip(row) : null;
337
+ }
338
+ getSharpnessRun(runId) {
339
+ const row = this.db.prepare(`
340
+ SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
341
+ FROM sharpness_runs
342
+ WHERE run_id = ?
343
+ `).get(runId);
344
+ return row ? decodeSharpnessRun(row) : null;
345
+ }
346
+ findSharpnessRun(query) {
347
+ const row = this.db.prepare(`
348
+ SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
349
+ 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);
352
+ return row ? decodeSharpnessRun(row) : null;
353
+ }
354
+ latestSharpnessRun(clipKey, filter) {
355
+ const clauses = ['clip_key = ?'];
356
+ const values = [clipKey];
357
+ if (filter?.fingerprintKey !== undefined) {
358
+ clauses.push('fingerprint_key = ?');
359
+ values.push(filter.fingerprintKey);
360
+ }
361
+ if (filter?.mode !== undefined) {
362
+ clauses.push("json_extract(settings_json, '$.mode') = ?");
363
+ values.push(filter.mode);
364
+ }
365
+ if (filter?.method !== undefined) {
366
+ clauses.push('method = ?');
367
+ values.push(filter.method);
368
+ }
369
+ if (filter?.version !== undefined) {
370
+ clauses.push('version = ?');
371
+ values.push(filter.version);
372
+ }
373
+ if (filter?.settingsJson !== undefined) {
374
+ clauses.push('settings_json = ?');
375
+ values.push(filter.settingsJson);
376
+ }
377
+ const row = this.db.prepare(`
378
+ SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
379
+ FROM sharpness_runs
380
+ WHERE ${clauses.join(' AND ')}
381
+ ORDER BY analyzed_at_ms DESC, run_id DESC
382
+ LIMIT 1
383
+ `).get(...values);
384
+ return row ? decodeSharpnessRun(row) : null;
385
+ }
386
+ saveSharpnessRun(input) {
387
+ const analyzedAtMs = input.analyzedAtMs ?? Date.now();
388
+ return this.transaction('BEGIN IMMEDIATE', () => {
389
+ const clip = this.getClipByKey(input.clipKey);
390
+ if (!clip) {
391
+ throw new Error(`clip is not indexed in archive: ${input.clipKey}`);
392
+ }
393
+ if (input.expectedFingerprint !== undefined &&
394
+ (clip.fingerprint.size !== input.expectedFingerprint.size ||
395
+ clip.fingerprint.mtimeMs !== input.expectedFingerprint.mtimeMs)) {
396
+ throw new Error(`clip fingerprint changed during sharpness analysis: ${input.clipKey}`);
397
+ }
398
+ this.db.prepare(`
399
+ 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);
402
+ const inserted = this.db.prepare(`
403
+ INSERT INTO sharpness_runs (
404
+ clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
405
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
406
+ `).run(input.clipKey, input.fingerprintKey, input.method, input.version, input.settingsJson, input.samples.length, analyzedAtMs);
407
+ const runId = Number(inserted.lastInsertRowid);
408
+ const addSample = this.db.prepare(`
409
+ INSERT INTO sharpness_samples (run_id, frame_index, t_sec, sharpness_score, edge_coverage)
410
+ VALUES (?, ?, ?, ?, ?)
411
+ `);
412
+ for (const sample of input.samples) {
413
+ addSample.run(runId, sample.frameIndex, sample.tSec, sample.sharpnessScore, sample.edgeCoverage);
414
+ }
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
+ };
425
+ });
426
+ }
427
+ sharpnessSampleWhere(runId, filter) {
428
+ const clauses = ['run_id = ?'];
429
+ const values = [runId];
430
+ if (filter?.startSec !== undefined) {
431
+ clauses.push('t_sec >= ?');
432
+ values.push(filter.startSec);
433
+ }
434
+ if (filter?.endSec !== undefined) {
435
+ clauses.push('t_sec <= ?');
436
+ values.push(filter.endSec);
437
+ }
438
+ return { where: `WHERE ${clauses.join(' AND ')}`, values };
439
+ }
440
+ countSharpnessSamples(runId, filter) {
441
+ const { where, values } = this.sharpnessSampleWhere(runId, filter);
442
+ const row = this.db.prepare(`SELECT COUNT(*) AS count FROM sharpness_samples ${where}`).get(...values);
443
+ return row.count;
444
+ }
445
+ readSharpnessSamples(runId, filter) {
446
+ const { where, values } = this.sharpnessSampleWhere(runId, filter);
447
+ let paging = '';
448
+ if (filter?.limit !== undefined) {
449
+ paging += ' LIMIT ?';
450
+ values.push(filter.limit);
451
+ if (filter.offset !== undefined) {
452
+ paging += ' OFFSET ?';
453
+ values.push(filter.offset);
454
+ }
455
+ }
456
+ else if (filter?.offset !== undefined) {
457
+ paging += ' LIMIT -1 OFFSET ?';
458
+ values.push(filter.offset);
459
+ }
460
+ const rows = this.db.prepare(`
461
+ SELECT frame_index, t_sec, sharpness_score, edge_coverage
462
+ FROM sharpness_samples
463
+ ${where}
464
+ ORDER BY frame_index ASC
465
+ ${paging}
466
+ `).all(...values);
467
+ return rows.map(decodeSharpnessSample);
468
+ }
266
469
  listSegments(filters = {}) {
267
470
  return this.transaction('BEGIN', () => {
268
471
  const { clauses, values } = this.clipFilterClauses(filters.bbox, filters.availability, false);
@@ -323,6 +526,35 @@ export class ArchiveStore {
323
526
  }
324
527
  });
325
528
  }
529
+ removeClipsUnder(root) {
530
+ return this.transaction('BEGIN IMMEDIATE', () => {
531
+ const rows = this.db.prepare(`
532
+ SELECT clip_key, json_extract(record_json, '$.path') AS clip_path FROM clips
533
+ `).all();
534
+ const matched = rows
535
+ .filter((row) => typeof row.clip_path === 'string' && isWithinRoot(root, row.clip_path))
536
+ .map((row) => row.clip_key);
537
+ if (matched.length === 0)
538
+ return 0;
539
+ const remove = this.db.prepare('DELETE FROM clips WHERE clip_key = ?');
540
+ for (const key of matched)
541
+ remove.run(key);
542
+ this.refreshFlights();
543
+ this.db.exec('UPDATE archive_revision SET revision = revision + 1');
544
+ return matched.length;
545
+ });
546
+ }
547
+ pruneOffline() {
548
+ return this.transaction('BEGIN IMMEDIATE', () => {
549
+ const { changes } = this.db.prepare("DELETE FROM clips WHERE availability = 'offline'").run();
550
+ const count = Number(changes);
551
+ if (count === 0)
552
+ return 0;
553
+ this.refreshFlights();
554
+ this.db.exec('UPDATE archive_revision SET revision = revision + 1');
555
+ return count;
556
+ });
557
+ }
326
558
  revision() {
327
559
  return this.db.prepare('SELECT revision FROM archive_revision').get()?.revision;
328
560
  }
@@ -366,13 +598,20 @@ export class ArchiveStore {
366
598
  }
367
599
  return { clauses, values };
368
600
  }
369
- selectClips(bbox, availability, includeArcs, segmentFilter) {
601
+ selectClips(bbox, availability, includeArcs, segmentFilter, overviewOnly = false) {
370
602
  const { clauses, values } = this.clipFilterClauses(bbox, availability, includeArcs, segmentFilter);
371
603
  const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
604
+ const columns = overviewOnly
605
+ ? `clips.clip_key, clips.availability, clips.size, clips.mtime_ms, clips.srt_size, clips.srt_mtime_ms,
606
+ clips.schema_version, json_set(clips.record_json, '$.track', json('[]')) AS record_json,
607
+ clips.overview_json, clip_flights.flight_id, clip_flights.flight_order, clip_flights.split_from_key`
608
+ : '*';
372
609
  const rows = this.db.prepare(`
373
- SELECT * FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
610
+ SELECT ${columns} FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
374
611
  `).all(...values);
375
- return rows.map(decodeFlightClip);
612
+ return overviewOnly
613
+ ? rows.map(decodeClipOverview)
614
+ : rows.map(decodeFlightClip);
376
615
  }
377
616
  refreshFlights() {
378
617
  const rows = this.db.prepare(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-archive",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Scan a local library of drone recordings.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,18 +18,29 @@
18
18
  "node": ">=24"
19
19
  },
20
20
  "scripts": {
21
- "build": "node ../../scripts/clean-package-dist.mjs && tsc -p tsconfig.json",
22
- "prepack": "npm run build --workspace drone-path-core --prefix ../.. && npm run build"
21
+ "build": "tsc -b",
22
+ "prepack": "node ../../scripts/clean-package-dist.mjs && tsc -b"
23
23
  },
24
24
  "author": "Manuel Warum",
25
25
  "license": "MIT",
26
+ "homepage": "https://www.dronepath.dev",
27
+ "keywords": [
28
+ "dji",
29
+ "drone",
30
+ "telemetry",
31
+ "gpx",
32
+ "srt",
33
+ "kml",
34
+ "mcp",
35
+ "davinci-resolve"
36
+ ],
26
37
  "repository": {
27
38
  "type": "git",
28
39
  "url": "git+https://github.com/MrManny/drone-path.git",
29
40
  "directory": "packages/archive"
30
41
  },
31
42
  "dependencies": {
32
- "drone-path-core": "~1.1.0",
43
+ "drone-path-core": "~1.2.0",
33
44
  "leaflet": "~1.9.4",
34
45
  "p-queue": "~10.0.0"
35
46
  }