drone-path-archive 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/THIRD-PARTY-NOTICES.md +4 -0
- package/dist/camera-time.d.ts +2 -0
- package/dist/camera-time.js +16 -0
- package/dist/export-map.d.ts +12 -0
- package/dist/export-map.js +95 -0
- package/dist/export.d.ts +9 -0
- package/dist/export.js +78 -0
- package/dist/flight-members.d.ts +6 -0
- package/dist/flight-members.js +14 -0
- package/dist/gaze.d.ts +9 -0
- package/dist/gaze.js +32 -0
- package/dist/indexed-scan.d.ts +8 -0
- package/dist/indexed-scan.js +176 -0
- package/dist/paths.d.ts +1 -0
- package/dist/paths.js +16 -0
- package/dist/query.d.ts +33 -0
- package/dist/query.js +66 -0
- package/dist/scan-track.d.ts +17 -0
- package/dist/scan-track.js +85 -0
- package/dist/scanner.d.ts +44 -0
- package/dist/scanner.js +93 -0
- package/dist/store.d.ts +82 -0
- package/dist/store.js +336 -0
- package/package.json +34 -4
- package/README.md +0 -3
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const ISO_ZONED_TIME = /^(\d{4}-\d{2}-\d{2})T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/u;
|
|
2
|
+
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
|
|
3
|
+
function validCalendarDay(day) {
|
|
4
|
+
const epoch = Date.parse(day);
|
|
5
|
+
return Number.isFinite(epoch) && new Date(epoch).toISOString().slice(0, 10) === day;
|
|
6
|
+
}
|
|
7
|
+
export function zonedTimeMs(time) {
|
|
8
|
+
const day = ISO_ZONED_TIME.exec(time)?.[1];
|
|
9
|
+
return day && validCalendarDay(day) ? Date.parse(time) : NaN;
|
|
10
|
+
}
|
|
11
|
+
export function parseDateBound(time) {
|
|
12
|
+
const epoch = ISO_DAY.test(time) && validCalendarDay(time) ? Date.parse(time) : zonedTimeMs(time);
|
|
13
|
+
if (!Number.isFinite(epoch))
|
|
14
|
+
throw new Error('expected an ISO date or timestamp with a time zone');
|
|
15
|
+
return epoch;
|
|
16
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { LatLon } from 'drone-path-core/geo';
|
|
2
|
+
interface MapClip {
|
|
3
|
+
track: LatLon[][];
|
|
4
|
+
gaze: (readonly LatLon[])[];
|
|
5
|
+
label?: string;
|
|
6
|
+
availability?: 'online' | 'offline';
|
|
7
|
+
}
|
|
8
|
+
export interface MapFlight {
|
|
9
|
+
clips: MapClip[];
|
|
10
|
+
}
|
|
11
|
+
export declare function archiveMapHtml(flights: readonly MapFlight[]): string;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
const require = createRequire(import.meta.url);
|
|
5
|
+
function leafletAssets() {
|
|
6
|
+
const root = path.dirname(require.resolve('leaflet/package.json'));
|
|
7
|
+
const read = (file) => fs.readFileSync(path.join(root, file), 'utf8');
|
|
8
|
+
const script = read('dist/leaflet.js').replace(/\/\/# sourceMappingURL=.*$/mu, '');
|
|
9
|
+
// This map uses vectors and zoom buttons, so Leaflet's image controls and
|
|
10
|
+
// default marker assets would only introduce unused external references.
|
|
11
|
+
const css = read('dist/leaflet.css').replace(/url\([^)]*\)/gu, 'none');
|
|
12
|
+
return { script, css, license: read('LICENSE') };
|
|
13
|
+
}
|
|
14
|
+
function mapClient() {
|
|
15
|
+
// Kept separate from export data: popup text is only assigned to DOM nodes.
|
|
16
|
+
return String.raw `
|
|
17
|
+
const flights = JSON.parse(document.querySelector('#archive-data').textContent);
|
|
18
|
+
const map = L.map('map', { attributionControl: false });
|
|
19
|
+
const bounds = L.latLngBounds([]);
|
|
20
|
+
const colors = ['#1565c0', '#a33e00', '#00736e', '#a12466', '#613aa1', '#537421'];
|
|
21
|
+
const anchor = flights.flatMap((flight) => flight.clips)
|
|
22
|
+
.flatMap((clip) => [...clip.track, ...clip.gaze])[0]?.[0]?.lon ?? 0;
|
|
23
|
+
const layers = L.layerGroup().addTo(map);
|
|
24
|
+
const footprints = L.layerGroup();
|
|
25
|
+
let hasGaze = false;
|
|
26
|
+
function coordinates(points) {
|
|
27
|
+
let reference = anchor;
|
|
28
|
+
return points.map(({ lat, lon }) => {
|
|
29
|
+
const wrapped = lon + 360 * Math.round((reference - lon) / 360);
|
|
30
|
+
reference = wrapped;
|
|
31
|
+
return [lat, wrapped];
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function popup(clip, index) {
|
|
35
|
+
const box = document.createElement('div');
|
|
36
|
+
box.textContent = clip.label ? clip.label + ' (' + clip.availability + ')' : 'Flight ' + (index + 1);
|
|
37
|
+
return box;
|
|
38
|
+
}
|
|
39
|
+
for (const [index, flight] of flights.entries()) {
|
|
40
|
+
const color = colors[index % colors.length];
|
|
41
|
+
for (const clip of flight.clips) {
|
|
42
|
+
for (const segment of clip.track) {
|
|
43
|
+
const positions = coordinates(segment);
|
|
44
|
+
const layer = positions.length === 1 ? L.circleMarker(positions[0], { color, radius: 4 }) :
|
|
45
|
+
L.polyline(positions, { color, weight: 3, smoothFactor: 0 });
|
|
46
|
+
layer.bindPopup(() => popup(clip, index)).addTo(layers);
|
|
47
|
+
for (const position of positions) bounds.extend(position);
|
|
48
|
+
}
|
|
49
|
+
for (const polygon of clip.gaze) {
|
|
50
|
+
hasGaze = true;
|
|
51
|
+
const positions = coordinates(polygon);
|
|
52
|
+
L.polygon(positions, { color, weight: 1, fillOpacity: 0.1 })
|
|
53
|
+
.bindPopup(() => popup(clip, index)).addTo(footprints);
|
|
54
|
+
for (const position of positions) bounds.extend(position);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (hasGaze) L.control.layers({}, { 'Camera footprints': footprints.addTo(map) }, { collapsed: false }).addTo(map);
|
|
59
|
+
if (bounds.isValid()) map.fitBounds(bounds, { padding: [24, 24], maxZoom: 17 });
|
|
60
|
+
else {
|
|
61
|
+
map.setView([0, 0], 2);
|
|
62
|
+
document.querySelector('#empty').hidden = false;
|
|
63
|
+
}
|
|
64
|
+
`;
|
|
65
|
+
}
|
|
66
|
+
export function archiveMapHtml(flights) {
|
|
67
|
+
const { script, css, license } = leafletAssets();
|
|
68
|
+
const data = JSON.stringify(flights).replaceAll('<', '\\u003c');
|
|
69
|
+
return `<!doctype html>
|
|
70
|
+
<html lang="en">
|
|
71
|
+
<head>
|
|
72
|
+
<meta charset="utf-8">
|
|
73
|
+
<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'">
|
|
75
|
+
<title>Drone Path archive</title>
|
|
76
|
+
<style>
|
|
77
|
+
${css}
|
|
78
|
+
html,body,#map{height:100%;margin:0}
|
|
79
|
+
#map{background:#f4f6f7}
|
|
80
|
+
#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}
|
|
81
|
+
</style>
|
|
82
|
+
</head>
|
|
83
|
+
<body>
|
|
84
|
+
<div id="map" aria-label="Flight map"></div>
|
|
85
|
+
<div id="empty" hidden>No tracks match this export.</div>
|
|
86
|
+
<script type="application/json" id="archive-data">${data}</script>
|
|
87
|
+
<!--
|
|
88
|
+
${license}
|
|
89
|
+
-->
|
|
90
|
+
<script>${script}</script>
|
|
91
|
+
<script>${mapClient()}</script>
|
|
92
|
+
</body>
|
|
93
|
+
</html>
|
|
94
|
+
`;
|
|
95
|
+
}
|
package/dist/export.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ListFilters } from './query.js';
|
|
2
|
+
interface ExportOptions {
|
|
3
|
+
filters?: ListFilters;
|
|
4
|
+
redactLaunchM?: number;
|
|
5
|
+
includeGaze?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export declare function exportArchiveMap(db: string, output: string, options?: ExportOptions): void;
|
|
8
|
+
export declare function exportArchiveTracks(db: string, output: string, options?: Omit<ExportOptions, 'includeGaze'>): void;
|
|
9
|
+
export {};
|
package/dist/export.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { launchRedactor } from 'drone-path-core/launch-redaction';
|
|
4
|
+
import { splitTrackAtAntimeridian } from 'drone-path-core/track-antimeridian';
|
|
5
|
+
import { trackFormatOf } from 'drone-path-core/track-format';
|
|
6
|
+
import { serializeGeoJsonTracks } from 'drone-path-core/track-geojson';
|
|
7
|
+
import { serializeGpxTracks } from 'drone-path-core/track-gpx';
|
|
8
|
+
import { serializeKmlTracks } from 'drone-path-core/track-kml';
|
|
9
|
+
import { kmzBytes } from 'drone-path-core/track-kmz';
|
|
10
|
+
import { archiveMapHtml } from './export-map.js';
|
|
11
|
+
import { groupFlightMembers } from './flight-members.js';
|
|
12
|
+
import { matchesMetadata } from './query.js';
|
|
13
|
+
import { ArchiveStore } from './store.js';
|
|
14
|
+
function exportFlights(db, { filters = {}, redactLaunchM = 0, includeGaze = false }, splitDateline = false) {
|
|
15
|
+
if (!Number.isFinite(redactLaunchM) || redactLaunchM < 0) {
|
|
16
|
+
throw new Error('expected a nonnegative launch redaction radius in meters');
|
|
17
|
+
}
|
|
18
|
+
const redact = redactLaunchM > 0;
|
|
19
|
+
const store = new ArchiveStore(db);
|
|
20
|
+
try {
|
|
21
|
+
const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record }) => matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact });
|
|
22
|
+
const redactTrack = launchRedactor(endpoints, redactLaunchM);
|
|
23
|
+
const flights = groupFlightMembers(clips);
|
|
24
|
+
return [...flights.values()].flatMap((members) => {
|
|
25
|
+
const selected = members.flatMap(({ record, availability, gaze }) => {
|
|
26
|
+
const geometry = splitDateline ? splitTrackAtAntimeridian(record.track) : record.track;
|
|
27
|
+
const track = redactTrack(geometry).map((segment) => segment.map(({ lat, lon }) => ({ lat, lon })));
|
|
28
|
+
if (track.length === 0 && gaze.length === 0)
|
|
29
|
+
return [];
|
|
30
|
+
return [{
|
|
31
|
+
track,
|
|
32
|
+
gaze: gaze.map(({ polygon }) => polygon),
|
|
33
|
+
label: redact ? undefined : record.path.split(/[\\/]/u).at(-1),
|
|
34
|
+
availability: redact ? undefined : availability,
|
|
35
|
+
}];
|
|
36
|
+
});
|
|
37
|
+
return selected.length > 0 ? [{ clips: selected }] : [];
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
store.close();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function writeExport(db, output, content) {
|
|
45
|
+
const resolved = (file) => fs.existsSync(file) ? fs.realpathSync(file) : path.resolve(file);
|
|
46
|
+
const outputPath = resolved(output);
|
|
47
|
+
const databasePath = resolved(db);
|
|
48
|
+
const samePath = process.platform === 'win32' ?
|
|
49
|
+
outputPath.toLowerCase() === databasePath.toLowerCase() : outputPath === databasePath;
|
|
50
|
+
if (samePath)
|
|
51
|
+
throw new Error('export file cannot overwrite the archive database');
|
|
52
|
+
if (fs.existsSync(output) && fs.existsSync(db)) {
|
|
53
|
+
const target = fs.statSync(output, { bigint: true });
|
|
54
|
+
const database = fs.statSync(db, { bigint: true });
|
|
55
|
+
if (target.dev === database.dev && target.ino === database.ino) {
|
|
56
|
+
throw new Error('export file cannot overwrite the archive database');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
fs.mkdirSync(path.dirname(output), { recursive: true });
|
|
60
|
+
fs.writeFileSync(output, content);
|
|
61
|
+
}
|
|
62
|
+
export function exportArchiveMap(db, output, options = {}) {
|
|
63
|
+
if (path.extname(output).toLowerCase() !== '.html')
|
|
64
|
+
throw new Error('expected an .html output file');
|
|
65
|
+
writeExport(db, output, archiveMapHtml(exportFlights(db, options)));
|
|
66
|
+
}
|
|
67
|
+
export function exportArchiveTracks(db, output, options = {}) {
|
|
68
|
+
const format = trackFormatOf(output);
|
|
69
|
+
if (format === 'json')
|
|
70
|
+
throw new Error('expected a .gpx, .geojson, .kml, or .kmz output file');
|
|
71
|
+
const tracks = exportFlights(db, { ...options, includeGaze: false }, true).map(({ clips }) => clips.flatMap(({ track }) => track.map((segment) => segment.map(({ lat, lon }) => ({ lat, lon, altM: null, timeMs: null })))));
|
|
72
|
+
switch (format) {
|
|
73
|
+
case 'gpx': return writeExport(db, output, serializeGpxTracks(tracks));
|
|
74
|
+
case 'geojson': return writeExport(db, output, serializeGeoJsonTracks(tracks));
|
|
75
|
+
case 'kml': return writeExport(db, output, serializeKmlTracks(tracks));
|
|
76
|
+
case 'kmz': return writeExport(db, output, kmzBytes(serializeKmlTracks(tracks)));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function groupFlightMembers(clips) {
|
|
2
|
+
const flights = new Map();
|
|
3
|
+
for (const clip of clips) {
|
|
4
|
+
const { flightId } = clip.flight;
|
|
5
|
+
const members = flights.get(flightId);
|
|
6
|
+
if (members)
|
|
7
|
+
members.push(clip);
|
|
8
|
+
else
|
|
9
|
+
flights.set(flightId, [clip]);
|
|
10
|
+
}
|
|
11
|
+
for (const members of flights.values())
|
|
12
|
+
members.sort((a, b) => a.flight.order - b.flight.order);
|
|
13
|
+
return flights;
|
|
14
|
+
}
|
package/dist/gaze.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { GroundFootprint } from 'drone-path-core/ground-footprint';
|
|
2
|
+
import type { Bbox } from 'drone-path-core/geo';
|
|
3
|
+
import type { TrackRecord } from 'drone-path-core/track';
|
|
4
|
+
export interface GazeSample {
|
|
5
|
+
tSec: number;
|
|
6
|
+
polygon: GroundFootprint;
|
|
7
|
+
}
|
|
8
|
+
export declare function sampleGaze(records: readonly TrackRecord[]): GazeSample[];
|
|
9
|
+
export declare function gazeBbox(samples: readonly GazeSample[]): Bbox | null;
|
package/dist/gaze.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { footprintBbox, projectGroundFootprint } from 'drone-path-core/ground-footprint';
|
|
2
|
+
export function sampleGaze(records) {
|
|
3
|
+
const samples = [];
|
|
4
|
+
let nextSec = -Infinity;
|
|
5
|
+
for (const { tSec, lat, lng, altRel, gimbalPitchDeg, gimbalYawDeg, gimbalRollDeg } of records) {
|
|
6
|
+
if (!Number.isFinite(tSec) || tSec < nextSec || typeof lat !== 'number' || typeof lng !== 'number' || typeof altRel !== 'number'
|
|
7
|
+
|| typeof gimbalPitchDeg !== 'number' || typeof gimbalYawDeg !== 'number')
|
|
8
|
+
continue;
|
|
9
|
+
const polygon = projectGroundFootprint({
|
|
10
|
+
lat, lon: lng, altitudeM: altRel, pitchDeg: gimbalPitchDeg, yawDeg: gimbalYawDeg,
|
|
11
|
+
rollDeg: gimbalRollDeg ?? 0,
|
|
12
|
+
});
|
|
13
|
+
if (polygon === null)
|
|
14
|
+
continue;
|
|
15
|
+
samples.push({ tSec, polygon });
|
|
16
|
+
nextSec = tSec + 1;
|
|
17
|
+
}
|
|
18
|
+
return samples;
|
|
19
|
+
}
|
|
20
|
+
export function gazeBbox(samples) {
|
|
21
|
+
if (samples.length === 0)
|
|
22
|
+
return null;
|
|
23
|
+
const bounds = { minLat: 90, maxLat: -90, minLon: 180, maxLon: -180 };
|
|
24
|
+
for (const { polygon } of samples) {
|
|
25
|
+
const bbox = footprintBbox(polygon);
|
|
26
|
+
bounds.minLat = Math.min(bounds.minLat, bbox.minLat);
|
|
27
|
+
bounds.maxLat = Math.max(bounds.maxLat, bbox.maxLat);
|
|
28
|
+
bounds.minLon = Math.min(bounds.minLon, bbox.minLon > bbox.maxLon ? -180 : bbox.minLon);
|
|
29
|
+
bounds.maxLon = Math.max(bounds.maxLon, bbox.minLon > bbox.maxLon ? 180 : bbox.maxLon);
|
|
30
|
+
}
|
|
31
|
+
return bounds;
|
|
32
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
|
|
2
|
+
import type { ScanOptions, ScanRecord } from './scanner.js';
|
|
3
|
+
export interface IndexedScanOptions extends Omit<ScanOptions, 'tools' | 'sidecarFor' | 'onTrack' | 'onGaze'> {
|
|
4
|
+
db: string;
|
|
5
|
+
prune?: boolean;
|
|
6
|
+
getTools: () => Promise<FfmpegToolPaths>;
|
|
7
|
+
}
|
|
8
|
+
export declare function scanArchive(dirs: readonly string[], options: IndexedScanOptions): Promise<ScanRecord[]>;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createSrtSidecarLookup } from 'drone-path-core/srt-sidecar';
|
|
4
|
+
import { decimateSegments, sampleSegments } from './scan-track.js';
|
|
5
|
+
import { discoverRecordings, scanRecordings } from './scanner.js';
|
|
6
|
+
import { ArchiveStore, CLIP_FINGERPRINT_VERSION } from './store.js';
|
|
7
|
+
function isMissing(error) {
|
|
8
|
+
const code = error?.code;
|
|
9
|
+
return code === 'ENOENT' || code === 'ENOTDIR';
|
|
10
|
+
}
|
|
11
|
+
function clipKey(file) {
|
|
12
|
+
return process.platform === 'win32' ? file.toLowerCase() : file;
|
|
13
|
+
}
|
|
14
|
+
function within(root, file, recurse) {
|
|
15
|
+
const rel = path.relative(root, file);
|
|
16
|
+
return rel !== '' && rel !== '..' && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel)
|
|
17
|
+
&& (recurse === true || !rel.includes(path.sep));
|
|
18
|
+
}
|
|
19
|
+
async function fileStats(file) {
|
|
20
|
+
try {
|
|
21
|
+
const entry = await stat(file);
|
|
22
|
+
return entry.isFile() ? entry : null;
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (!isMissing(error))
|
|
26
|
+
throw error;
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function inspectInput(file, sidecarFor) {
|
|
31
|
+
const video = await fileStats(file);
|
|
32
|
+
if (!video)
|
|
33
|
+
return null;
|
|
34
|
+
let sidecar;
|
|
35
|
+
try {
|
|
36
|
+
sidecar = await sidecarFor(file);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (!isMissing(error))
|
|
40
|
+
throw error;
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const srt = sidecar === null ? null : await fileStats(sidecar);
|
|
44
|
+
return {
|
|
45
|
+
sidecar,
|
|
46
|
+
fingerprint: {
|
|
47
|
+
size: video.size, mtimeMs: video.mtimeMs,
|
|
48
|
+
srtSize: srt?.size ?? null, srtMtimeMs: srt?.mtimeMs ?? null,
|
|
49
|
+
schemaVersion: CLIP_FINGERPRINT_VERSION,
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function matches(a, b) {
|
|
54
|
+
return !!b && a.size === b.size && a.mtimeMs === b.mtimeMs && a.srtSize === b.srtSize
|
|
55
|
+
&& a.srtMtimeMs === b.srtMtimeMs && a.schemaVersion === b.schemaVersion;
|
|
56
|
+
}
|
|
57
|
+
async function scanRoots(dirs, indexedPaths, { prune, recurse, signal }) {
|
|
58
|
+
const roots = [];
|
|
59
|
+
const present = [];
|
|
60
|
+
for (const dir of dirs) {
|
|
61
|
+
signal?.throwIfAborted();
|
|
62
|
+
try {
|
|
63
|
+
const canonical = await realpath(dir);
|
|
64
|
+
roots.push(canonical);
|
|
65
|
+
present.push(canonical);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
const absolute = path.resolve(dir);
|
|
69
|
+
if (!isMissing(error) || (prune !== true && !indexedPaths.some((file) => within(absolute, file, recurse)))) {
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
roots.push(absolute);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { roots, present };
|
|
76
|
+
}
|
|
77
|
+
export async function scanArchive(dirs, options) {
|
|
78
|
+
const store = new ArchiveStore(options.db);
|
|
79
|
+
try {
|
|
80
|
+
return await indexFolders(store, dirs, options);
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
store.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async function indexFolders(store, dirs, options) {
|
|
87
|
+
const { signal, recurse, prune, onRecord } = options;
|
|
88
|
+
const { revision, clips } = store.snapshot();
|
|
89
|
+
const previous = new Map(clips.map((clip) => [clip.key, clip]));
|
|
90
|
+
const { roots, present } = await scanRoots(dirs, clips.map(({ record }) => record.path), options);
|
|
91
|
+
const files = await discoverRecordings(present, { recurse, signal });
|
|
92
|
+
const records = new Map();
|
|
93
|
+
const pending = new Map();
|
|
94
|
+
const sidecarFor = createSrtSidecarLookup();
|
|
95
|
+
const seen = new Set();
|
|
96
|
+
const backfills = new Set();
|
|
97
|
+
const online = [];
|
|
98
|
+
for (const file of files) {
|
|
99
|
+
signal?.throwIfAborted();
|
|
100
|
+
const key = clipKey(file);
|
|
101
|
+
if (seen.has(key))
|
|
102
|
+
continue;
|
|
103
|
+
const current = await inspectInput(file, sidecarFor);
|
|
104
|
+
if (!current)
|
|
105
|
+
continue;
|
|
106
|
+
seen.add(key);
|
|
107
|
+
const prior = previous.get(key);
|
|
108
|
+
const unchanged = prior && matches(current.fingerprint, prior.fingerprint);
|
|
109
|
+
if (unchanged && !prior.gazePending && prior.record.status !== 'error') {
|
|
110
|
+
records.set(file, prior.record);
|
|
111
|
+
onRecord?.(prior.record);
|
|
112
|
+
if (prior.availability === 'offline')
|
|
113
|
+
online.push(key);
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
pending.set(file, current);
|
|
117
|
+
if (unchanged && prior.gazePending) {
|
|
118
|
+
backfills.add(file);
|
|
119
|
+
if (prior.availability === 'offline')
|
|
120
|
+
online.push(key);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const updates = await probeChanges(pending, options);
|
|
125
|
+
for (const update of updates)
|
|
126
|
+
records.set(update.record.path, update.record);
|
|
127
|
+
const offline = [];
|
|
128
|
+
const removed = [];
|
|
129
|
+
for (const { key, record, availability } of clips) {
|
|
130
|
+
signal?.throwIfAborted();
|
|
131
|
+
if (seen.has(key) || !roots.some((root) => within(root, record.path, recurse)))
|
|
132
|
+
continue;
|
|
133
|
+
if (await fileStats(record.path))
|
|
134
|
+
continue;
|
|
135
|
+
if (prune)
|
|
136
|
+
removed.push(key);
|
|
137
|
+
else if (availability === 'online')
|
|
138
|
+
offline.push(key);
|
|
139
|
+
}
|
|
140
|
+
signal?.throwIfAborted();
|
|
141
|
+
// A failed footprint backfill leaves the existing track indexed and retryable.
|
|
142
|
+
const successfulUpdates = updates.filter(({ record }) => record.status !== 'error' || !backfills.has(record.path));
|
|
143
|
+
store.commit(revision, successfulUpdates, online, offline, removed);
|
|
144
|
+
return files.flatMap((file) => records.get(file) ?? []);
|
|
145
|
+
}
|
|
146
|
+
async function probeChanges(pending, { concurrency, signal, getTools, onRecord }) {
|
|
147
|
+
if (pending.size === 0)
|
|
148
|
+
return [];
|
|
149
|
+
const tracks = new Map();
|
|
150
|
+
const gaze = new Map();
|
|
151
|
+
const tools = await getTools();
|
|
152
|
+
const scanned = await scanRecordings([...pending.keys()], {
|
|
153
|
+
tools, concurrency, signal, onRecord,
|
|
154
|
+
sidecarFor: (file) => pending.get(file)?.sidecar,
|
|
155
|
+
onGaze: (file, samples) => gaze.set(file, samples),
|
|
156
|
+
onTrack: (file, segments) => {
|
|
157
|
+
tracks.set(file, { overview: decimateSegments(segments, 60, 9), samples: sampleSegments(segments) });
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
const updates = [];
|
|
161
|
+
const sidecarFor = createSrtSidecarLookup();
|
|
162
|
+
for (const record of scanned) {
|
|
163
|
+
signal?.throwIfAborted();
|
|
164
|
+
const original = pending.get(record.path);
|
|
165
|
+
const current = await inspectInput(record.path, sidecarFor);
|
|
166
|
+
if (!current || original.sidecar !== current.sidecar || !matches(original.fingerprint, current.fingerprint)) {
|
|
167
|
+
throw new Error(`recording changed during scan, rerun the scan: ${record.path}`);
|
|
168
|
+
}
|
|
169
|
+
updates.push({
|
|
170
|
+
key: clipKey(record.path), availability: 'online', fingerprint: original.fingerprint, record,
|
|
171
|
+
...tracks.get(record.path) ?? { overview: [], samples: [] },
|
|
172
|
+
gaze: gaze.get(record.path),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
return updates;
|
|
176
|
+
}
|
package/dist/paths.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function archiveDbPath(override?: string): string;
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
export function archiveDbPath(override) {
|
|
4
|
+
if (override !== undefined)
|
|
5
|
+
return path.resolve(override);
|
|
6
|
+
const xdgData = process.env['XDG_DATA_HOME'];
|
|
7
|
+
const unixData = xdgData !== undefined && path.isAbsolute(xdgData)
|
|
8
|
+
? xdgData
|
|
9
|
+
: path.join(homedir(), '.local', 'share');
|
|
10
|
+
const base = process.platform === 'win32'
|
|
11
|
+
? process.env['LOCALAPPDATA'] ?? path.join(homedir(), 'AppData', 'Local')
|
|
12
|
+
: process.platform === 'darwin'
|
|
13
|
+
? path.join(homedir(), 'Library', 'Application Support')
|
|
14
|
+
: unixData;
|
|
15
|
+
return path.join(base, 'drone-path', 'archive.sqlite');
|
|
16
|
+
}
|
package/dist/query.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Bbox, LatLon } from 'drone-path-core/geo';
|
|
2
|
+
import type { ScanRecord } from './scanner.js';
|
|
3
|
+
import type { IndexedClip } from './store.js';
|
|
4
|
+
export { parseDateBound } from './camera-time.js';
|
|
5
|
+
export declare const DEFAULT_RADIUS_M = 100;
|
|
6
|
+
export type ArchiveAvailability = IndexedClip['availability'];
|
|
7
|
+
export type ArchiveClip = ScanRecord & {
|
|
8
|
+
availability: ArchiveAvailability;
|
|
9
|
+
};
|
|
10
|
+
export type FlightListClip = ArchiveClip & {
|
|
11
|
+
splitFromKey: string | null;
|
|
12
|
+
};
|
|
13
|
+
export interface ArchiveFlight {
|
|
14
|
+
flightId: string;
|
|
15
|
+
clips: FlightListClip[];
|
|
16
|
+
}
|
|
17
|
+
export interface ListFilters {
|
|
18
|
+
bbox?: Bbox;
|
|
19
|
+
afterMs?: number;
|
|
20
|
+
beforeMs?: number;
|
|
21
|
+
minDistanceM?: number;
|
|
22
|
+
availability?: ArchiveAvailability;
|
|
23
|
+
}
|
|
24
|
+
export interface NearHit {
|
|
25
|
+
clip: ArchiveClip;
|
|
26
|
+
tSec: number;
|
|
27
|
+
distanceM: number;
|
|
28
|
+
matchType: 'track' | 'gaze';
|
|
29
|
+
}
|
|
30
|
+
export declare function matchesMetadata(clip: ScanRecord, { afterMs, beforeMs, minDistanceM }: ListFilters): boolean;
|
|
31
|
+
export declare function listArchive(db: string, filters?: ListFilters): ArchiveClip[];
|
|
32
|
+
export declare function listArchiveFlights(db: string, filters?: ListFilters): ArchiveFlight[];
|
|
33
|
+
export declare function nearArchive(db: string, point: LatLon, radiusM?: number, includeGaze?: boolean): NearHit[];
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { footprintContains } from 'drone-path-core/ground-footprint';
|
|
2
|
+
import { nearestOnTrack, radiusBbox } from 'drone-path-core/spatial';
|
|
3
|
+
import { zonedTimeMs } from './camera-time.js';
|
|
4
|
+
import { groupFlightMembers } from './flight-members.js';
|
|
5
|
+
import { groupSamples } from './scan-track.js';
|
|
6
|
+
import { ArchiveStore } from './store.js';
|
|
7
|
+
export { parseDateBound } from './camera-time.js';
|
|
8
|
+
export const DEFAULT_RADIUS_M = 100;
|
|
9
|
+
export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM }) {
|
|
10
|
+
if (minDistanceM !== undefined &&
|
|
11
|
+
(clip.telemetry === null || clip.telemetry.trackDistanceM < minDistanceM))
|
|
12
|
+
return false;
|
|
13
|
+
if (afterMs === undefined && beforeMs === undefined)
|
|
14
|
+
return true;
|
|
15
|
+
const time = clip.cameraCreationTime === null ? NaN : zonedTimeMs(clip.cameraCreationTime);
|
|
16
|
+
return Number.isFinite(time) &&
|
|
17
|
+
(afterMs === undefined || time >= afterMs) &&
|
|
18
|
+
(beforeMs === undefined || time < beforeMs);
|
|
19
|
+
}
|
|
20
|
+
function toClip({ record, availability }) {
|
|
21
|
+
return { ...record, availability };
|
|
22
|
+
}
|
|
23
|
+
function matchingClips(db, filters) {
|
|
24
|
+
const store = new ArchiveStore(db);
|
|
25
|
+
try {
|
|
26
|
+
return store.listClips(filters.bbox, filters.availability).flatMap((indexed) => {
|
|
27
|
+
const clip = toClip(indexed);
|
|
28
|
+
return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
store.close();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function listArchive(db, filters = {}) {
|
|
36
|
+
return matchingClips(db, filters).map(({ clip }) => clip);
|
|
37
|
+
}
|
|
38
|
+
export function listArchiveFlights(db, filters = {}) {
|
|
39
|
+
const flights = groupFlightMembers(matchingClips(db, filters));
|
|
40
|
+
return [...flights].map(([flightId, members]) => ({
|
|
41
|
+
flightId, clips: members.map(({ clip, flight }) => ({ ...clip, splitFromKey: flight.splitFromKey })),
|
|
42
|
+
}));
|
|
43
|
+
}
|
|
44
|
+
export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze = false) {
|
|
45
|
+
const store = new ArchiveStore(db);
|
|
46
|
+
try {
|
|
47
|
+
const hits = [];
|
|
48
|
+
const { tracks, gaze } = store.readNearCandidates(radiusBbox(point, radiusM), includeGaze ? point : undefined);
|
|
49
|
+
for (const { clip, samples } of tracks) {
|
|
50
|
+
const match = nearestOnTrack(point, groupSamples(samples));
|
|
51
|
+
if (match !== null && match.distanceM <= radiusM) {
|
|
52
|
+
hits.push({ clip: toClip(clip), ...match, matchType: 'track' });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
for (const { clip, samples } of gaze) {
|
|
56
|
+
const match = samples.find(({ polygon }) => footprintContains(polygon, point));
|
|
57
|
+
if (match)
|
|
58
|
+
hits.push({ clip: toClip(clip), tSec: match.tSec, distanceM: 0, matchType: 'gaze' });
|
|
59
|
+
}
|
|
60
|
+
// Stable sorting preserves clip-key order within each match type for equal distances.
|
|
61
|
+
return hits.sort((a, b) => a.distanceM - b.distanceM);
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
store.close();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Bbox, LatLon } from 'drone-path-core/geo';
|
|
2
|
+
import type { TrackRecord } from 'drone-path-core/track';
|
|
3
|
+
export interface ScanPoint extends LatLon {
|
|
4
|
+
tSec: number;
|
|
5
|
+
}
|
|
6
|
+
export interface SparseSample extends ScanPoint {
|
|
7
|
+
segment: number;
|
|
8
|
+
}
|
|
9
|
+
export declare function groupSamples(samples: readonly SparseSample[]): ScanPoint[][];
|
|
10
|
+
export declare function decimateSegments(segments: readonly ScanPoint[][], maxPoints: number, zoom: number): ScanPoint[][];
|
|
11
|
+
export declare function sampleSegments(segments: readonly ScanPoint[][]): SparseSample[];
|
|
12
|
+
export declare function summarizeTrack(records: readonly TrackRecord[], onTrack?: (segments: ScanPoint[][]) => void): {
|
|
13
|
+
track: ScanPoint[][];
|
|
14
|
+
bbox: Bbox | null;
|
|
15
|
+
fixCount: number;
|
|
16
|
+
trackDistanceM: number;
|
|
17
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { decimateTrack } from 'drone-path-core/decimate';
|
|
2
|
+
import { haversineM } from 'drone-path-core/geo';
|
|
3
|
+
export function groupSamples(samples) {
|
|
4
|
+
const segments = new Map();
|
|
5
|
+
for (const sample of samples) {
|
|
6
|
+
const segment = segments.get(sample.segment);
|
|
7
|
+
if (segment)
|
|
8
|
+
segment.push(sample);
|
|
9
|
+
else
|
|
10
|
+
segments.set(sample.segment, [sample]);
|
|
11
|
+
}
|
|
12
|
+
return [...segments.values()];
|
|
13
|
+
}
|
|
14
|
+
export function decimateSegments(segments, maxPoints, zoom) {
|
|
15
|
+
let minimum = 0;
|
|
16
|
+
let count = 0;
|
|
17
|
+
const retained = segments.filter((points) => {
|
|
18
|
+
const endpoints = Math.min(points.length, 2);
|
|
19
|
+
if (minimum + endpoints > maxPoints)
|
|
20
|
+
return false;
|
|
21
|
+
minimum += endpoints;
|
|
22
|
+
count += points.length;
|
|
23
|
+
return true;
|
|
24
|
+
});
|
|
25
|
+
const extras = count - minimum;
|
|
26
|
+
const available = Math.min(extras, maxPoints - minimum);
|
|
27
|
+
let allocated = 0;
|
|
28
|
+
let seen = 0;
|
|
29
|
+
return retained.map((points) => {
|
|
30
|
+
const endpoints = Math.min(points.length, 2);
|
|
31
|
+
seen += points.length - endpoints;
|
|
32
|
+
const cumulative = extras === 0 ? 0 : Math.floor(seen * available / extras);
|
|
33
|
+
const budget = endpoints + cumulative - allocated;
|
|
34
|
+
allocated = cumulative;
|
|
35
|
+
if (points.length < 2)
|
|
36
|
+
return points;
|
|
37
|
+
const reduced = decimateTrack(points.map(({ lat }) => lat), points.map(({ lon }) => lon), zoom, { maxPoints: budget });
|
|
38
|
+
return reduced.frame.map((index) => points[index]);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export function sampleSegments(segments) {
|
|
42
|
+
const samples = [];
|
|
43
|
+
for (const [segment, points] of segments.entries()) {
|
|
44
|
+
let second;
|
|
45
|
+
for (const [index, point] of points.entries()) {
|
|
46
|
+
const bucket = Math.floor(point.tSec);
|
|
47
|
+
if (bucket === second && index !== points.length - 1)
|
|
48
|
+
continue;
|
|
49
|
+
second = bucket;
|
|
50
|
+
samples.push({ ...point, segment });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return samples;
|
|
54
|
+
}
|
|
55
|
+
export function summarizeTrack(records, onTrack) {
|
|
56
|
+
const segments = [];
|
|
57
|
+
let segment = [];
|
|
58
|
+
let bbox = null;
|
|
59
|
+
let trackDistanceM = 0;
|
|
60
|
+
let fixCount = 0;
|
|
61
|
+
for (const { lat, lng, tSec } of records) {
|
|
62
|
+
if (lat === null || lat === undefined || lng === null || lng === undefined || !Number.isFinite(tSec)) {
|
|
63
|
+
if (segment.length > 0)
|
|
64
|
+
segments.push(segment);
|
|
65
|
+
segment = [];
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const point = { lat, lon: lng, tSec };
|
|
69
|
+
const previous = segment.at(-1);
|
|
70
|
+
if (previous)
|
|
71
|
+
trackDistanceM += haversineM(previous, point);
|
|
72
|
+
segment.push(point);
|
|
73
|
+
fixCount++;
|
|
74
|
+
bbox ??= { minLat: lat, maxLat: lat, minLon: lng, maxLon: lng };
|
|
75
|
+
bbox.minLat = Math.min(bbox.minLat, lat);
|
|
76
|
+
bbox.maxLat = Math.max(bbox.maxLat, lat);
|
|
77
|
+
bbox.minLon = Math.min(bbox.minLon, lng);
|
|
78
|
+
bbox.maxLon = Math.max(bbox.maxLon, lng);
|
|
79
|
+
}
|
|
80
|
+
if (segment.length > 0)
|
|
81
|
+
segments.push(segment);
|
|
82
|
+
onTrack?.(segments);
|
|
83
|
+
const track = decimateSegments(segments, 500, 18);
|
|
84
|
+
return { track, bbox, fixCount, trackDistanceM };
|
|
85
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { VideoProbe } from 'drone-path-core/ffmpeg';
|
|
2
|
+
import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
|
|
3
|
+
import type { Bbox } from 'drone-path-core/geo';
|
|
4
|
+
import type { SourceSamples } from 'drone-path-core/telemetry';
|
|
5
|
+
import type { GazeSample } from './gaze.js';
|
|
6
|
+
import type { ScanPoint } from './scan-track.js';
|
|
7
|
+
export type ScanStatus = 'ok' | 'no-telemetry' | 'no-gps' | 'error';
|
|
8
|
+
type ScanVideo = Pick<VideoProbe, 'fps' | 'frames' | 'width' | 'height'> & {
|
|
9
|
+
durationSec: number | null;
|
|
10
|
+
};
|
|
11
|
+
export interface ScanRecord {
|
|
12
|
+
path: string;
|
|
13
|
+
size: number | null;
|
|
14
|
+
mtimeMs: number | null;
|
|
15
|
+
status: ScanStatus;
|
|
16
|
+
video: ScanVideo | null;
|
|
17
|
+
/** Original camera tag, with unverified accuracy and time zone. */
|
|
18
|
+
cameraCreationTime: string | null;
|
|
19
|
+
telemetry: {
|
|
20
|
+
source: SourceSamples['source'];
|
|
21
|
+
method: SourceSamples['method'];
|
|
22
|
+
fixCount: number;
|
|
23
|
+
noLock: number;
|
|
24
|
+
trackDistanceM: number;
|
|
25
|
+
} | null;
|
|
26
|
+
bbox: Bbox | null;
|
|
27
|
+
track: ScanPoint[][];
|
|
28
|
+
error: string | null;
|
|
29
|
+
}
|
|
30
|
+
export interface ScanOptions {
|
|
31
|
+
tools: FfmpegToolPaths;
|
|
32
|
+
recurse?: boolean;
|
|
33
|
+
concurrency?: number;
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
sidecarFor?: (file: string) => string | null | undefined;
|
|
36
|
+
onRecord?: (record: ScanRecord) => void;
|
|
37
|
+
onTrack?: (file: string, segments: ScanPoint[][]) => void;
|
|
38
|
+
onGaze?: (file: string, samples: GazeSample[]) => void;
|
|
39
|
+
}
|
|
40
|
+
export declare function discoverRecordings(dirs: readonly string[], { recurse, signal }?: Pick<ScanOptions, 'recurse' | 'signal'>): Promise<string[]>;
|
|
41
|
+
export declare function scanRecording(file: string, { tools, signal, sidecarFor, onTrack, onGaze }: Pick<ScanOptions, 'tools' | 'signal' | 'sidecarFor' | 'onTrack' | 'onGaze'>): Promise<ScanRecord>;
|
|
42
|
+
export declare function scanFolders(dirs: readonly string[], options: ScanOptions): Promise<ScanRecord[]>;
|
|
43
|
+
export declare function scanRecordings(files: readonly string[], options: ScanOptions): Promise<ScanRecord[]>;
|
|
44
|
+
export {};
|
package/dist/scanner.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { readdir, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import PQueue from 'p-queue';
|
|
4
|
+
import { errorMessage } from 'drone-path-core/errors';
|
|
5
|
+
import { probeVideo } from 'drone-path-core/ffmpeg';
|
|
6
|
+
import { loadTelemetrySamples } from 'drone-path-core/telemetry';
|
|
7
|
+
import { sampleGaze } from './gaze.js';
|
|
8
|
+
import { summarizeTrack } from './scan-track.js';
|
|
9
|
+
function isRecording(name) {
|
|
10
|
+
const lower = name.toLowerCase();
|
|
11
|
+
return lower.endsWith('.mp4') && !lower.endsWith('_map.mp4');
|
|
12
|
+
}
|
|
13
|
+
export async function discoverRecordings(dirs, { recurse, signal } = {}) {
|
|
14
|
+
const visited = new Set();
|
|
15
|
+
const found = [];
|
|
16
|
+
const pending = [];
|
|
17
|
+
for (const dir of dirs) {
|
|
18
|
+
signal?.throwIfAborted();
|
|
19
|
+
pending.push(await realpath(dir));
|
|
20
|
+
}
|
|
21
|
+
for (const dir of pending) {
|
|
22
|
+
signal?.throwIfAborted();
|
|
23
|
+
if (visited.has(dir))
|
|
24
|
+
continue;
|
|
25
|
+
visited.add(dir);
|
|
26
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
27
|
+
const full = path.join(dir, entry.name);
|
|
28
|
+
if (entry.isDirectory() && recurse)
|
|
29
|
+
pending.push(full);
|
|
30
|
+
if (entry.isFile() && isRecording(entry.name))
|
|
31
|
+
found.push(full);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return found.sort();
|
|
35
|
+
}
|
|
36
|
+
export async function scanRecording(file, { tools, signal, sidecarFor, onTrack, onGaze }) {
|
|
37
|
+
signal?.throwIfAborted();
|
|
38
|
+
const record = {
|
|
39
|
+
path: file, size: null, mtimeMs: null, status: 'error', video: null,
|
|
40
|
+
cameraCreationTime: null, telemetry: null, bbox: null, track: [], error: null,
|
|
41
|
+
};
|
|
42
|
+
try {
|
|
43
|
+
const stats = await stat(file);
|
|
44
|
+
if (!stats.isFile())
|
|
45
|
+
throw new Error('recording is no longer a regular file');
|
|
46
|
+
record.size = stats.size;
|
|
47
|
+
record.mtimeMs = stats.mtimeMs;
|
|
48
|
+
signal?.throwIfAborted();
|
|
49
|
+
const { fps, frames, width, height, durationSec, creationTime, camMeta } = await probeVideo(tools, file, undefined, signal);
|
|
50
|
+
record.video = { fps, frames, width, height, durationSec: Number.isFinite(durationSec) ? durationSec : null };
|
|
51
|
+
record.cameraCreationTime = creationTime ?? null;
|
|
52
|
+
const loaded = await loadTelemetrySamples(tools, file, durationSec, camMeta, signal, sidecarFor?.(file));
|
|
53
|
+
signal?.throwIfAborted();
|
|
54
|
+
if (!loaded) {
|
|
55
|
+
record.status = 'no-telemetry';
|
|
56
|
+
return record;
|
|
57
|
+
}
|
|
58
|
+
if (loaded.trackValues.length === 0) {
|
|
59
|
+
throw new Error('cam meta stream contains no readable telemetry samples');
|
|
60
|
+
}
|
|
61
|
+
const { bbox, track, fixCount, trackDistanceM } = summarizeTrack(loaded.trackValues, onTrack && ((segments) => onTrack(file, segments)));
|
|
62
|
+
record.bbox = bbox;
|
|
63
|
+
record.track = track;
|
|
64
|
+
record.telemetry = { source: loaded.source, method: loaded.method, fixCount, noLock: loaded.noLock, trackDistanceM };
|
|
65
|
+
if (onGaze && loaded.method === 'dvtm-packets')
|
|
66
|
+
onGaze(file, sampleGaze(loaded.trackValues));
|
|
67
|
+
record.status = fixCount > 0 ? 'ok' : 'no-gps';
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
signal?.throwIfAborted();
|
|
71
|
+
record.error = errorMessage(error);
|
|
72
|
+
}
|
|
73
|
+
return record;
|
|
74
|
+
}
|
|
75
|
+
export async function scanFolders(dirs, options) {
|
|
76
|
+
const files = await discoverRecordings(dirs, options);
|
|
77
|
+
return scanRecordings(files, options);
|
|
78
|
+
}
|
|
79
|
+
export async function scanRecordings(files, options) {
|
|
80
|
+
const queue = new PQueue({ concurrency: options.concurrency ?? 4 });
|
|
81
|
+
// Wait for active tasks to release their file handles and child processes after abort.
|
|
82
|
+
const results = await Promise.allSettled(files.map((file) => queue.add(async () => {
|
|
83
|
+
const record = await scanRecording(file, options);
|
|
84
|
+
options.onRecord?.(record);
|
|
85
|
+
return record;
|
|
86
|
+
})));
|
|
87
|
+
options.signal?.throwIfAborted();
|
|
88
|
+
return results.map((result) => {
|
|
89
|
+
if (result.status === 'rejected')
|
|
90
|
+
throw result.reason;
|
|
91
|
+
return result.value;
|
|
92
|
+
});
|
|
93
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { FlightMembership } from 'drone-path-core/flight-grouping';
|
|
2
|
+
import type { Bbox, LatLon } from 'drone-path-core/geo';
|
|
3
|
+
import type { GazeSample } from './gaze.js';
|
|
4
|
+
import type { ScanPoint, SparseSample } from './scan-track.js';
|
|
5
|
+
import type { ScanRecord } from './scanner.js';
|
|
6
|
+
export declare const ARCHIVE_SCHEMA_VERSION = 3;
|
|
7
|
+
export declare const CLIP_FINGERPRINT_VERSION = 1;
|
|
8
|
+
export interface ClipFingerprint {
|
|
9
|
+
size: number;
|
|
10
|
+
mtimeMs: number;
|
|
11
|
+
srtSize: number | null;
|
|
12
|
+
srtMtimeMs: number | null;
|
|
13
|
+
schemaVersion: number;
|
|
14
|
+
}
|
|
15
|
+
export interface IndexedClip {
|
|
16
|
+
key: string;
|
|
17
|
+
record: ScanRecord;
|
|
18
|
+
fingerprint: ClipFingerprint;
|
|
19
|
+
availability: 'online' | 'offline';
|
|
20
|
+
}
|
|
21
|
+
export interface ClipUpdate extends IndexedClip {
|
|
22
|
+
overview: ScanPoint[][];
|
|
23
|
+
samples: SparseSample[];
|
|
24
|
+
gaze?: GazeSample[];
|
|
25
|
+
}
|
|
26
|
+
export interface IndexedFlightClip extends IndexedClip {
|
|
27
|
+
flight: FlightMembership;
|
|
28
|
+
}
|
|
29
|
+
export declare class ArchiveStore {
|
|
30
|
+
private readonly db;
|
|
31
|
+
constructor(file: string);
|
|
32
|
+
private schemaVersion;
|
|
33
|
+
private migrate;
|
|
34
|
+
close(): void;
|
|
35
|
+
snapshot(): {
|
|
36
|
+
revision: number;
|
|
37
|
+
clips: (IndexedClip & {
|
|
38
|
+
gazePending: boolean;
|
|
39
|
+
})[];
|
|
40
|
+
};
|
|
41
|
+
listClips(bbox?: Bbox, availability?: IndexedClip['availability']): IndexedFlightClip[];
|
|
42
|
+
private selectClipViewport;
|
|
43
|
+
readExportCandidates(bbox: Bbox | undefined, availability: IndexedClip['availability'] | undefined, matches: (clip: IndexedClip) => boolean, options: {
|
|
44
|
+
includeGaze: boolean;
|
|
45
|
+
redact: boolean;
|
|
46
|
+
}): {
|
|
47
|
+
endpoints: LatLon[];
|
|
48
|
+
clips: {
|
|
49
|
+
gaze: GazeSample[];
|
|
50
|
+
flight: FlightMembership;
|
|
51
|
+
key: string;
|
|
52
|
+
record: ScanRecord;
|
|
53
|
+
fingerprint: ClipFingerprint;
|
|
54
|
+
availability: "online" | "offline";
|
|
55
|
+
}[];
|
|
56
|
+
};
|
|
57
|
+
private readLaunchEndpoints;
|
|
58
|
+
readTrackCandidates(bbox: Bbox): {
|
|
59
|
+
clip: IndexedClip;
|
|
60
|
+
samples: SparseSample[];
|
|
61
|
+
}[];
|
|
62
|
+
readNearCandidates(bbox: Bbox, point?: LatLon): {
|
|
63
|
+
tracks: {
|
|
64
|
+
clip: IndexedFlightClip;
|
|
65
|
+
samples: SparseSample[];
|
|
66
|
+
}[];
|
|
67
|
+
gaze: {
|
|
68
|
+
clip: IndexedClip;
|
|
69
|
+
samples: GazeSample[];
|
|
70
|
+
}[];
|
|
71
|
+
};
|
|
72
|
+
private selectGazeCandidates;
|
|
73
|
+
readOverview(key: string): ScanPoint[][];
|
|
74
|
+
readSamples(key: string): SparseSample[];
|
|
75
|
+
commit(expectedRevision: number, updates: readonly ClipUpdate[], online: readonly string[], offline: readonly string[], removed: readonly string[]): void;
|
|
76
|
+
private revision;
|
|
77
|
+
private selectClips;
|
|
78
|
+
private refreshFlights;
|
|
79
|
+
private transaction;
|
|
80
|
+
private writeClip;
|
|
81
|
+
private writeGaze;
|
|
82
|
+
}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { mkdirSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
import { groupFlights } from 'drone-path-core/flight-grouping';
|
|
5
|
+
import { bboxIntersects, longitudeRanges, resolveTrackBbox } from 'drone-path-core/spatial';
|
|
6
|
+
import { zonedTimeMs } from './camera-time.js';
|
|
7
|
+
import { gazeBbox } from './gaze.js';
|
|
8
|
+
import { groupSamples } from './scan-track.js';
|
|
9
|
+
export const ARCHIVE_SCHEMA_VERSION = 3;
|
|
10
|
+
export const CLIP_FINGERPRINT_VERSION = 1;
|
|
11
|
+
function decodeClip(row) {
|
|
12
|
+
return {
|
|
13
|
+
key: row.clip_key,
|
|
14
|
+
availability: row.availability,
|
|
15
|
+
fingerprint: {
|
|
16
|
+
size: row.size, mtimeMs: row.mtime_ms,
|
|
17
|
+
srtSize: row.srt_size, srtMtimeMs: row.srt_mtime_ms,
|
|
18
|
+
schemaVersion: row.schema_version,
|
|
19
|
+
},
|
|
20
|
+
record: JSON.parse(row.record_json),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function decodeFlightClip(row) {
|
|
24
|
+
return {
|
|
25
|
+
...decodeClip(row),
|
|
26
|
+
flight: {
|
|
27
|
+
key: row.clip_key, flightId: row.flight_id, order: row.flight_order, splitFromKey: row.split_from_key,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const SCHEMA = `
|
|
32
|
+
CREATE TABLE archive_revision (revision INTEGER NOT NULL) STRICT;
|
|
33
|
+
INSERT INTO archive_revision VALUES (0);
|
|
34
|
+
CREATE TABLE clips (
|
|
35
|
+
clip_key TEXT PRIMARY KEY,
|
|
36
|
+
availability TEXT NOT NULL CHECK (availability IN ('online', 'offline')),
|
|
37
|
+
size INTEGER NOT NULL,
|
|
38
|
+
mtime_ms REAL NOT NULL,
|
|
39
|
+
srt_size INTEGER,
|
|
40
|
+
srt_mtime_ms REAL,
|
|
41
|
+
schema_version INTEGER NOT NULL,
|
|
42
|
+
min_lat REAL,
|
|
43
|
+
min_lon REAL,
|
|
44
|
+
max_lat REAL,
|
|
45
|
+
max_lon REAL,
|
|
46
|
+
record_json TEXT NOT NULL,
|
|
47
|
+
overview_json TEXT NOT NULL
|
|
48
|
+
) STRICT;
|
|
49
|
+
CREATE INDEX clips_bbox ON clips (min_lat, max_lat, min_lon, max_lon);
|
|
50
|
+
CREATE TABLE clip_samples (
|
|
51
|
+
clip_key TEXT NOT NULL REFERENCES clips (clip_key) ON DELETE CASCADE,
|
|
52
|
+
segment INTEGER NOT NULL,
|
|
53
|
+
sample_index INTEGER NOT NULL,
|
|
54
|
+
t_sec REAL NOT NULL,
|
|
55
|
+
lat REAL NOT NULL,
|
|
56
|
+
lon REAL NOT NULL,
|
|
57
|
+
PRIMARY KEY (clip_key, segment, sample_index)
|
|
58
|
+
) STRICT;
|
|
59
|
+
`;
|
|
60
|
+
const FLIGHT_SCHEMA = `
|
|
61
|
+
CREATE TABLE clip_flights (
|
|
62
|
+
clip_key TEXT PRIMARY KEY REFERENCES clips (clip_key) ON DELETE CASCADE,
|
|
63
|
+
flight_id TEXT NOT NULL,
|
|
64
|
+
flight_order INTEGER NOT NULL,
|
|
65
|
+
split_from_key TEXT REFERENCES clips (clip_key) ON DELETE SET NULL
|
|
66
|
+
) STRICT;
|
|
67
|
+
`;
|
|
68
|
+
const GAZE_SCHEMA = `
|
|
69
|
+
CREATE TABLE clip_gaze (
|
|
70
|
+
clip_key TEXT PRIMARY KEY REFERENCES clips (clip_key) ON DELETE CASCADE,
|
|
71
|
+
min_lat REAL,
|
|
72
|
+
max_lat REAL,
|
|
73
|
+
min_lon REAL,
|
|
74
|
+
max_lon REAL,
|
|
75
|
+
samples_json TEXT NOT NULL
|
|
76
|
+
) STRICT;
|
|
77
|
+
CREATE INDEX clip_gaze_bbox ON clip_gaze (min_lat, max_lat, min_lon, max_lon);
|
|
78
|
+
`;
|
|
79
|
+
export class ArchiveStore {
|
|
80
|
+
db;
|
|
81
|
+
constructor(file) {
|
|
82
|
+
if (file !== ':memory:')
|
|
83
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
84
|
+
this.db = new DatabaseSync(file);
|
|
85
|
+
try {
|
|
86
|
+
this.db.exec('PRAGMA busy_timeout = 5000');
|
|
87
|
+
this.db.exec('PRAGMA foreign_keys = ON');
|
|
88
|
+
if (this.schemaVersion() !== ARCHIVE_SCHEMA_VERSION)
|
|
89
|
+
this.migrate();
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
this.db.close();
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
schemaVersion() {
|
|
97
|
+
return this.db.prepare('PRAGMA user_version').get()?.user_version;
|
|
98
|
+
}
|
|
99
|
+
migrate() {
|
|
100
|
+
this.transaction('BEGIN IMMEDIATE', () => {
|
|
101
|
+
const version = this.schemaVersion();
|
|
102
|
+
if (version === ARCHIVE_SCHEMA_VERSION)
|
|
103
|
+
return;
|
|
104
|
+
if (version === 0) {
|
|
105
|
+
if (this.db.prepare('SELECT 1 FROM sqlite_schema LIMIT 1').get()) {
|
|
106
|
+
throw new Error('existing database has no archive schema');
|
|
107
|
+
}
|
|
108
|
+
this.db.exec(SCHEMA);
|
|
109
|
+
}
|
|
110
|
+
else if (version !== 1 && version !== 2) {
|
|
111
|
+
throw new Error(`unsupported archive database schema version: ${String(version)}`);
|
|
112
|
+
}
|
|
113
|
+
if (version === 0 || version === 1) {
|
|
114
|
+
this.db.exec(FLIGHT_SCHEMA);
|
|
115
|
+
this.refreshFlights();
|
|
116
|
+
}
|
|
117
|
+
this.db.exec(GAZE_SCHEMA);
|
|
118
|
+
this.db.exec(`PRAGMA user_version = ${ARCHIVE_SCHEMA_VERSION}`);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
close() {
|
|
122
|
+
this.db.close();
|
|
123
|
+
}
|
|
124
|
+
snapshot() {
|
|
125
|
+
return this.transaction('BEGIN', () => ({
|
|
126
|
+
revision: this.revision(),
|
|
127
|
+
clips: this.db.prepare(`
|
|
128
|
+
SELECT clips.*, clip_gaze.clip_key IS NULL AND
|
|
129
|
+
json_extract(record_json, '$.telemetry.method') IS 'dvtm-packets' AS gaze_pending
|
|
130
|
+
FROM clips LEFT JOIN clip_gaze USING (clip_key) ORDER BY clip_key
|
|
131
|
+
`).all().map((row) => ({
|
|
132
|
+
...decodeClip(row), gazePending: row.gaze_pending === 1,
|
|
133
|
+
})),
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
listClips(bbox, availability) {
|
|
137
|
+
if (bbox === undefined)
|
|
138
|
+
return this.selectClips(undefined, availability, false);
|
|
139
|
+
return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability));
|
|
140
|
+
}
|
|
141
|
+
selectClipViewport(bbox, availability) {
|
|
142
|
+
return this.selectClips(bbox, availability, false).filter(({ key, record }) => {
|
|
143
|
+
const raw = record.bbox;
|
|
144
|
+
if (raw === null)
|
|
145
|
+
return false;
|
|
146
|
+
if (raw.maxLon - raw.minLon <= 180)
|
|
147
|
+
return true;
|
|
148
|
+
return bboxIntersects(bbox, resolveTrackBbox(raw, [...record.track, ...groupSamples(this.readSamples(key))]));
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
readExportCandidates(bbox, availability, matches, options) {
|
|
152
|
+
return this.transaction('BEGIN', () => {
|
|
153
|
+
const clips = (bbox === undefined ? this.selectClips(undefined, availability, false) :
|
|
154
|
+
this.selectClipViewport(bbox, availability)).filter(matches);
|
|
155
|
+
const endpoints = options.redact ? this.readLaunchEndpoints(new Set(clips.map(({ flight }) => flight.flightId))) : [];
|
|
156
|
+
const gaze = options.includeGaze ? this.db.prepare('SELECT samples_json FROM clip_gaze WHERE clip_key = ?') : undefined;
|
|
157
|
+
return {
|
|
158
|
+
endpoints,
|
|
159
|
+
clips: clips.map((clip) => ({
|
|
160
|
+
...clip,
|
|
161
|
+
gaze: JSON.parse(gaze?.get(clip.key)?.samples_json ?? '[]'),
|
|
162
|
+
})),
|
|
163
|
+
};
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
readLaunchEndpoints(flightIds) {
|
|
167
|
+
const endpoints = [];
|
|
168
|
+
for (const direction of ['ASC', 'DESC']) {
|
|
169
|
+
const statement = this.db.prepare(`
|
|
170
|
+
SELECT lat, lon FROM clip_flights JOIN clip_samples USING (clip_key)
|
|
171
|
+
WHERE flight_id = ?
|
|
172
|
+
ORDER BY flight_order ${direction}, segment ${direction}, sample_index ${direction} LIMIT 1
|
|
173
|
+
`);
|
|
174
|
+
for (const id of flightIds) {
|
|
175
|
+
const point = statement.get(id);
|
|
176
|
+
if (point)
|
|
177
|
+
endpoints.push(point);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return endpoints;
|
|
181
|
+
}
|
|
182
|
+
readTrackCandidates(bbox) {
|
|
183
|
+
return this.readNearCandidates(bbox).tracks;
|
|
184
|
+
}
|
|
185
|
+
readNearCandidates(bbox, point) {
|
|
186
|
+
return this.transaction('BEGIN', () => ({
|
|
187
|
+
tracks: this.selectClips(bbox, undefined, true).map((clip) => ({ clip, samples: this.readSamples(clip.key) })),
|
|
188
|
+
gaze: point ? this.selectGazeCandidates(point) : [],
|
|
189
|
+
}));
|
|
190
|
+
}
|
|
191
|
+
selectGazeCandidates({ lat, lon }) {
|
|
192
|
+
const longitude = lon === 180 ? -180 : lon;
|
|
193
|
+
const rows = this.db.prepare(`
|
|
194
|
+
SELECT clips.*, samples_json FROM clips JOIN clip_gaze USING (clip_key)
|
|
195
|
+
WHERE clip_gaze.min_lat <= ? AND clip_gaze.max_lat >= ?
|
|
196
|
+
AND clip_gaze.min_lon <= ? AND clip_gaze.max_lon >= ?
|
|
197
|
+
ORDER BY clip_key
|
|
198
|
+
`).all(lat, lat, longitude, longitude);
|
|
199
|
+
return rows.map((row) => ({ clip: decodeClip(row), samples: JSON.parse(row.samples_json) }));
|
|
200
|
+
}
|
|
201
|
+
readOverview(key) {
|
|
202
|
+
const row = this.db.prepare('SELECT overview_json FROM clips WHERE clip_key = ?').get(key);
|
|
203
|
+
return row ? JSON.parse(row.overview_json) : [];
|
|
204
|
+
}
|
|
205
|
+
readSamples(key) {
|
|
206
|
+
return this.db.prepare(`
|
|
207
|
+
SELECT segment, lat, lon, t_sec AS tSec FROM clip_samples
|
|
208
|
+
WHERE clip_key = ? ORDER BY segment, sample_index
|
|
209
|
+
`).all(key);
|
|
210
|
+
}
|
|
211
|
+
commit(expectedRevision, updates, online, offline, removed) {
|
|
212
|
+
this.transaction('BEGIN IMMEDIATE', () => {
|
|
213
|
+
if (this.revision() !== expectedRevision) {
|
|
214
|
+
throw new Error('archive index changed during scan, rerun the scan');
|
|
215
|
+
}
|
|
216
|
+
for (const update of updates)
|
|
217
|
+
this.writeClip(update);
|
|
218
|
+
const setAvailability = this.db.prepare('UPDATE clips SET availability = ? WHERE clip_key = ?');
|
|
219
|
+
for (const key of online)
|
|
220
|
+
setAvailability.run('online', key);
|
|
221
|
+
for (const key of offline)
|
|
222
|
+
setAvailability.run('offline', key);
|
|
223
|
+
const remove = this.db.prepare('DELETE FROM clips WHERE clip_key = ?');
|
|
224
|
+
for (const key of removed)
|
|
225
|
+
remove.run(key);
|
|
226
|
+
if (updates.length + removed.length > 0)
|
|
227
|
+
this.refreshFlights();
|
|
228
|
+
if (updates.length + online.length + offline.length + removed.length > 0) {
|
|
229
|
+
this.db.exec('UPDATE archive_revision SET revision = revision + 1');
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
revision() {
|
|
234
|
+
return this.db.prepare('SELECT revision FROM archive_revision').get()?.revision;
|
|
235
|
+
}
|
|
236
|
+
selectClips(bbox, availability, includeArcs) {
|
|
237
|
+
const clauses = [];
|
|
238
|
+
const values = [];
|
|
239
|
+
if (availability !== undefined) {
|
|
240
|
+
clauses.push('availability = ?');
|
|
241
|
+
values.push(availability);
|
|
242
|
+
}
|
|
243
|
+
if (bbox !== undefined) {
|
|
244
|
+
const ranges = longitudeRanges(bbox);
|
|
245
|
+
const longitude = ranges.map(() => '(min_lon <= ? AND max_lon >= ?)').join(' OR ');
|
|
246
|
+
const latitude = 'min_lat <= ? AND max_lat >= ?';
|
|
247
|
+
if (includeArcs) {
|
|
248
|
+
// An arc's length in degrees is at most the latitude difference plus the
|
|
249
|
+
// longitude span. An excursion beyond either latitude endpoint adds
|
|
250
|
+
// twice its height to that lower bound, so half the span covers it.
|
|
251
|
+
// Wider raw longitude ranges may span the antimeridian or contain a pole-crossing arc.
|
|
252
|
+
clauses.push(`(max_lon - min_lon >= 180 OR (
|
|
253
|
+
min_lat - (max_lon - min_lon) / 2 <= ? AND max_lat + (max_lon - min_lon) / 2 >= ?
|
|
254
|
+
AND (${longitude})
|
|
255
|
+
))`);
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
clauses.push(`(${latitude}) AND (max_lon - min_lon > 180 OR (${longitude}))`);
|
|
259
|
+
}
|
|
260
|
+
values.push(bbox.maxLat, bbox.minLat, ...ranges.flatMap(([west, east]) => [east, west]));
|
|
261
|
+
}
|
|
262
|
+
const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
|
|
263
|
+
const rows = this.db.prepare(`
|
|
264
|
+
SELECT * FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
|
|
265
|
+
`).all(...values);
|
|
266
|
+
return rows.map(decodeFlightClip);
|
|
267
|
+
}
|
|
268
|
+
refreshFlights() {
|
|
269
|
+
const rows = this.db.prepare(`
|
|
270
|
+
SELECT clip_key, size, json_extract(record_json, '$.cameraCreationTime') AS camera_time,
|
|
271
|
+
json_extract(record_json, '$.video.durationSec') AS duration_sec
|
|
272
|
+
FROM clips ORDER BY clip_key
|
|
273
|
+
`).all();
|
|
274
|
+
const first = this.db.prepare(`
|
|
275
|
+
SELECT lat, lon, t_sec AS tSec FROM clip_samples
|
|
276
|
+
WHERE clip_key = ? ORDER BY segment, sample_index LIMIT 1
|
|
277
|
+
`);
|
|
278
|
+
const last = this.db.prepare(`
|
|
279
|
+
SELECT lat, lon, t_sec AS tSec FROM clip_samples
|
|
280
|
+
WHERE clip_key = ? ORDER BY segment DESC, sample_index DESC LIMIT 1
|
|
281
|
+
`);
|
|
282
|
+
const memberships = groupFlights(rows.map(({ clip_key, size, camera_time, duration_sec }) => ({
|
|
283
|
+
key: clip_key, size, startMs: camera_time === null ? null : zonedTimeMs(camera_time),
|
|
284
|
+
durationSec: duration_sec,
|
|
285
|
+
firstFix: first.get(clip_key),
|
|
286
|
+
lastFix: last.get(clip_key),
|
|
287
|
+
})));
|
|
288
|
+
this.db.exec('DELETE FROM clip_flights');
|
|
289
|
+
const add = this.db.prepare('INSERT INTO clip_flights VALUES (?, ?, ?, ?)');
|
|
290
|
+
for (const { key, flightId, order, splitFromKey } of memberships)
|
|
291
|
+
add.run(key, flightId, order, splitFromKey);
|
|
292
|
+
}
|
|
293
|
+
transaction(begin, body) {
|
|
294
|
+
this.db.exec(begin);
|
|
295
|
+
try {
|
|
296
|
+
const result = body();
|
|
297
|
+
this.db.exec('COMMIT');
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
this.db.exec('ROLLBACK');
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
writeClip({ key, availability, fingerprint, record, overview, samples, gaze }) {
|
|
306
|
+
const { size, mtimeMs, srtSize, srtMtimeMs, schemaVersion } = fingerprint;
|
|
307
|
+
const bbox = record.bbox;
|
|
308
|
+
this.db.prepare(`
|
|
309
|
+
INSERT INTO clips (
|
|
310
|
+
clip_key, availability, size, mtime_ms, srt_size, srt_mtime_ms, schema_version,
|
|
311
|
+
min_lat, min_lon, max_lat, max_lon, record_json, overview_json
|
|
312
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
313
|
+
ON CONFLICT (clip_key) DO UPDATE SET
|
|
314
|
+
availability = excluded.availability,
|
|
315
|
+
size = excluded.size, mtime_ms = excluded.mtime_ms,
|
|
316
|
+
srt_size = excluded.srt_size, srt_mtime_ms = excluded.srt_mtime_ms,
|
|
317
|
+
schema_version = excluded.schema_version,
|
|
318
|
+
min_lat = excluded.min_lat, min_lon = excluded.min_lon,
|
|
319
|
+
max_lat = excluded.max_lat, max_lon = excluded.max_lon,
|
|
320
|
+
record_json = excluded.record_json, overview_json = excluded.overview_json
|
|
321
|
+
`).run(key, availability, size, mtimeMs, srtSize, srtMtimeMs, schemaVersion, bbox?.minLat ?? null, bbox?.minLon ?? null, bbox?.maxLat ?? null, bbox?.maxLon ?? null, JSON.stringify(record), JSON.stringify(overview));
|
|
322
|
+
this.db.prepare('DELETE FROM clip_samples WHERE clip_key = ?').run(key);
|
|
323
|
+
this.writeGaze(key, gaze);
|
|
324
|
+
const add = this.db.prepare('INSERT INTO clip_samples VALUES (?, ?, ?, ?, ?, ?)');
|
|
325
|
+
for (const [index, sample] of samples.entries()) {
|
|
326
|
+
add.run(key, sample.segment, index, sample.tSec, sample.lat, sample.lon);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
writeGaze(key, gaze) {
|
|
330
|
+
this.db.prepare('DELETE FROM clip_gaze WHERE clip_key = ?').run(key);
|
|
331
|
+
if (!gaze)
|
|
332
|
+
return;
|
|
333
|
+
const bbox = gazeBbox(gaze);
|
|
334
|
+
this.db.prepare('INSERT INTO clip_gaze VALUES (?, ?, ?, ?, ?, ?)').run(key, bbox?.minLat ?? null, bbox?.maxLat ?? null, bbox?.minLon ?? null, bbox?.maxLon ?? null, JSON.stringify(gaze));
|
|
335
|
+
}
|
|
336
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "drone-path-archive",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Scan a local library of drone recordings.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
"./*": {
|
|
8
|
+
"types": "./dist/*.d.ts",
|
|
9
|
+
"default": "./dist/*.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist/**/*.js",
|
|
14
|
+
"dist/**/*.d.ts",
|
|
15
|
+
"THIRD-PARTY-NOTICES.md"
|
|
16
|
+
],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=24"
|
|
19
|
+
},
|
|
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"
|
|
23
|
+
},
|
|
24
|
+
"author": "Manuel Warum",
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/MrManny/drone-path.git",
|
|
29
|
+
"directory": "packages/archive"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"drone-path-core": "~1.0.0-rc1",
|
|
33
|
+
"leaflet": "~1.9.4",
|
|
34
|
+
"p-queue": "~10.0.0"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/README.md
DELETED