drone-path-archive 1.1.1 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/query.d.ts +6 -1
- package/dist/query.js +31 -9
- package/dist/sharpness.d.ts +82 -0
- package/dist/sharpness.js +396 -0
- package/dist/store.d.ts +53 -1
- package/dist/store.js +263 -6
- package/package.json +15 -4
package/dist/query.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export type FlightListClip = ArchiveClip & {
|
|
|
14
14
|
export interface ArchiveFlight {
|
|
15
15
|
flightId: string;
|
|
16
16
|
clips: FlightListClip[];
|
|
17
|
+
startMs?: number | null;
|
|
17
18
|
}
|
|
18
19
|
export interface ListFilters {
|
|
19
20
|
bbox?: Bbox;
|
|
@@ -36,6 +37,10 @@ export interface NearHit {
|
|
|
36
37
|
export declare function segmentFilterOf({ segmentType, minSmoothness }: ListFilters): SegmentFilter | undefined;
|
|
37
38
|
export declare function matchesMetadata(clip: ScanRecord, { afterMs, beforeMs, minDistanceM }: ListFilters): boolean;
|
|
38
39
|
export declare function listArchive(db: string, filters?: ListFilters): ArchiveClip[];
|
|
39
|
-
export declare function listArchiveFlights(db: string, filters?: ListFilters
|
|
40
|
+
export declare function listArchiveFlights(db: string, filters?: ListFilters, options?: {
|
|
41
|
+
overview?: boolean;
|
|
42
|
+
}): ArchiveFlight[];
|
|
43
|
+
export declare function listArchiveFlightOverviews(db: string, filters?: ListFilters): ArchiveFlight[];
|
|
40
44
|
export declare function listArchiveSegments(db: string, filters?: ListFilters): ArchiveSegment[];
|
|
41
45
|
export declare function nearArchive(db: string, point: LatLon, radiusM?: number, includeGaze?: boolean): NearHit[];
|
|
46
|
+
export declare function pruneArchiveOffline(db: string): number;
|
package/dist/query.js
CHANGED
|
@@ -28,21 +28,40 @@ export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM }) {
|
|
|
28
28
|
function toClip({ record, availability }) {
|
|
29
29
|
return { ...record, availability };
|
|
30
30
|
}
|
|
31
|
-
function matchingClips(
|
|
31
|
+
function matchingClips(store, filters, overview = false) {
|
|
32
32
|
const segmentFilter = segmentFilterOf(filters);
|
|
33
|
-
|
|
33
|
+
const clips = overview
|
|
34
|
+
? store.listClipOverviews(filters.bbox, filters.availability, segmentFilter)
|
|
35
|
+
: store.listClips(filters.bbox, filters.availability, segmentFilter);
|
|
36
|
+
return clips.flatMap((indexed) => {
|
|
34
37
|
const clip = toClip(indexed);
|
|
35
38
|
return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
|
|
36
|
-
})
|
|
39
|
+
});
|
|
37
40
|
}
|
|
38
41
|
export function listArchive(db, filters = {}) {
|
|
39
|
-
return
|
|
42
|
+
return withArchiveStore(db, (store) => matchingClips(store, filters).map(({ clip }) => clip));
|
|
40
43
|
}
|
|
41
|
-
export function listArchiveFlights(db, filters = {}) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
export function listArchiveFlights(db, filters = {}, options = {}) {
|
|
45
|
+
return withArchiveStore(db, (store) => {
|
|
46
|
+
const flights = [...groupFlightMembers(matchingClips(store, filters, options.overview === true))];
|
|
47
|
+
// Filters can omit the clip that started a flight.
|
|
48
|
+
const starts = options.overview
|
|
49
|
+
? store.readFlightStartTimes(flights.flatMap(([id, members]) => members[0].flight.order === 0 ? [] : [id]))
|
|
50
|
+
: undefined;
|
|
51
|
+
return flights.map(([flightId, members]) => {
|
|
52
|
+
const clips = members.map(({ clip, flight }) => ({ ...clip, splitFromKey: flight.splitFromKey }));
|
|
53
|
+
if (!options.overview)
|
|
54
|
+
return { flightId, clips };
|
|
55
|
+
const start = members[0].flight.order === 0
|
|
56
|
+
? clips[0].cameraCreationTime
|
|
57
|
+
: starts?.get(flightId);
|
|
58
|
+
const startMs = start ? zonedTimeMs(start) : NaN;
|
|
59
|
+
return { flightId, clips, startMs: Number.isFinite(startMs) ? startMs : null };
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
export function listArchiveFlightOverviews(db, filters = {}) {
|
|
64
|
+
return listArchiveFlights(db, filters, { overview: true });
|
|
46
65
|
}
|
|
47
66
|
export function listArchiveSegments(db, filters = {}) {
|
|
48
67
|
const segmentFilter = segmentFilterOf(filters);
|
|
@@ -75,3 +94,6 @@ export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze =
|
|
|
75
94
|
return hits.sort((a, b) => a.distanceM - b.distanceM);
|
|
76
95
|
});
|
|
77
96
|
}
|
|
97
|
+
export function pruneArchiveOffline(db) {
|
|
98
|
+
return withArchiveStore(db, (store) => store.pruneOffline());
|
|
99
|
+
}
|
|
@@ -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 =
|
|
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,9 +33,36 @@ 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);
|
|
65
|
+
private ensureFlightStartIndex;
|
|
38
66
|
private schemaVersion;
|
|
39
67
|
private migrate;
|
|
40
68
|
close(): void;
|
|
@@ -46,6 +74,7 @@ export declare class ArchiveStore {
|
|
|
46
74
|
})[];
|
|
47
75
|
};
|
|
48
76
|
listClips(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
|
|
77
|
+
listClipOverviews(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
|
|
49
78
|
private clipMatchesViewport;
|
|
50
79
|
private selectClipViewport;
|
|
51
80
|
readExportCandidates(bbox: Bbox | undefined, availability: IndexedClip['availability'] | undefined, matches: (clip: IndexedClip) => boolean, options: {
|
|
@@ -81,6 +110,26 @@ export declare class ArchiveStore {
|
|
|
81
110
|
readOverview(key: string): ScanPoint[][];
|
|
82
111
|
readSamples(key: string): SparseSample[];
|
|
83
112
|
readSegments(key: string): KinematicShot[];
|
|
113
|
+
getClipByKey(key: string): IndexedClip | null;
|
|
114
|
+
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;
|
|
122
|
+
latestSharpnessRun(clipKey: string, filter?: {
|
|
123
|
+
fingerprintKey?: string;
|
|
124
|
+
mode?: SharpnessAnalysisMode;
|
|
125
|
+
method?: string;
|
|
126
|
+
version?: string;
|
|
127
|
+
settingsJson?: string;
|
|
128
|
+
}): SharpnessRunRecord | null;
|
|
129
|
+
saveSharpnessRun(input: SaveSharpnessRunInput): SharpnessRunRecord;
|
|
130
|
+
private sharpnessSampleWhere;
|
|
131
|
+
countSharpnessSamples(runId: number, filter?: Pick<SharpnessSampleFilter, 'startSec' | 'endSec'>): number;
|
|
132
|
+
readSharpnessSamples(runId: number, filter?: SharpnessSampleFilter): ClipSharpnessSample[];
|
|
84
133
|
listSegments(filters?: {
|
|
85
134
|
bbox?: Bbox;
|
|
86
135
|
availability?: IndexedClip['availability'];
|
|
@@ -91,9 +140,12 @@ export declare class ArchiveStore {
|
|
|
91
140
|
segment: KinematicShot;
|
|
92
141
|
}[];
|
|
93
142
|
commit(expectedRevision: number, updates: readonly ClipUpdate[], online: readonly string[], offline: readonly string[], removed: readonly string[]): void;
|
|
143
|
+
removeClipsUnder(root: string): number;
|
|
144
|
+
pruneOffline(): number;
|
|
94
145
|
private revision;
|
|
95
146
|
private clipFilterClauses;
|
|
96
147
|
private selectClips;
|
|
148
|
+
readFlightStartTimes(flightIds: readonly string[]): Map<string, string | null>;
|
|
97
149
|
private refreshFlights;
|
|
98
150
|
private transaction;
|
|
99
151
|
private writeClip;
|
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 =
|
|
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) {
|
|
@@ -116,12 +176,20 @@ export class ArchiveStore {
|
|
|
116
176
|
this.db.exec('PRAGMA foreign_keys = ON');
|
|
117
177
|
if (this.schemaVersion() !== ARCHIVE_SCHEMA_VERSION)
|
|
118
178
|
this.migrate();
|
|
179
|
+
this.ensureFlightStartIndex();
|
|
119
180
|
}
|
|
120
181
|
catch (error) {
|
|
121
182
|
this.db.close();
|
|
122
183
|
throw error;
|
|
123
184
|
}
|
|
124
185
|
}
|
|
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');
|
|
191
|
+
}
|
|
192
|
+
}
|
|
125
193
|
schemaVersion() {
|
|
126
194
|
return this.db.prepare('PRAGMA user_version').get()?.user_version;
|
|
127
195
|
}
|
|
@@ -154,6 +222,9 @@ export class ArchiveStore {
|
|
|
154
222
|
}
|
|
155
223
|
this.db.exec(SEGMENTS_SCHEMA);
|
|
156
224
|
}
|
|
225
|
+
if (version < 5) {
|
|
226
|
+
this.db.exec(SHARPNESS_SCHEMA);
|
|
227
|
+
}
|
|
157
228
|
this.db.exec(`PRAGMA user_version = ${ARCHIVE_SCHEMA_VERSION}`);
|
|
158
229
|
});
|
|
159
230
|
}
|
|
@@ -182,6 +253,11 @@ export class ArchiveStore {
|
|
|
182
253
|
return this.selectClips(undefined, availability, false, segmentFilter);
|
|
183
254
|
return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter));
|
|
184
255
|
}
|
|
256
|
+
listClipOverviews(bbox, availability, segmentFilter) {
|
|
257
|
+
if (bbox === undefined)
|
|
258
|
+
return this.selectClips(undefined, availability, false, segmentFilter, true);
|
|
259
|
+
return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter, true));
|
|
260
|
+
}
|
|
185
261
|
clipMatchesViewport(bbox, key, record) {
|
|
186
262
|
const raw = record.bbox;
|
|
187
263
|
if (raw === null)
|
|
@@ -190,8 +266,8 @@ export class ArchiveStore {
|
|
|
190
266
|
return true;
|
|
191
267
|
return bboxIntersects(bbox, resolveTrackBbox(raw, [...record.track, ...groupSamples(this.readSamples(key))]));
|
|
192
268
|
}
|
|
193
|
-
selectClipViewport(bbox, availability, segmentFilter) {
|
|
194
|
-
const clips = this.selectClips(bbox, availability, false, segmentFilter);
|
|
269
|
+
selectClipViewport(bbox, availability, segmentFilter, overviewOnly = false) {
|
|
270
|
+
const clips = this.selectClips(bbox, availability, false, segmentFilter, overviewOnly);
|
|
195
271
|
if (bbox === undefined)
|
|
196
272
|
return clips;
|
|
197
273
|
return clips.filter(({ key, record }) => this.clipMatchesViewport(bbox, key, record));
|
|
@@ -263,6 +339,141 @@ export class ArchiveStore {
|
|
|
263
339
|
`).all(key);
|
|
264
340
|
return rows.map(decodeSegment);
|
|
265
341
|
}
|
|
342
|
+
getClipByKey(key) {
|
|
343
|
+
const row = this.db.prepare('SELECT * FROM clips WHERE clip_key = ?').get(key);
|
|
344
|
+
return row ? decodeClip(row) : null;
|
|
345
|
+
}
|
|
346
|
+
getSharpnessRun(runId) {
|
|
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 run_id = ?
|
|
351
|
+
`).get(runId);
|
|
352
|
+
return row ? decodeSharpnessRun(row) : null;
|
|
353
|
+
}
|
|
354
|
+
findSharpnessRun(query) {
|
|
355
|
+
const row = this.db.prepare(`
|
|
356
|
+
SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
|
|
357
|
+
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);
|
|
360
|
+
return row ? decodeSharpnessRun(row) : null;
|
|
361
|
+
}
|
|
362
|
+
latestSharpnessRun(clipKey, filter) {
|
|
363
|
+
const clauses = ['clip_key = ?'];
|
|
364
|
+
const values = [clipKey];
|
|
365
|
+
if (filter?.fingerprintKey !== undefined) {
|
|
366
|
+
clauses.push('fingerprint_key = ?');
|
|
367
|
+
values.push(filter.fingerprintKey);
|
|
368
|
+
}
|
|
369
|
+
if (filter?.mode !== undefined) {
|
|
370
|
+
clauses.push("json_extract(settings_json, '$.mode') = ?");
|
|
371
|
+
values.push(filter.mode);
|
|
372
|
+
}
|
|
373
|
+
if (filter?.method !== undefined) {
|
|
374
|
+
clauses.push('method = ?');
|
|
375
|
+
values.push(filter.method);
|
|
376
|
+
}
|
|
377
|
+
if (filter?.version !== undefined) {
|
|
378
|
+
clauses.push('version = ?');
|
|
379
|
+
values.push(filter.version);
|
|
380
|
+
}
|
|
381
|
+
if (filter?.settingsJson !== undefined) {
|
|
382
|
+
clauses.push('settings_json = ?');
|
|
383
|
+
values.push(filter.settingsJson);
|
|
384
|
+
}
|
|
385
|
+
const row = this.db.prepare(`
|
|
386
|
+
SELECT run_id, clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
|
|
387
|
+
FROM sharpness_runs
|
|
388
|
+
WHERE ${clauses.join(' AND ')}
|
|
389
|
+
ORDER BY analyzed_at_ms DESC, run_id DESC
|
|
390
|
+
LIMIT 1
|
|
391
|
+
`).get(...values);
|
|
392
|
+
return row ? decodeSharpnessRun(row) : null;
|
|
393
|
+
}
|
|
394
|
+
saveSharpnessRun(input) {
|
|
395
|
+
const analyzedAtMs = input.analyzedAtMs ?? Date.now();
|
|
396
|
+
return this.transaction('BEGIN IMMEDIATE', () => {
|
|
397
|
+
const clip = this.getClipByKey(input.clipKey);
|
|
398
|
+
if (!clip) {
|
|
399
|
+
throw new Error(`clip is not indexed in archive: ${input.clipKey}`);
|
|
400
|
+
}
|
|
401
|
+
if (input.expectedFingerprint !== undefined &&
|
|
402
|
+
(clip.fingerprint.size !== input.expectedFingerprint.size ||
|
|
403
|
+
clip.fingerprint.mtimeMs !== input.expectedFingerprint.mtimeMs)) {
|
|
404
|
+
throw new Error(`clip fingerprint changed during sharpness analysis: ${input.clipKey}`);
|
|
405
|
+
}
|
|
406
|
+
this.db.prepare(`
|
|
407
|
+
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);
|
|
410
|
+
const inserted = this.db.prepare(`
|
|
411
|
+
INSERT INTO sharpness_runs (
|
|
412
|
+
clip_key, fingerprint_key, method, version, settings_json, sample_count, analyzed_at_ms
|
|
413
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
414
|
+
`).run(input.clipKey, input.fingerprintKey, input.method, input.version, input.settingsJson, input.samples.length, analyzedAtMs);
|
|
415
|
+
const runId = Number(inserted.lastInsertRowid);
|
|
416
|
+
const addSample = this.db.prepare(`
|
|
417
|
+
INSERT INTO sharpness_samples (run_id, frame_index, t_sec, sharpness_score, edge_coverage)
|
|
418
|
+
VALUES (?, ?, ?, ?, ?)
|
|
419
|
+
`);
|
|
420
|
+
for (const sample of input.samples) {
|
|
421
|
+
addSample.run(runId, sample.frameIndex, sample.tSec, sample.sharpnessScore, sample.edgeCoverage);
|
|
422
|
+
}
|
|
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
|
+
};
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
sharpnessSampleWhere(runId, filter) {
|
|
436
|
+
const clauses = ['run_id = ?'];
|
|
437
|
+
const values = [runId];
|
|
438
|
+
if (filter?.startSec !== undefined) {
|
|
439
|
+
clauses.push('t_sec >= ?');
|
|
440
|
+
values.push(filter.startSec);
|
|
441
|
+
}
|
|
442
|
+
if (filter?.endSec !== undefined) {
|
|
443
|
+
clauses.push('t_sec <= ?');
|
|
444
|
+
values.push(filter.endSec);
|
|
445
|
+
}
|
|
446
|
+
return { where: `WHERE ${clauses.join(' AND ')}`, values };
|
|
447
|
+
}
|
|
448
|
+
countSharpnessSamples(runId, filter) {
|
|
449
|
+
const { where, values } = this.sharpnessSampleWhere(runId, filter);
|
|
450
|
+
const row = this.db.prepare(`SELECT COUNT(*) AS count FROM sharpness_samples ${where}`).get(...values);
|
|
451
|
+
return row.count;
|
|
452
|
+
}
|
|
453
|
+
readSharpnessSamples(runId, filter) {
|
|
454
|
+
const { where, values } = this.sharpnessSampleWhere(runId, filter);
|
|
455
|
+
let paging = '';
|
|
456
|
+
if (filter?.limit !== undefined) {
|
|
457
|
+
paging += ' LIMIT ?';
|
|
458
|
+
values.push(filter.limit);
|
|
459
|
+
if (filter.offset !== undefined) {
|
|
460
|
+
paging += ' OFFSET ?';
|
|
461
|
+
values.push(filter.offset);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
else if (filter?.offset !== undefined) {
|
|
465
|
+
paging += ' LIMIT -1 OFFSET ?';
|
|
466
|
+
values.push(filter.offset);
|
|
467
|
+
}
|
|
468
|
+
const rows = this.db.prepare(`
|
|
469
|
+
SELECT frame_index, t_sec, sharpness_score, edge_coverage
|
|
470
|
+
FROM sharpness_samples
|
|
471
|
+
${where}
|
|
472
|
+
ORDER BY frame_index ASC
|
|
473
|
+
${paging}
|
|
474
|
+
`).all(...values);
|
|
475
|
+
return rows.map(decodeSharpnessSample);
|
|
476
|
+
}
|
|
266
477
|
listSegments(filters = {}) {
|
|
267
478
|
return this.transaction('BEGIN', () => {
|
|
268
479
|
const { clauses, values } = this.clipFilterClauses(filters.bbox, filters.availability, false);
|
|
@@ -323,6 +534,35 @@ export class ArchiveStore {
|
|
|
323
534
|
}
|
|
324
535
|
});
|
|
325
536
|
}
|
|
537
|
+
removeClipsUnder(root) {
|
|
538
|
+
return this.transaction('BEGIN IMMEDIATE', () => {
|
|
539
|
+
const rows = this.db.prepare(`
|
|
540
|
+
SELECT clip_key, json_extract(record_json, '$.path') AS clip_path FROM clips
|
|
541
|
+
`).all();
|
|
542
|
+
const matched = rows
|
|
543
|
+
.filter((row) => typeof row.clip_path === 'string' && isWithinRoot(root, row.clip_path))
|
|
544
|
+
.map((row) => row.clip_key);
|
|
545
|
+
if (matched.length === 0)
|
|
546
|
+
return 0;
|
|
547
|
+
const remove = this.db.prepare('DELETE FROM clips WHERE clip_key = ?');
|
|
548
|
+
for (const key of matched)
|
|
549
|
+
remove.run(key);
|
|
550
|
+
this.refreshFlights();
|
|
551
|
+
this.db.exec('UPDATE archive_revision SET revision = revision + 1');
|
|
552
|
+
return matched.length;
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
pruneOffline() {
|
|
556
|
+
return this.transaction('BEGIN IMMEDIATE', () => {
|
|
557
|
+
const { changes } = this.db.prepare("DELETE FROM clips WHERE availability = 'offline'").run();
|
|
558
|
+
const count = Number(changes);
|
|
559
|
+
if (count === 0)
|
|
560
|
+
return 0;
|
|
561
|
+
this.refreshFlights();
|
|
562
|
+
this.db.exec('UPDATE archive_revision SET revision = revision + 1');
|
|
563
|
+
return count;
|
|
564
|
+
});
|
|
565
|
+
}
|
|
326
566
|
revision() {
|
|
327
567
|
return this.db.prepare('SELECT revision FROM archive_revision').get()?.revision;
|
|
328
568
|
}
|
|
@@ -366,13 +606,30 @@ export class ArchiveStore {
|
|
|
366
606
|
}
|
|
367
607
|
return { clauses, values };
|
|
368
608
|
}
|
|
369
|
-
selectClips(bbox, availability, includeArcs, segmentFilter) {
|
|
609
|
+
selectClips(bbox, availability, includeArcs, segmentFilter, overviewOnly = false) {
|
|
370
610
|
const { clauses, values } = this.clipFilterClauses(bbox, availability, includeArcs, segmentFilter);
|
|
371
611
|
const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
|
|
612
|
+
const columns = overviewOnly
|
|
613
|
+
? `clips.clip_key, clips.availability, clips.size, clips.mtime_ms, clips.srt_size, clips.srt_mtime_ms,
|
|
614
|
+
clips.schema_version, json_set(clips.record_json, '$.track', json('[]')) AS record_json,
|
|
615
|
+
clips.overview_json, clip_flights.flight_id, clip_flights.flight_order, clip_flights.split_from_key`
|
|
616
|
+
: '*';
|
|
372
617
|
const rows = this.db.prepare(`
|
|
373
|
-
SELECT
|
|
618
|
+
SELECT ${columns} FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
|
|
374
619
|
`).all(...values);
|
|
375
|
-
return
|
|
620
|
+
return overviewOnly
|
|
621
|
+
? rows.map(decodeClipOverview)
|
|
622
|
+
: rows.map(decodeFlightClip);
|
|
623
|
+
}
|
|
624
|
+
readFlightStartTimes(flightIds) {
|
|
625
|
+
if (flightIds.length === 0)
|
|
626
|
+
return new Map();
|
|
627
|
+
const rows = this.db.prepare(`
|
|
628
|
+
SELECT flight_id, json_extract(record_json, '$.cameraCreationTime') AS camera_time
|
|
629
|
+
FROM clip_flights JOIN clips USING (clip_key)
|
|
630
|
+
WHERE flight_order = 0 AND flight_id IN (SELECT value FROM json_each(?))
|
|
631
|
+
`).all(JSON.stringify(flightIds));
|
|
632
|
+
return new Map(rows.map(({ flight_id, camera_time }) => [flight_id, camera_time]));
|
|
376
633
|
}
|
|
377
634
|
refreshFlights() {
|
|
378
635
|
const rows = this.db.prepare(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "drone-path-archive",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.1",
|
|
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": "
|
|
22
|
-
"prepack": "
|
|
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.
|
|
43
|
+
"drone-path-core": "~1.2.1",
|
|
33
44
|
"leaflet": "~1.9.4",
|
|
34
45
|
"p-queue": "~10.0.0"
|
|
35
46
|
}
|