drone-path-core 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,9 @@
1
- import type { ExecFileOptions } from 'node:child_process';
1
+ import type { ChildProcess, ExecFileOptions, SpawnOptions } from 'node:child_process';
2
2
  interface ToolOutput {
3
3
  stdout: string;
4
4
  stderr: string;
5
5
  }
6
6
  export declare function runTool(command: string, args: readonly string[], opts?: ExecFileOptions): Promise<ToolOutput>;
7
7
  export declare function runToolBinary(command: string, args: readonly string[], opts?: ExecFileOptions): Promise<Buffer>;
8
+ export declare function spawnTool(command: string, args: readonly string[], opts?: SpawnOptions): ChildProcess;
8
9
  export {};
package/dist/exec-tool.js CHANGED
@@ -1,4 +1,4 @@
1
- import { execFile } from 'node:child_process';
1
+ import { execFile, spawn } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  const execFileAsync = promisify(execFile);
4
4
  // One child-process seam for src/: command, argv and buffer budget pass
@@ -16,3 +16,6 @@ export async function runToolBinary(command, args, opts) {
16
16
  const { stdout } = await execFileAsync(command, args, { windowsHide: true, ...opts, encoding: 'buffer' });
17
17
  return stdout;
18
18
  }
19
+ export function spawnTool(command, args, opts) {
20
+ return spawn(command, args, { windowsHide: true, ...opts });
21
+ }
@@ -1,4 +1,5 @@
1
1
  import type { FfmpegToolPaths } from './ffmpeg-tools.js';
2
+ import type { FrameSharpness } from './sharpness.js';
2
3
  export type KeyframeRequest = {
3
4
  kind: 'time';
4
5
  tSec: number;
@@ -25,11 +26,13 @@ export interface ExtractedKeyframe {
25
26
  width: number;
26
27
  height: number;
27
28
  telemetry: TelemetrySnapshot | null;
29
+ sharpness?: FrameSharpness;
28
30
  }
29
31
  export interface ExtractKeyframesOptions {
30
32
  at: readonly KeyframeRequest[];
31
33
  maxWidth?: number;
32
34
  outDir?: string;
35
+ sharpness?: boolean;
33
36
  tools: FfmpegToolPaths;
34
37
  signal?: AbortSignal;
35
38
  }
package/dist/keyframes.js CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { runTool } from './exec-tool.js';
4
4
  import { probeVideo } from './ffmpeg.js';
5
5
  import { timeAt } from './frametime.js';
6
+ import { analyzeFrameSharpness } from './sharpness.js';
6
7
  import { loadTelemetrySamples } from './telemetry.js';
7
8
  import { computeTelemetry } from './telemetry-math.js';
8
9
  function parseFrameToken(raw, token) {
@@ -200,14 +201,20 @@ export async function extractKeyframes(videoPath, options) {
200
201
  cause: e,
201
202
  });
202
203
  }
203
- results.push({
204
+ const entry = {
204
205
  path: outPath,
205
206
  tSec,
206
207
  frame,
207
208
  width,
208
209
  height,
209
210
  telemetry: snapshotAt(tSec, frame),
210
- });
211
+ };
212
+ if (options.sharpness) {
213
+ entry.sharpness = await analyzeFrameSharpness(options.tools, videoPath, tSec, {
214
+ signal: options.signal,
215
+ });
216
+ }
217
+ results.push(entry);
211
218
  }
212
219
  return results;
213
220
  }
@@ -0,0 +1,62 @@
1
+ import type { FfmpegToolPaths } from './ffmpeg-tools.js';
2
+ export declare const SHARPNESS_ANALYZER_METHOD = "ffmpeg-blurdetect";
3
+ export declare const SHARPNESS_ANALYZER_VERSION = "1";
4
+ export declare const SHARPNESS_ANALYSIS_WIDTH = 640;
5
+ export declare const DEFAULT_MIN_EDGE_COVERAGE = 0.002;
6
+ export interface SharpnessAnalyzer {
7
+ method: string;
8
+ version: string;
9
+ }
10
+ export interface FrameSharpness {
11
+ sharpnessScore: number | null;
12
+ edgeCoverage: number;
13
+ analyzer: SharpnessAnalyzer;
14
+ }
15
+ export interface RawSharpnessFrame {
16
+ index: number;
17
+ ptsTime: number | null;
18
+ blurWidth: number | null;
19
+ edgeCoverage: number;
20
+ }
21
+ export interface SharpnessFilterGraphOptions {
22
+ analysisWidth?: number;
23
+ stride?: number;
24
+ }
25
+ export interface AnalyzeFrameSharpnessOptions {
26
+ analysisWidth?: number;
27
+ minEdgeCoverage?: number;
28
+ signal?: AbortSignal;
29
+ }
30
+ export type SharpnessAnalysisMode = 'sampled' | 'every-frame';
31
+ export interface ClipSharpnessSample {
32
+ frameIndex: number;
33
+ tSec: number;
34
+ sharpnessScore: number | null;
35
+ edgeCoverage: number;
36
+ }
37
+ export interface ClipSharpnessResult {
38
+ analyzer: SharpnessAnalyzer;
39
+ mode: SharpnessAnalysisMode;
40
+ stride: number;
41
+ analysisWidth: number;
42
+ minEdgeCoverage: number;
43
+ samples: ClipSharpnessSample[];
44
+ }
45
+ export interface AnalyzeClipSharpnessOptions {
46
+ mode?: SharpnessAnalysisMode;
47
+ fps?: number;
48
+ analysisWidth?: number;
49
+ minEdgeCoverage?: number;
50
+ signal?: AbortSignal;
51
+ onSample?: (sample: ClipSharpnessSample) => void;
52
+ }
53
+ /** Build the FFmpeg filtergraph that measures edge blur width and coverage on decoded luminance. */
54
+ export declare function buildSharpnessFilterGraph(options?: SharpnessFilterGraphOptions): string;
55
+ /** Parse per-frame blur width and edge coverage metadata emitted by FFmpeg metadata=mode=print. */
56
+ export declare function parseBlurdetectMetadata(output: string): RawSharpnessFrame[];
57
+ /** Convert raw blur width and edge coverage into a monotonic higher-is-sharper score. */
58
+ export declare function scoreSharpnessSample(blurWidth: number | null, edgeCoverage: number, minEdgeCoverage?: number): FrameSharpness;
59
+ /** Analyze sharpness of a single decoded video frame at the given timestamp. */
60
+ export declare function analyzeFrameSharpness(tools: FfmpegToolPaths, videoPath: string, tSec: number, options?: AnalyzeFrameSharpnessOptions): Promise<FrameSharpness>;
61
+ /** Stream clip-wide sharpness samples from FFmpeg using sampled (1/sec) or every-frame mode. */
62
+ export declare function analyzeClipSharpness(tools: FfmpegToolPaths, videoPath: string, options?: AnalyzeClipSharpnessOptions): Promise<ClipSharpnessResult>;
@@ -0,0 +1,307 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ import { runTool, spawnTool } from './exec-tool.js';
3
+ import { probeVideo } from './ffmpeg.js';
4
+ import { timeAt } from './frametime.js';
5
+ export const SHARPNESS_ANALYZER_METHOD = 'ffmpeg-blurdetect';
6
+ export const SHARPNESS_ANALYZER_VERSION = '1';
7
+ export const SHARPNESS_ANALYSIS_WIDTH = 640;
8
+ export const DEFAULT_MIN_EDGE_COVERAGE = 0.002;
9
+ function clamp(value, min, max) {
10
+ return Math.min(max, Math.max(min, value));
11
+ }
12
+ function roundTo(value, decimals) {
13
+ const factor = 10 ** decimals;
14
+ const rounded = Math.round(value * factor) / factor;
15
+ return rounded === 0 ? 0 : rounded;
16
+ }
17
+ function parseFiniteOrNull(raw) {
18
+ const num = Number(raw.trim());
19
+ return Number.isFinite(num) ? num : null;
20
+ }
21
+ /** Build the FFmpeg filtergraph that measures edge blur width and coverage on decoded luminance. */
22
+ export function buildSharpnessFilterGraph(options) {
23
+ const analysisWidth = options?.analysisWidth ?? SHARPNESS_ANALYSIS_WIDTH;
24
+ if (!Number.isInteger(analysisWidth) || analysisWidth < 1) {
25
+ throw new Error('sharpness analysis width must be a positive integer');
26
+ }
27
+ const stride = options?.stride;
28
+ if (stride !== undefined && (!Number.isInteger(stride) || stride < 1)) {
29
+ throw new Error('sharpness stride must be a positive integer');
30
+ }
31
+ const stages = [];
32
+ if (stride !== undefined && stride > 1) {
33
+ stages.push(`select='not(mod(n,${stride}))'`);
34
+ }
35
+ // Normalize to fixed luminance width before blurdetect/edgedetect so scores
36
+ // are comparable across 1080p/4K sources and independent of JPEG encoding.
37
+ stages.push(`scale=${analysisWidth}:-2:flags=area`, 'format=gray', 'blurdetect=high=0.117647:low=0.0588235:radius=50:planes=1', 'edgedetect=low=0.0588235:high=0.117647:mode=wires', 'signalstats', 'metadata=mode=print:file=-');
38
+ return stages.join(',');
39
+ }
40
+ function createBlurdetectParser(onFrame) {
41
+ let current = null;
42
+ const pushLine = (rawLine) => {
43
+ const line = rawLine.trim();
44
+ if (line === '')
45
+ return;
46
+ const header = /^frame:(\d+)\s+pts:\S+\s+pts_time:(\S+)/u.exec(line);
47
+ if (header) {
48
+ if (current)
49
+ onFrame(current);
50
+ current = {
51
+ index: Number(header[1]),
52
+ ptsTime: parseFiniteOrNull(header[2]),
53
+ blurWidth: null,
54
+ edgeCoverage: 0,
55
+ };
56
+ return;
57
+ }
58
+ if (!current)
59
+ return;
60
+ if (line.startsWith('lavfi.blur=')) {
61
+ current.blurWidth = parseFiniteOrNull(line.slice('lavfi.blur='.length));
62
+ }
63
+ else if (line.startsWith('lavfi.signalstats.YAVG=')) {
64
+ const yavg = parseFiniteOrNull(line.slice('lavfi.signalstats.YAVG='.length));
65
+ if (yavg !== null) {
66
+ current.edgeCoverage = clamp(yavg / 255, 0, 1);
67
+ }
68
+ }
69
+ };
70
+ const flush = () => {
71
+ if (current) {
72
+ onFrame(current);
73
+ current = null;
74
+ }
75
+ };
76
+ return { pushLine, flush };
77
+ }
78
+ /** Parse per-frame blur width and edge coverage metadata emitted by FFmpeg metadata=mode=print. */
79
+ export function parseBlurdetectMetadata(output) {
80
+ const frames = [];
81
+ const parser = createBlurdetectParser((frame) => frames.push(frame));
82
+ for (const rawLine of output.split(/\r?\n/u)) {
83
+ parser.pushLine(rawLine);
84
+ }
85
+ parser.flush();
86
+ return frames;
87
+ }
88
+ /** Convert raw blur width and edge coverage into a monotonic higher-is-sharper score. */
89
+ export function scoreSharpnessSample(blurWidth, edgeCoverage, minEdgeCoverage = DEFAULT_MIN_EDGE_COVERAGE) {
90
+ const normalizedCoverage = Number.isFinite(edgeCoverage) ? clamp(edgeCoverage, 0, 1) : 0;
91
+ const roundedCoverage = roundTo(normalizedCoverage, 6);
92
+ const analyzer = {
93
+ method: SHARPNESS_ANALYZER_METHOD,
94
+ version: SHARPNESS_ANALYZER_VERSION,
95
+ };
96
+ if (blurWidth === null ||
97
+ !Number.isFinite(blurWidth) ||
98
+ blurWidth <= 0 ||
99
+ normalizedCoverage < minEdgeCoverage) {
100
+ return {
101
+ sharpnessScore: null,
102
+ edgeCoverage: roundedCoverage,
103
+ analyzer,
104
+ };
105
+ }
106
+ return {
107
+ sharpnessScore: roundTo(100 / (1 + blurWidth / 4), 2),
108
+ edgeCoverage: roundedCoverage,
109
+ analyzer,
110
+ };
111
+ }
112
+ /** Analyze sharpness of a single decoded video frame at the given timestamp. */
113
+ export async function analyzeFrameSharpness(tools, videoPath, tSec, options) {
114
+ if (!Number.isFinite(tSec) || tSec < 0) {
115
+ throw new Error(`invalid sharpness timestamp: ${tSec}`);
116
+ }
117
+ const filterGraph = buildSharpnessFilterGraph({ analysisWidth: options?.analysisWidth });
118
+ options?.signal?.throwIfAborted();
119
+ let stdout;
120
+ let stderr;
121
+ try {
122
+ ({ stdout, stderr } = await runTool(tools.ffmpeg, [
123
+ '-v', 'error',
124
+ '-ss', tSec.toFixed(6),
125
+ '-i', videoPath,
126
+ '-frames:v', '1',
127
+ '-vf', filterGraph,
128
+ '-f', 'null',
129
+ '-',
130
+ ], { signal: options?.signal }));
131
+ }
132
+ catch (e) {
133
+ if (options?.signal?.aborted)
134
+ throw e;
135
+ throw new Error(`ffmpeg failed while analyzing frame sharpness at ${tSec.toFixed(3)}s`, {
136
+ cause: e,
137
+ });
138
+ }
139
+ const parsedStdout = parseBlurdetectMetadata(stdout);
140
+ const frames = parsedStdout.length > 0 ? parsedStdout : parseBlurdetectMetadata(stderr);
141
+ if (frames.length === 0) {
142
+ throw new Error(`ffmpeg blurdetect produced no frame metadata at ${tSec.toFixed(3)}s`);
143
+ }
144
+ return scoreSharpnessSample(frames[0].blurWidth, frames[0].edgeCoverage, options?.minEdgeCoverage);
145
+ }
146
+ /** Stream clip-wide sharpness samples from FFmpeg using sampled (1/sec) or every-frame mode. */
147
+ export async function analyzeClipSharpness(tools, videoPath, options) {
148
+ const mode = options?.mode ?? 'sampled';
149
+ if (mode !== 'sampled' && mode !== 'every-frame') {
150
+ throw new Error(`invalid sharpness analysis mode: ${String(mode)}`);
151
+ }
152
+ const analysisWidth = options?.analysisWidth ?? SHARPNESS_ANALYSIS_WIDTH;
153
+ const minEdgeCoverage = options?.minEdgeCoverage ?? DEFAULT_MIN_EDGE_COVERAGE;
154
+ if (!Number.isFinite(minEdgeCoverage) || minEdgeCoverage < 0 || minEdgeCoverage > 1) {
155
+ throw new Error(`invalid sharpness min-edge-coverage: ${minEdgeCoverage}`);
156
+ }
157
+ let fps = options?.fps;
158
+ if (fps !== undefined && (!Number.isFinite(fps) || fps <= 0)) {
159
+ throw new Error(`invalid clip fps: ${fps}`);
160
+ }
161
+ options?.signal?.throwIfAborted();
162
+ if (mode === 'sampled' && fps === undefined) {
163
+ const probe = await probeVideo(tools, videoPath, undefined, options?.signal);
164
+ fps = probe.fps.value;
165
+ options?.signal?.throwIfAborted();
166
+ }
167
+ const stride = mode === 'every-frame' ? 1 : Math.max(1, Math.round(fps));
168
+ const filterGraph = buildSharpnessFilterGraph({ analysisWidth, stride });
169
+ const samples = [];
170
+ const toSample = (raw) => {
171
+ const frameIndex = raw.index * stride;
172
+ const tSec = raw.ptsTime ?? (fps !== undefined && fps > 0 ? timeAt(frameIndex, fps) : 0);
173
+ const scored = scoreSharpnessSample(raw.blurWidth, raw.edgeCoverage, minEdgeCoverage);
174
+ return {
175
+ frameIndex,
176
+ tSec,
177
+ sharpnessScore: scored.sharpnessScore,
178
+ edgeCoverage: scored.edgeCoverage,
179
+ };
180
+ };
181
+ const emitFrame = (raw) => {
182
+ const sample = toSample(raw);
183
+ samples.push(sample);
184
+ options?.onSample?.(sample);
185
+ };
186
+ const stderrText = await new Promise((resolve, reject) => {
187
+ if (options?.signal?.aborted) {
188
+ reject(options.signal.reason ?? new Error('clip sharpness analysis canceled'));
189
+ return;
190
+ }
191
+ const child = spawnTool(tools.ffmpeg, [
192
+ '-v', 'error',
193
+ '-i', videoPath,
194
+ '-vf', filterGraph,
195
+ '-f', 'null',
196
+ '-',
197
+ ], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
198
+ const parser = createBlurdetectParser(emitFrame);
199
+ const stdoutDecoder = new StringDecoder('utf8');
200
+ const stderrDecoder = new StringDecoder('utf8');
201
+ let stdoutBuffer = '';
202
+ let stderrBuffer = '';
203
+ let settled = false;
204
+ let terminating = false;
205
+ let pendingError;
206
+ const cleanup = () => {
207
+ options?.signal?.removeEventListener('abort', onAbort);
208
+ };
209
+ const fail = (err) => {
210
+ if (settled)
211
+ return;
212
+ settled = true;
213
+ cleanup();
214
+ reject(err);
215
+ };
216
+ const stopChild = (reason) => {
217
+ if (settled || terminating)
218
+ return;
219
+ terminating = true;
220
+ pendingError = reason;
221
+ child.kill();
222
+ };
223
+ const onAbort = () => {
224
+ stopChild(options?.signal?.reason ?? new Error('clip sharpness analysis canceled'));
225
+ };
226
+ options?.signal?.addEventListener('abort', onAbort, { once: true });
227
+ child.stdout?.on('data', (chunk) => {
228
+ if (settled || terminating)
229
+ return;
230
+ stdoutBuffer += typeof chunk === 'string' ? chunk : stdoutDecoder.write(chunk);
231
+ try {
232
+ let newlineIdx = stdoutBuffer.indexOf('\n');
233
+ while (newlineIdx !== -1) {
234
+ const line = stdoutBuffer.slice(0, newlineIdx);
235
+ stdoutBuffer = stdoutBuffer.slice(newlineIdx + 1);
236
+ parser.pushLine(line);
237
+ newlineIdx = stdoutBuffer.indexOf('\n');
238
+ }
239
+ }
240
+ catch (err) {
241
+ stopChild(err);
242
+ }
243
+ });
244
+ child.stderr?.on('data', (chunk) => {
245
+ if (settled || terminating)
246
+ return;
247
+ stderrBuffer += typeof chunk === 'string' ? chunk : stderrDecoder.write(chunk);
248
+ });
249
+ child.once('error', (err) => {
250
+ if (terminating) {
251
+ fail(pendingError);
252
+ return;
253
+ }
254
+ fail(new Error('ffmpeg failed while analyzing clip sharpness', { cause: err }));
255
+ });
256
+ child.once('close', (code) => {
257
+ if (settled)
258
+ return;
259
+ if (terminating) {
260
+ fail(pendingError);
261
+ return;
262
+ }
263
+ stdoutBuffer += stdoutDecoder.end();
264
+ stderrBuffer += stderrDecoder.end();
265
+ try {
266
+ if (stdoutBuffer.length > 0) {
267
+ for (const line of stdoutBuffer.split(/\r?\n/u)) {
268
+ parser.pushLine(line);
269
+ }
270
+ }
271
+ parser.flush();
272
+ }
273
+ catch (err) {
274
+ fail(err);
275
+ return;
276
+ }
277
+ if (code !== 0) {
278
+ const detail = stderrBuffer.trim();
279
+ const suffix = detail ? `: ${detail}` : '';
280
+ fail(new Error(`ffmpeg failed while analyzing clip sharpness (exit code ${code ?? 'null'})${suffix}`));
281
+ return;
282
+ }
283
+ settled = true;
284
+ cleanup();
285
+ resolve(stderrBuffer);
286
+ });
287
+ });
288
+ if (samples.length === 0) {
289
+ for (const raw of parseBlurdetectMetadata(stderrText)) {
290
+ emitFrame(raw);
291
+ }
292
+ }
293
+ if (samples.length === 0) {
294
+ throw new Error('ffmpeg blurdetect produced no frame metadata');
295
+ }
296
+ return {
297
+ analyzer: {
298
+ method: SHARPNESS_ANALYZER_METHOD,
299
+ version: SHARPNESS_ANALYZER_VERSION,
300
+ },
301
+ mode,
302
+ stride,
303
+ analysisWidth,
304
+ minEdgeCoverage,
305
+ samples,
306
+ };
307
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-core",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "Extract drone telemetry from DJI CAM-meta video streams and SRT sidecars.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,11 +18,22 @@
18
18
  "node": ">=24"
19
19
  },
20
20
  "scripts": {
21
- "build": "node ../../scripts/clean-package-dist.mjs && tsc -p tsconfig.json",
22
- "prepack": "npm run build"
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",