@lumy-pack/scene-sieve 0.0.14 → 0.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.
Files changed (46) hide show
  1. package/README.md +47 -24
  2. package/dist/{errors.d.ts → cli/errors/classify-error.d.ts} +5 -0
  3. package/dist/cli/index.d.ts +3 -0
  4. package/dist/{utils → cli/options}/parse-options.d.ts +6 -1
  5. package/dist/cli.mjs +2437 -2126
  6. package/dist/constants/pipeline-defaults.d.ts +13 -0
  7. package/dist/core/{analyzer.d.ts → analyzer/analyzer.d.ts} +11 -6
  8. package/dist/core/{dbscan.d.ts → analyzer/clustering/dbscan.d.ts} +1 -1
  9. package/dist/core/analyzer/constants/vision-tuning.d.ts +12 -0
  10. package/dist/core/analyzer/features/feature-diff.d.ts +14 -0
  11. package/dist/core/analyzer/features/frame-features.d.ts +32 -0
  12. package/dist/core/analyzer/index.d.ts +3 -0
  13. package/dist/core/constants/workspace-layout.d.ts +9 -0
  14. package/dist/core/{extractor.d.ts → extractor/extractor.d.ts} +6 -4
  15. package/dist/core/extractor/index.d.ts +1 -0
  16. package/dist/core/index.d.ts +8 -9
  17. package/dist/core/input-resolver/index.d.ts +1 -0
  18. package/dist/core/{input-resolver.d.ts → input-resolver/input-resolver.d.ts} +11 -1
  19. package/dist/core/input-resolver/validation/validate-options.d.ts +8 -0
  20. package/dist/core/orchestrator/index.d.ts +3 -0
  21. package/dist/core/{orchestrator.d.ts → orchestrator/orchestrator.d.ts} +1 -1
  22. package/dist/core/{run-in-worker.d.ts → orchestrator/worker/run-in-worker.d.ts} +5 -1
  23. package/dist/core/pruner/index.d.ts +1 -0
  24. package/dist/core/{pruner.d.ts → pruner/pruner.d.ts} +2 -2
  25. package/dist/{utils/math.d.ts → core/pruner/scoring/normalize-scores.d.ts} +4 -0
  26. package/dist/core/segmenter/index.d.ts +1 -0
  27. package/dist/core/{segmenter.d.ts → segmenter/segmenter.d.ts} +11 -11
  28. package/dist/core/utils/metadata/build-video-metadata.d.ts +14 -0
  29. package/dist/core/workspace/index.d.ts +1 -0
  30. package/dist/core/{workspace.d.ts → workspace/workspace.d.ts} +1 -1
  31. package/dist/index.cjs +1854 -1486
  32. package/dist/index.d.ts +1 -1
  33. package/dist/index.mjs +1836 -1455
  34. package/dist/pipeline-worker.mjs +1734 -1474
  35. package/dist/types/index.d.ts +25 -0
  36. package/package.json +5 -4
  37. package/dist/constants.d.ts +0 -32
  38. /package/dist/{commands → cli/commands}/Sieve.d.ts +0 -0
  39. /package/dist/{utils → cli/commands}/command-registry.d.ts +0 -0
  40. /package/dist/{components → cli/components}/PhaseStep.d.ts +0 -0
  41. /package/dist/{components → cli/components}/ProgressBar.d.ts +0 -0
  42. /package/dist/core/{pipeline-worker.d.ts → orchestrator/worker/pipeline-worker.d.ts} +0 -0
  43. /package/dist/{utils → core/pruner/heap}/min-heap.d.ts +0 -0
  44. /package/dist/{utils → core/segmenter/scheduling}/concurrency.d.ts +0 -0
  45. /package/dist/{utils → core/utils/filesystem}/paths.d.ts +0 -0
  46. /package/dist/{utils → logging}/logger.d.ts +0 -0
@@ -1,1588 +1,1848 @@
1
- // src/core/pipeline-worker.ts
2
- import { parentPort, workerData } from "worker_threads";
3
-
4
- // src/core/orchestrator.ts
5
- import { randomUUID as randomUUID2 } from "crypto";
6
- import { filter as filter6 } from "@winglet/common-utils";
7
-
8
- // src/utils/logger.ts
1
+ import { createRequire } from "node:module";
2
+ import { parentPort, workerData } from "node:worker_threads";
3
+ import { randomUUID } from "node:crypto";
4
+ import { filter, map } from "@winglet/common-utils";
9
5
  import pc from "picocolors";
10
- var debugMode = false;
11
- var jsonMode = false;
6
+ import sharp from "sharp";
7
+ import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
8
+ import { basename, extname, join, resolve } from "node:path";
9
+ import { path } from "@ffprobe-installer/ffprobe";
10
+ import { execa } from "execa";
11
+ import ffmpegPath from "ffmpeg-static";
12
+ import { homedir, tmpdir } from "node:os";
13
+
14
+ //#region src/logging/logger.ts
15
+ let debugMode = false;
16
+ let jsonMode = false;
12
17
  function setDebugMode(enabled) {
13
- debugMode = enabled;
18
+ debugMode = enabled;
14
19
  }
15
20
  function timestamp() {
16
- return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
21
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
17
22
  }
18
- var logger = {
19
- info(message) {
20
- if (jsonMode) {
21
- process.stderr.write(`${pc.blue("info")} ${message}
22
- `);
23
- } else {
24
- console.log(`${pc.blue("info")} ${message}`);
25
- }
26
- },
27
- success(message) {
28
- if (jsonMode) {
29
- process.stderr.write(`${pc.green("done")} ${message}
30
- `);
31
- } else {
32
- console.log(`
33
- ${pc.green("done")} ${message}`);
34
- }
35
- },
36
- warn(message) {
37
- console.warn(`${pc.yellow("warn")} ${message}`);
38
- },
39
- error(message) {
40
- console.error(`${pc.red("error")} ${message}`);
41
- },
42
- debug(message) {
43
- if (debugMode) {
44
- if (jsonMode) {
45
- process.stderr.write(`${pc.gray(`[${timestamp()}] debug`)} ${message}
46
- `);
47
- } else {
48
- console.log(`${pc.gray(`[${timestamp()}] debug`)} ${message}`);
49
- }
50
- }
51
- }
23
+ const logger = {
24
+ info(message) {
25
+ if (jsonMode) process.stderr.write(`${pc.blue("info")} ${message}\n`);
26
+ else console.log(`${pc.blue("info")} ${message}`);
27
+ },
28
+ success(message) {
29
+ if (jsonMode) process.stderr.write(`${pc.green("done")} ${message}\n`);
30
+ else console.log(`\n${pc.green("done")} ${message}`);
31
+ },
32
+ warn(message) {
33
+ console.warn(`${pc.yellow("warn")} ${message}`);
34
+ },
35
+ error(message) {
36
+ console.error(`${pc.red("error")} ${message}`);
37
+ },
38
+ debug(message) {
39
+ if (debugMode) if (jsonMode) process.stderr.write(`${pc.gray(`[${timestamp()}] debug`)} ${message}\n`);
40
+ else console.log(`${pc.gray(`[${timestamp()}] debug`)} ${message}`);
41
+ }
52
42
  };
53
43
 
54
- // src/core/analyzer.ts
55
- import { createRequire } from "module";
56
- import { filter, map } from "@winglet/common-utils";
57
- import sharp from "sharp";
44
+ //#endregion
45
+ //#region src/constants/pipeline-defaults.ts
46
+ const DEFAULT_THRESHOLD = .5;
47
+ const IOU_THRESHOLD = .9;
58
48
 
59
- // src/constants.ts
60
- import { tmpdir } from "os";
61
- import { join } from "path";
62
- var APP_NAME = "scene-sieve";
63
- var DEFAULT_COUNT = 20;
64
- var DEFAULT_THRESHOLD = 0.5;
65
- var DEFAULT_FPS = 5;
66
- var DEFAULT_SCALE = 720;
67
- var DEFAULT_QUALITY = 80;
68
- var DEFAULT_MAX_FRAMES = 300;
69
- var NORMALIZATION_LOGISTIC_K = 3;
70
- var NORMALIZATION_ALPHA = 0.4;
71
- var NORMALIZATION_MAD_COEFFICIENT = 1.4826;
72
- var NORMALIZATION_MIN_SAMPLE_SIZE = 10;
73
- var WORKSPACE_PREFIX = `${APP_NAME}-`;
74
- var TEMP_BASE_DIR = tmpdir();
75
- var FRAME_OUTPUT_EXTENSION = ".jpg";
76
- var FRAME_FILENAME_PATTERN = "frame_%06d.jpg";
77
- var OPENCV_BATCH_SIZE = 10;
78
- var DBSCAN_ALPHA = 0.03;
79
- var DBSCAN_MIN_PTS = 4;
80
- var IOU_THRESHOLD = 0.9;
81
- var DECAY_LAMBDA = 0.95;
82
- var ANIMATION_FRAME_THRESHOLD = 5;
83
- var MATCH_DISTANCE_THRESHOLD = 0.25;
84
- var PIXELDIFF_GAUSSIAN_KERNEL = 3;
85
- var PIXELDIFF_BINARY_THRESHOLD = 30;
86
- var PIXELDIFF_CONTOUR_MIN_AREA = 100;
87
- var PIXELDIFF_SAMPLE_SPACING = 8;
88
- var DEFAULT_MAX_SEGMENT_DURATION = 300;
89
- var DEFAULT_SEGMENT_CONCURRENCY = 2;
90
- function getTempWorkspaceDir(sessionId) {
91
- return join(TEMP_BASE_DIR, `${WORKSPACE_PREFIX}${sessionId}`);
92
- }
49
+ //#endregion
50
+ //#region src/core/analyzer/constants/vision-tuning.ts
51
+ const DBSCAN_ALPHA = .03;
52
+ const DECAY_LAMBDA = .95;
53
+ const MATCH_DISTANCE_THRESHOLD = .25;
93
54
 
94
- // src/core/dbscan.ts
95
- var UNVISITED = -2;
96
- var NOISE = -1;
55
+ //#endregion
56
+ //#region src/core/analyzer/clustering/dbscan.ts
57
+ const UNVISITED = -2;
58
+ const NOISE = -1;
59
+ /**
60
+ * DBSCAN clustering with resolution-independent eps.
61
+ * eps = alpha * sqrt(width^2 + height^2)
62
+ */
97
63
  function dbscan(points, imageWidth, imageHeight, alpha, minPts) {
98
- if (points.length === 0) {
99
- return { labels: [], boundingBoxes: [] };
100
- }
101
- const eps = (alpha ?? DBSCAN_ALPHA) * Math.sqrt(imageWidth ** 2 + imageHeight ** 2);
102
- const epsSquared = eps * eps;
103
- const minPoints = minPts ?? DBSCAN_MIN_PTS;
104
- const labels = new Array(points.length).fill(UNVISITED);
105
- let clusterId = 0;
106
- for (let i = 0; i < points.length; i++) {
107
- if (labels[i] !== UNVISITED) continue;
108
- const neighbors = findNeighbors(points, i, epsSquared);
109
- if (neighbors.length < minPoints) {
110
- labels[i] = NOISE;
111
- continue;
112
- }
113
- labels[i] = clusterId;
114
- const seeds = [...neighbors];
115
- const seedSet = new Set(seeds);
116
- for (let si = 0; si < seeds.length; si++) {
117
- const q = seeds[si];
118
- if (labels[q] === NOISE) {
119
- labels[q] = clusterId;
120
- }
121
- if (labels[q] !== UNVISITED) continue;
122
- labels[q] = clusterId;
123
- const qNeighbors = findNeighbors(points, q, epsSquared);
124
- if (qNeighbors.length >= minPoints) {
125
- for (const n of qNeighbors) {
126
- if (!seedSet.has(n)) {
127
- seedSet.add(n);
128
- seeds.push(n);
129
- }
130
- }
131
- }
132
- }
133
- clusterId++;
134
- }
135
- const boundingBoxes = [];
136
- for (let c = 0; c < clusterId; c++) {
137
- let minX = Infinity;
138
- let minY = Infinity;
139
- let maxX = -Infinity;
140
- let maxY = -Infinity;
141
- for (let i = 0; i < points.length; i++) {
142
- if (labels[i] !== c) continue;
143
- const p = points[i];
144
- if (p.x < minX) minX = p.x;
145
- if (p.y < minY) minY = p.y;
146
- if (p.x > maxX) maxX = p.x;
147
- if (p.y > maxY) maxY = p.y;
148
- }
149
- boundingBoxes.push({
150
- x: minX,
151
- y: minY,
152
- width: maxX - minX,
153
- height: maxY - minY
154
- });
155
- }
156
- return { labels, boundingBoxes };
64
+ if (points.length === 0) return {
65
+ labels: [],
66
+ boundingBoxes: []
67
+ };
68
+ const eps = (alpha ?? .03) * Math.sqrt(imageWidth ** 2 + imageHeight ** 2);
69
+ const epsSquared = eps * eps;
70
+ const minPoints = minPts ?? 4;
71
+ const labels = new Array(points.length).fill(UNVISITED);
72
+ let clusterId = 0;
73
+ for (let i = 0; i < points.length; i++) {
74
+ if (labels[i] !== UNVISITED) continue;
75
+ const neighbors = findNeighbors(points, i, epsSquared);
76
+ if (neighbors.length < minPoints) {
77
+ labels[i] = NOISE;
78
+ continue;
79
+ }
80
+ labels[i] = clusterId;
81
+ const seeds = [...neighbors];
82
+ const seedSet = new Set(seeds);
83
+ for (let si = 0; si < seeds.length; si++) {
84
+ const q = seeds[si];
85
+ if (labels[q] === NOISE) labels[q] = clusterId;
86
+ if (labels[q] !== UNVISITED) continue;
87
+ labels[q] = clusterId;
88
+ const qNeighbors = findNeighbors(points, q, epsSquared);
89
+ if (qNeighbors.length >= minPoints) {
90
+ for (const n of qNeighbors) if (!seedSet.has(n)) {
91
+ seedSet.add(n);
92
+ seeds.push(n);
93
+ }
94
+ }
95
+ }
96
+ clusterId++;
97
+ }
98
+ const boundingBoxes = [];
99
+ for (let c = 0; c < clusterId; c++) {
100
+ let minX = Infinity;
101
+ let minY = Infinity;
102
+ let maxX = -Infinity;
103
+ let maxY = -Infinity;
104
+ for (let i = 0; i < points.length; i++) {
105
+ if (labels[i] !== c) continue;
106
+ const p = points[i];
107
+ if (p.x < minX) minX = p.x;
108
+ if (p.y < minY) minY = p.y;
109
+ if (p.x > maxX) maxX = p.x;
110
+ if (p.y > maxY) maxY = p.y;
111
+ }
112
+ boundingBoxes.push({
113
+ x: minX,
114
+ y: minY,
115
+ width: maxX - minX,
116
+ height: maxY - minY
117
+ });
118
+ }
119
+ return {
120
+ labels,
121
+ boundingBoxes
122
+ };
157
123
  }
158
124
  function findNeighbors(points, idx, epsSquared) {
159
- const p = points[idx];
160
- const neighbors = [];
161
- for (let i = 0; i < points.length; i++) {
162
- if (i === idx) continue;
163
- const q = points[i];
164
- const distSq = (p.x - q.x) ** 2 + (p.y - q.y) ** 2;
165
- if (distSq <= epsSquared) {
166
- neighbors.push(i);
167
- }
168
- }
169
- return neighbors;
125
+ const p = points[idx];
126
+ const neighbors = [];
127
+ for (let i = 0; i < points.length; i++) {
128
+ if (i === idx) continue;
129
+ const q = points[i];
130
+ if ((p.x - q.x) ** 2 + (p.y - q.y) ** 2 <= epsSquared) neighbors.push(i);
131
+ }
132
+ return neighbors;
170
133
  }
171
134
 
172
- // src/core/analyzer.ts
173
- var OPENCV_INIT_TIMEOUT_MS = 3e4;
174
- var require2 = createRequire(import.meta.url);
175
- var cvReady = null;
135
+ //#endregion
136
+ //#region src/core/analyzer/features/feature-diff.ts
137
+ /**
138
+ * Match prev to next with Hamming k=2, crossCheck=false and strict ratio 0.25.
139
+ * @param cvLib - Initialized OpenCV runtime.
140
+ * @param prev - Previous frame's live features, owned by the caller.
141
+ * @param next - Next frame's live features, owned by the caller.
142
+ * @returns Unmatched next-frame coordinates without changing input ownership.
143
+ * @throws Propagates matching errors after releasing temporary native handles.
144
+ */
145
+ function computeNewPoints(cvLib, prev, next) {
146
+ let matcher = null;
147
+ let matches = null;
148
+ try {
149
+ const matchedIndices = /* @__PURE__ */ new Set();
150
+ if (prev.descriptors.rows > 0 && next.descriptors.rows > 0) try {
151
+ matcher = new cvLib.BFMatcher(cvLib.NORM_HAMMING, false);
152
+ matches = new cvLib.DMatchVectorVector();
153
+ matcher.knnMatch(prev.descriptors, next.descriptors, matches, 2);
154
+ for (let i = 0; i < matches.size(); i++) {
155
+ const pair = matches.get(i);
156
+ try {
157
+ if (pair.size() < 2) continue;
158
+ const best = pair.get(0);
159
+ const second = pair.get(1);
160
+ if (best.distance < .25 * second.distance) matchedIndices.add(best.trainIdx);
161
+ } finally {
162
+ pair.delete();
163
+ }
164
+ }
165
+ } finally {
166
+ matcher?.delete();
167
+ }
168
+ const points = [];
169
+ for (let i = 0; i < next.keypoints.size(); i++) if (!matchedIndices.has(i)) {
170
+ const { x, y } = next.keypoints.get(i).pt;
171
+ points.push({
172
+ x,
173
+ y
174
+ });
175
+ }
176
+ return points;
177
+ } finally {
178
+ matches?.delete();
179
+ }
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/core/analyzer/features/frame-features.ts
184
+ /**
185
+ * Detect one frame's features without retaining its image or mask.
186
+ * @param cvLib - Initialized OpenCV runtime.
187
+ * @param akaze - Detector owned and released by the caller.
188
+ * @param frame - Grayscale bytes with matching width and height.
189
+ * @returns Feature handles that the caller must delete.
190
+ * @throws Propagates native errors after releasing partial allocations.
191
+ */
192
+ function computeFrameFeatures(cvLib, akaze, frame) {
193
+ let image = null;
194
+ let mask = null;
195
+ let keypoints = null;
196
+ let descriptors = null;
197
+ try {
198
+ image = new cvLib.Mat(frame.height, frame.width, cvLib.CV_8UC1);
199
+ image.data.set(frame.data);
200
+ mask = new cvLib.Mat();
201
+ keypoints = new cvLib.KeyPointVector();
202
+ descriptors = new cvLib.Mat();
203
+ akaze.detectAndCompute(image, mask, keypoints, descriptors);
204
+ const ownedKeypoints = keypoints;
205
+ const ownedDescriptors = descriptors;
206
+ let deleted = false;
207
+ const features = {
208
+ width: frame.width,
209
+ height: frame.height,
210
+ keypoints: ownedKeypoints,
211
+ descriptors: ownedDescriptors,
212
+ /** Release the transferred handles exactly once. */
213
+ delete() {
214
+ if (deleted) return;
215
+ deleted = true;
216
+ try {
217
+ ownedKeypoints.delete();
218
+ } finally {
219
+ ownedDescriptors.delete();
220
+ }
221
+ }
222
+ };
223
+ keypoints = null;
224
+ descriptors = null;
225
+ return features;
226
+ } finally {
227
+ image?.delete();
228
+ mask?.delete();
229
+ keypoints?.delete();
230
+ descriptors?.delete();
231
+ }
232
+ }
233
+
234
+ //#endregion
235
+ //#region src/core/analyzer/analyzer.ts
236
+ const OPENCV_INIT_TIMEOUT_MS = 3e4;
237
+ const require = createRequire(import.meta.url);
238
+ let cvReady = null;
176
239
  async function ensureOpenCV() {
177
- if (!cvReady) {
178
- cvReady = (async () => {
179
- const cvObj = require2("@techstark/opencv-js");
180
- delete cvObj.then;
181
- if (cvObj.Mat) return cvObj;
182
- return new Promise((resolve2, reject) => {
183
- const timeout = setTimeout(() => {
184
- reject(new Error("OpenCV WASM initialization timed out after 30s"));
185
- }, OPENCV_INIT_TIMEOUT_MS);
186
- cvObj.onRuntimeInitialized = () => {
187
- clearTimeout(timeout);
188
- resolve2(cvObj);
189
- };
190
- });
191
- })();
192
- }
193
- return cvReady;
240
+ if (!cvReady) cvReady = (async () => {
241
+ const cvObj = require("@techstark/opencv-js");
242
+ delete cvObj.then;
243
+ if (cvObj.Mat) return cvObj;
244
+ return new Promise((resolve, reject) => {
245
+ const timeout = setTimeout(() => {
246
+ reject(/* @__PURE__ */ new Error("OpenCV WASM initialization timed out after 30s"));
247
+ }, OPENCV_INIT_TIMEOUT_MS);
248
+ cvObj.onRuntimeInitialized = () => {
249
+ clearTimeout(timeout);
250
+ resolve(cvObj);
251
+ };
252
+ });
253
+ })();
254
+ return cvReady;
194
255
  }
195
256
  async function preprocessFrame(framePath, scale) {
196
- const { data, info } = await sharp(framePath).resize({ width: scale, withoutEnlargement: true }).grayscale().blur(1).raw().toBuffer({ resolveWithObject: true });
197
- return {
198
- data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
199
- width: info.width,
200
- height: info.height
201
- };
257
+ const { data, info } = await sharp(framePath).resize({
258
+ width: scale,
259
+ withoutEnlargement: true
260
+ }).grayscale().blur(1).raw().toBuffer({ resolveWithObject: true });
261
+ return {
262
+ data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
263
+ width: info.width,
264
+ height: info.height
265
+ };
202
266
  }
203
267
  function computeIoU(a, b) {
204
- const ix1 = Math.max(a.x, b.x);
205
- const iy1 = Math.max(a.y, b.y);
206
- const ix2 = Math.min(a.x + a.width, b.x + b.width);
207
- const iy2 = Math.min(a.y + a.height, b.y + b.height);
208
- const iw = Math.max(0, ix2 - ix1);
209
- const ih = Math.max(0, iy2 - iy1);
210
- const intersection = iw * ih;
211
- if (intersection === 0) return 0;
212
- const aArea = a.width * a.height;
213
- const bArea = b.width * b.height;
214
- const union = aArea + bArea - intersection;
215
- return union === 0 ? 0 : intersection / union;
268
+ const ix1 = Math.max(a.x, b.x);
269
+ const iy1 = Math.max(a.y, b.y);
270
+ const ix2 = Math.min(a.x + a.width, b.x + b.width);
271
+ const iy2 = Math.min(a.y + a.height, b.y + b.height);
272
+ const intersection = Math.max(0, ix2 - ix1) * Math.max(0, iy2 - iy1);
273
+ if (intersection === 0) return 0;
274
+ const union = a.width * a.height + b.width * b.height - intersection;
275
+ return union === 0 ? 0 : intersection / union;
216
276
  }
217
277
  var IoUTracker = class {
218
- constructor(fps = DEFAULT_FPS, iouThreshold = IOU_THRESHOLD, animationThreshold = ANIMATION_FRAME_THRESHOLD) {
219
- this.fps = fps;
220
- this.iouThreshold = iouThreshold;
221
- this.animationThreshold = animationThreshold;
222
- }
223
- regions = [];
224
- extractedAnimations = [];
225
- update(boxes, pairIndex) {
226
- const animationIndices = /* @__PURE__ */ new Set();
227
- const matched = /* @__PURE__ */ new Set();
228
- for (let bi = 0; bi < boxes.length; bi++) {
229
- const box = boxes[bi];
230
- let bestIoU = 0;
231
- let bestRegionIdx = -1;
232
- for (let ri = 0; ri < this.regions.length; ri++) {
233
- if (matched.has(ri)) continue;
234
- const iou = computeIoU(box, this.regions[ri].box);
235
- if (iou > bestIoU) {
236
- bestIoU = iou;
237
- bestRegionIdx = ri;
238
- }
239
- }
240
- if (bestIoU > this.iouThreshold && bestRegionIdx !== -1) {
241
- const region = this.regions[bestRegionIdx];
242
- const gap = pairIndex - region.lastSeen;
243
- region.box = box;
244
- region.consecutiveCount++;
245
- region.lastSeen = pairIndex;
246
- region.weight *= Math.pow(DECAY_LAMBDA, gap);
247
- matched.add(bestRegionIdx);
248
- if (region.consecutiveCount >= this.animationThreshold) {
249
- animationIndices.add(bi);
250
- }
251
- } else {
252
- this.regions.push({
253
- box,
254
- consecutiveCount: 1,
255
- firstSeen: pairIndex,
256
- lastSeen: pairIndex,
257
- weight: 1
258
- });
259
- }
260
- }
261
- for (let ri = 0; ri < this.regions.length; ri++) {
262
- if (!matched.has(ri)) {
263
- const gap = pairIndex - this.regions[ri].lastSeen;
264
- this.regions[ri].weight *= Math.pow(DECAY_LAMBDA, gap);
265
- }
266
- }
267
- for (let i = 0; i < this.regions.length; i++) {
268
- const region = this.regions[i];
269
- if (region.weight <= 0.01 && !matched.has(i)) {
270
- this.collectAnimation(region);
271
- }
272
- }
273
- this.regions = filter(
274
- this.regions,
275
- (r, i) => r.weight > 0.01 || matched.has(i)
276
- );
277
- return animationIndices;
278
- }
279
- collectAnimation(region) {
280
- if (region.consecutiveCount >= this.animationThreshold) {
281
- const durationMs = region.consecutiveCount / this.fps * 1e3;
282
- this.extractedAnimations.push({
283
- type: "loading_spinner",
284
- // 기본값으로 loading_spinner 사용
285
- boundingBox: region.box,
286
- startFrameId: region.firstSeen,
287
- endFrameId: region.lastSeen,
288
- durationMs
289
- });
290
- }
291
- }
292
- flushAndGetAnimations() {
293
- for (const region of this.regions) {
294
- this.collectAnimation(region);
295
- }
296
- this.regions = [];
297
- return this.extractedAnimations;
298
- }
299
- getAnimationWeight(boxIndex, boxes) {
300
- if (boxIndex >= boxes.length) return 0;
301
- const box = boxes[boxIndex];
302
- let maxWeight = 0;
303
- for (const region of this.regions) {
304
- if (region.consecutiveCount >= this.animationThreshold) {
305
- const iou = computeIoU(box, region.box);
306
- if (iou > this.iouThreshold) {
307
- maxWeight = Math.max(maxWeight, region.weight);
308
- }
309
- }
310
- }
311
- return maxWeight;
312
- }
278
+ fps;
279
+ iouThreshold;
280
+ animationThreshold;
281
+ regions = [];
282
+ extractedAnimations = [];
283
+ constructor(fps = 5, iouThreshold = IOU_THRESHOLD, animationThreshold = 5) {
284
+ this.fps = fps;
285
+ this.iouThreshold = iouThreshold;
286
+ this.animationThreshold = animationThreshold;
287
+ }
288
+ update(boxes, pairIndex) {
289
+ const animationIndices = /* @__PURE__ */ new Set();
290
+ const matched = /* @__PURE__ */ new Set();
291
+ for (let bi = 0; bi < boxes.length; bi++) {
292
+ const box = boxes[bi];
293
+ let bestIoU = 0;
294
+ let bestRegionIdx = -1;
295
+ for (let ri = 0; ri < this.regions.length; ri++) {
296
+ if (matched.has(ri)) continue;
297
+ const iou = computeIoU(box, this.regions[ri].box);
298
+ if (iou > bestIoU) {
299
+ bestIoU = iou;
300
+ bestRegionIdx = ri;
301
+ }
302
+ }
303
+ if (bestIoU > this.iouThreshold && bestRegionIdx !== -1) {
304
+ const region = this.regions[bestRegionIdx];
305
+ const gap = pairIndex - region.lastSeen;
306
+ region.box = box;
307
+ region.consecutiveCount++;
308
+ region.lastSeen = pairIndex;
309
+ region.weight *= Math.pow(DECAY_LAMBDA, gap);
310
+ matched.add(bestRegionIdx);
311
+ if (region.consecutiveCount >= this.animationThreshold) animationIndices.add(bi);
312
+ } else this.regions.push({
313
+ box,
314
+ consecutiveCount: 1,
315
+ firstSeen: pairIndex,
316
+ lastSeen: pairIndex,
317
+ weight: 1
318
+ });
319
+ }
320
+ for (let ri = 0; ri < this.regions.length; ri++) if (!matched.has(ri)) {
321
+ const gap = pairIndex - this.regions[ri].lastSeen;
322
+ this.regions[ri].weight *= Math.pow(DECAY_LAMBDA, gap);
323
+ }
324
+ for (let i = 0; i < this.regions.length; i++) {
325
+ const region = this.regions[i];
326
+ if (region.weight <= .01 && !matched.has(i)) this.collectAnimation(region);
327
+ }
328
+ this.regions = filter(this.regions, (r, i) => r.weight > .01 || matched.has(i));
329
+ return animationIndices;
330
+ }
331
+ collectAnimation(region) {
332
+ if (region.consecutiveCount >= this.animationThreshold) {
333
+ const durationMs = region.consecutiveCount / this.fps * 1e3;
334
+ this.extractedAnimations.push({
335
+ type: "loading_spinner",
336
+ boundingBox: region.box,
337
+ startFrameId: region.firstSeen,
338
+ endFrameId: region.lastSeen,
339
+ durationMs
340
+ });
341
+ }
342
+ }
343
+ flushAndGetAnimations() {
344
+ for (const region of this.regions) this.collectAnimation(region);
345
+ this.regions = [];
346
+ return this.extractedAnimations;
347
+ }
348
+ getAnimationWeight(boxIndex, boxes) {
349
+ if (boxIndex >= boxes.length) return 0;
350
+ const box = boxes[boxIndex];
351
+ let maxWeight = 0;
352
+ for (const region of this.regions) if (region.consecutiveCount >= this.animationThreshold) {
353
+ if (computeIoU(box, region.box) > this.iouThreshold) maxWeight = Math.max(maxWeight, region.weight);
354
+ }
355
+ return maxWeight;
356
+ }
313
357
  };
314
- async function computeAKAZEDiff(cvLib, frame1, frame2) {
315
- const cv = cvLib;
316
- const mat1 = new cv.Mat(frame1.height, frame1.width, cv.CV_8UC1);
317
- mat1.data.set(frame1.data);
318
- const mat2 = new cv.Mat(frame2.height, frame2.width, cv.CV_8UC1);
319
- mat2.data.set(frame2.data);
320
- const kp1 = new cvLib.KeyPointVector();
321
- const kp2 = new cvLib.KeyPointVector();
322
- const desc1 = new cvLib.Mat();
323
- const desc2 = new cvLib.Mat();
324
- const mask1 = new cvLib.Mat();
325
- const mask2 = new cvLib.Mat();
326
- const akaze = new cvLib.AKAZE();
327
- let matches = null;
328
- try {
329
- akaze.detectAndCompute(mat1, mask1, kp1, desc1);
330
- akaze.detectAndCompute(mat2, mask2, kp2, desc2);
331
- const matchedKp1Indices = /* @__PURE__ */ new Set();
332
- const matchedKp2Indices = /* @__PURE__ */ new Set();
333
- if (desc1.rows > 0 && desc2.rows > 0) {
334
- const matcher = new cvLib.BFMatcher(cvLib.NORM_HAMMING, false);
335
- try {
336
- matches = new cvLib.DMatchVectorVector();
337
- matcher.knnMatch(desc1, desc2, matches, 2);
338
- for (let i = 0; i < matches.size(); i++) {
339
- const pair = matches.get(i);
340
- if (pair.size() < 2) continue;
341
- const m0 = pair.get(0);
342
- const m1 = pair.get(1);
343
- if (m0.distance < MATCH_DISTANCE_THRESHOLD * m1.distance) {
344
- matchedKp1Indices.add(m0.queryIdx);
345
- matchedKp2Indices.add(m0.trainIdx);
346
- }
347
- }
348
- } finally {
349
- matcher.delete();
350
- }
351
- }
352
- const sNew = [];
353
- for (let i = 0; i < kp2.size(); i++) {
354
- if (!matchedKp2Indices.has(i)) {
355
- const pt = kp2.get(i).pt;
356
- sNew.push({ x: pt.x, y: pt.y });
357
- }
358
- }
359
- const sLoss = [];
360
- for (let i = 0; i < kp1.size(); i++) {
361
- if (!matchedKp1Indices.has(i)) {
362
- const pt = kp1.get(i).pt;
363
- sLoss.push({ x: pt.x, y: pt.y });
364
- }
365
- }
366
- return { sNew, sLoss };
367
- } finally {
368
- mat1.delete();
369
- mat2.delete();
370
- kp1.delete();
371
- kp2.delete();
372
- desc1.delete();
373
- desc2.delete();
374
- mask1.delete();
375
- mask2.delete();
376
- akaze.delete();
377
- if (matches) matches.delete();
378
- }
379
- }
358
+ /**
359
+ * Pixel-level difference fallback for AKAZE blind spots.
360
+ *
361
+ * When AKAZE produces sparse results (typical for UI screen recordings
362
+ * where form fields, dropdowns, or overlays change), this function
363
+ * detects changed regions via cv.absdiff and generates synthetic
364
+ * Point2D[] that feed into the existing DBSCAN → IoU → G(t) pipeline.
365
+ *
366
+ * Algorithm:
367
+ * 1. absdiff(frame1, frame2) → grayscale difference
368
+ * 2. GaussianBlur reduce JPEG compression noise
369
+ * 3. threshold binary mask of significant changes
370
+ * 4. findContours bounding rects of changed regions
371
+ * 5. Grid sampling within each bounding rect → Point2D[]
372
+ *
373
+ * @param cvLib - Initialized OpenCV runtime shared by the analyzer.
374
+ * @param frame1 - Previous grayscale frame, with the same dimensions as frame2.
375
+ * @param frame2 - Next grayscale frame, with the same dimensions as frame1.
376
+ * @returns Grid-sampled points from changed regions.
377
+ * @throws Propagates allocation or OpenCV errors after releasing acquired handles.
378
+ */
380
379
  function computePixelDiff(cvLib, frame1, frame2) {
381
- const cv = cvLib;
382
- const mat1 = new cv.Mat(frame1.height, frame1.width, cv.CV_8UC1);
383
- const mat2 = new cv.Mat(frame2.height, frame2.width, cv.CV_8UC1);
384
- const diff = new cv.Mat();
385
- const blurred = new cv.Mat();
386
- const binary = new cv.Mat();
387
- const contours = new cv.MatVector();
388
- const hierarchy = new cv.Mat();
389
- try {
390
- mat1.data.set(frame1.data);
391
- mat2.data.set(frame2.data);
392
- cv.absdiff(mat1, mat2, diff);
393
- const ksize = new cv.Size(
394
- PIXELDIFF_GAUSSIAN_KERNEL,
395
- PIXELDIFF_GAUSSIAN_KERNEL
396
- );
397
- cv.GaussianBlur(diff, blurred, ksize, 0);
398
- cv.threshold(
399
- blurred,
400
- binary,
401
- PIXELDIFF_BINARY_THRESHOLD,
402
- 255,
403
- cv.THRESH_BINARY
404
- );
405
- cv.findContours(
406
- binary,
407
- contours,
408
- hierarchy,
409
- cv.RETR_EXTERNAL,
410
- cv.CHAIN_APPROX_SIMPLE
411
- );
412
- const points = [];
413
- for (let c = 0; c < contours.size(); c++) {
414
- const contour = contours.get(c);
415
- const rect = cv.boundingRect(contour);
416
- if (rect.width * rect.height < PIXELDIFF_CONTOUR_MIN_AREA) continue;
417
- for (let y = rect.y; y < rect.y + rect.height; y += PIXELDIFF_SAMPLE_SPACING) {
418
- for (let x = rect.x; x < rect.x + rect.width; x += PIXELDIFF_SAMPLE_SPACING) {
419
- points.push({ x, y });
420
- }
421
- }
422
- }
423
- return points;
424
- } finally {
425
- mat1.delete();
426
- mat2.delete();
427
- diff.delete();
428
- blurred.delete();
429
- binary.delete();
430
- contours.delete();
431
- hierarchy.delete();
432
- }
380
+ const cv = cvLib;
381
+ let mat1 = null;
382
+ let mat2 = null;
383
+ let diff = null;
384
+ let blurred = null;
385
+ let binary = null;
386
+ let contours = null;
387
+ let hierarchy = null;
388
+ try {
389
+ mat1 = new cv.Mat(frame1.height, frame1.width, cv.CV_8UC1);
390
+ mat2 = new cv.Mat(frame2.height, frame2.width, cv.CV_8UC1);
391
+ diff = new cv.Mat();
392
+ blurred = new cv.Mat();
393
+ binary = new cv.Mat();
394
+ contours = new cv.MatVector();
395
+ hierarchy = new cv.Mat();
396
+ mat1.data.set(frame1.data);
397
+ mat2.data.set(frame2.data);
398
+ cv.absdiff(mat1, mat2, diff);
399
+ const ksize = new cv.Size(3, 3);
400
+ cv.GaussianBlur(diff, blurred, ksize, 0);
401
+ cv.threshold(blurred, binary, 30, 255, cv.THRESH_BINARY);
402
+ cv.findContours(binary, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE);
403
+ const points = [];
404
+ for (let c = 0; c < contours.size(); c++) {
405
+ const contour = contours.get(c);
406
+ try {
407
+ const rect = cv.boundingRect(contour);
408
+ if (rect.width * rect.height < 100) continue;
409
+ for (let y = rect.y; y < rect.y + rect.height; y += 8) for (let x = rect.x; x < rect.x + rect.width; x += 8) points.push({
410
+ x,
411
+ y
412
+ });
413
+ } finally {
414
+ contour.delete();
415
+ }
416
+ }
417
+ return points;
418
+ } finally {
419
+ mat1?.delete();
420
+ mat2?.delete();
421
+ diff?.delete();
422
+ blurred?.delete();
423
+ binary?.delete();
424
+ contours?.delete();
425
+ hierarchy?.delete();
426
+ }
433
427
  }
434
428
  function computeInformationGain(clusters, clusterPoints, imageArea, animationIndices, animationWeights) {
435
- if (clusters.length === 0) return 0;
436
- let gain = 0;
437
- for (let i = 0; i < clusters.length; i++) {
438
- const box = clusters[i];
439
- const clusterArea = box.width * box.height;
440
- if (clusterArea <= 0) continue;
441
- const normalizedArea = clusterArea / imageArea;
442
- const featureDensity = clusterPoints[i] / clusterArea;
443
- let contribution = normalizedArea * featureDensity;
444
- if (animationIndices.has(i)) {
445
- const animWeight = animationWeights[i] ?? 0;
446
- contribution *= 1 - animWeight;
447
- }
448
- gain += contribution;
449
- }
450
- return gain;
429
+ if (clusters.length === 0) return 0;
430
+ let gain = 0;
431
+ for (let i = 0; i < clusters.length; i++) {
432
+ const box = clusters[i];
433
+ const clusterArea = box.width * box.height;
434
+ if (clusterArea <= 0) continue;
435
+ let contribution = clusterArea / imageArea * (clusterPoints[i] / clusterArea);
436
+ if (animationIndices.has(i)) {
437
+ const animWeight = animationWeights[i] ?? 0;
438
+ contribution *= 1 - animWeight;
439
+ }
440
+ gain += contribution;
441
+ }
442
+ return gain;
451
443
  }
452
- async function analyzeBatch(cvLib, frames, scale, tracker, pairOffset) {
453
- const edges = [];
454
- const preprocessed = await Promise.all(
455
- map(frames, (f) => preprocessFrame(f.extractPath, scale))
456
- );
457
- const imageWidth = preprocessed[0]?.width ?? scale;
458
- const imageHeight = preprocessed[0]?.height ?? Math.round(scale * 9 / 16);
459
- const imageArea = imageWidth * imageHeight;
460
- for (let i = 0; i < frames.length - 1; i++) {
461
- const pairIndex = pairOffset + i;
462
- try {
463
- const { sNew } = await computeAKAZEDiff(
464
- cvLib,
465
- preprocessed[i],
466
- preprocessed[i + 1]
467
- );
468
- let dbscanResult = dbscan(sNew, imageWidth, imageHeight);
469
- let clusters = dbscanResult.boundingBoxes;
470
- if (clusters.length === 0) {
471
- const pixelDiffPoints = computePixelDiff(
472
- cvLib,
473
- preprocessed[i],
474
- preprocessed[i + 1]
475
- );
476
- if (pixelDiffPoints.length > 0) {
477
- logger.debug(
478
- `Edge ${frames[i].id}->${frames[i + 1].id}: pixel-diff fallback (${pixelDiffPoints.length} points)`
479
- );
480
- dbscanResult = dbscan(
481
- pixelDiffPoints,
482
- imageWidth,
483
- imageHeight,
484
- void 0,
485
- 2
486
- );
487
- clusters = dbscanResult.boundingBoxes;
488
- }
489
- }
490
- const clusterPointCounts = new Array(clusters.length).fill(0);
491
- for (const label of dbscanResult.labels) {
492
- if (label >= 0) {
493
- clusterPointCounts[label]++;
494
- }
495
- }
496
- const animationIndices = tracker.update(clusters, pairIndex);
497
- const animationWeights = map(
498
- clusters,
499
- (_, ci) => animationIndices.has(ci) ? tracker.getAnimationWeight(ci, clusters) : 0
500
- );
501
- const score = computeInformationGain(
502
- clusters,
503
- clusterPointCounts,
504
- imageArea,
505
- animationIndices,
506
- animationWeights
507
- );
508
- logger.debug(
509
- `Edge ${frames[i].id}->${frames[i + 1].id} G(t)=${score.toFixed(6)}`
510
- );
511
- edges.push({
512
- sourceId: frames[i].id,
513
- targetId: frames[i + 1].id,
514
- score
515
- });
516
- } catch (err) {
517
- logger.debug(`Frame pair analysis failed: ${String(err)}`);
518
- edges.push({
519
- sourceId: frames[i].id,
520
- targetId: frames[i + 1].id,
521
- score: 0
522
- });
523
- }
524
- }
525
- return edges;
444
+ /**
445
+ * Analyze one batch, retaining its boundary frame for the following batch.
446
+ * @param cvLib - Initialized OpenCV runtime.
447
+ * @param akaze - Detector owned by analyzeFrames.
448
+ * @param frames - Boundary frame followed by new adjacent frames.
449
+ * @param carry - Boundary bytes and live features transferred from the previous batch.
450
+ * @param scale - Maximum preprocessing width.
451
+ * @param tracker - Stateful animation tracker shared across batches.
452
+ * @param pairOffset - Global position of this batch's first pair.
453
+ * @returns Scores, pair failure count, and ownership of the final frame's features.
454
+ */
455
+ async function analyzeBatch(cvLib, akaze, frames, carry, scale, tracker, pairOffset) {
456
+ const edges = [];
457
+ let failures = 0;
458
+ let prev = carry?.features ?? null;
459
+ let next = null;
460
+ try {
461
+ const preprocessed = await Promise.all(map(frames, (f, index) => index === 0 && carry ? carry.preprocessed : preprocessFrame(f.extractPath, scale)));
462
+ const imageWidth = preprocessed[0]?.width ?? scale;
463
+ const imageHeight = preprocessed[0]?.height ?? Math.round(scale * 9 / 16);
464
+ const imageArea = imageWidth * imageHeight;
465
+ for (let i = 0; i < frames.length - 1; i++) {
466
+ const pairIndex = pairOffset + i;
467
+ try {
468
+ prev ??= computeFrameFeatures(cvLib, akaze, preprocessed[i]);
469
+ next = computeFrameFeatures(cvLib, akaze, preprocessed[i + 1]);
470
+ let dbscanResult = dbscan(computeNewPoints(cvLib, prev, next), imageWidth, imageHeight);
471
+ let clusters = dbscanResult.boundingBoxes;
472
+ if (clusters.length === 0) {
473
+ const pixelDiffPoints = computePixelDiff(cvLib, preprocessed[i], preprocessed[i + 1]);
474
+ if (pixelDiffPoints.length > 0) {
475
+ logger.debug(`Edge ${frames[i].id}->${frames[i + 1].id}: pixel-diff fallback (${pixelDiffPoints.length} points)`);
476
+ dbscanResult = dbscan(pixelDiffPoints, imageWidth, imageHeight, void 0, 2);
477
+ clusters = dbscanResult.boundingBoxes;
478
+ }
479
+ }
480
+ const clusterPointCounts = new Array(clusters.length).fill(0);
481
+ for (const label of dbscanResult.labels) if (label >= 0) clusterPointCounts[label]++;
482
+ const animationIndices = tracker.update(clusters, pairIndex);
483
+ const animationWeights = map(clusters, (_, ci) => animationIndices.has(ci) ? tracker.getAnimationWeight(ci, clusters) : 0);
484
+ const score = computeInformationGain(clusters, clusterPointCounts, imageArea, animationIndices, animationWeights);
485
+ logger.debug(`Edge ${frames[i].id}->${frames[i + 1].id} G(t)=${score.toFixed(6)}`);
486
+ edges.push({
487
+ sourceId: frames[i].id,
488
+ targetId: frames[i + 1].id,
489
+ score
490
+ });
491
+ } catch (err) {
492
+ logger.warn(`Frame pair analysis failed: ${String(err)}`);
493
+ failures++;
494
+ edges.push({
495
+ sourceId: frames[i].id,
496
+ targetId: frames[i + 1].id,
497
+ score: 0
498
+ });
499
+ } finally {
500
+ prev?.delete();
501
+ prev = next;
502
+ next = null;
503
+ }
504
+ }
505
+ const result = {
506
+ edges,
507
+ failures,
508
+ analysisResolution: {
509
+ width: imageWidth,
510
+ height: imageHeight
511
+ },
512
+ carry: prev ? {
513
+ preprocessed: preprocessed[preprocessed.length - 1],
514
+ features: prev
515
+ } : null
516
+ };
517
+ prev = null;
518
+ return result;
519
+ } finally {
520
+ prev?.delete();
521
+ next?.delete();
522
+ }
526
523
  }
524
+ /**
525
+ * Analyze adjacent frame pairs to compute information gain scores (G(t)).
526
+ * Processes frames in batches for memory efficiency.
527
+ *
528
+ * Pipeline:
529
+ * 1. AKAZE Feature Set Difference
530
+ * 2. DBSCAN Spatial Clustering
531
+ * 3. Spatio-temporal IoU Tracking
532
+ * 4. G(t) Information Gain Scoring
533
+ * @param ctx - Frames, analysis options, and the progress callback for this run.
534
+ * @returns Adjacent scores and tracked animations in analysis coordinates.
535
+ * @throws Propagates runtime errors and rejects total failure of two or more pairs after cleanup.
536
+ */
527
537
  async function analyzeFrames(ctx) {
528
- const { frames } = ctx;
529
- if (frames.length < 2) return { edges: [], animations: [] };
530
- logger.debug(
531
- `Analyzing ${frames.length} frames in batches of ${OPENCV_BATCH_SIZE}`
532
- );
533
- const cvLib = await ensureOpenCV();
534
- const edges = [];
535
- const tracker = new IoUTracker(
536
- ctx.options.fps,
537
- ctx.options.iouThreshold,
538
- ctx.options.animationThreshold
539
- );
540
- const scale = ctx.options.scale;
541
- for (let i = 0; i < frames.length - 1; i += OPENCV_BATCH_SIZE) {
542
- const batchEnd = Math.min(i + OPENCV_BATCH_SIZE + 1, frames.length);
543
- const batch = frames.slice(i, batchEnd);
544
- const batchEdges = await analyzeBatch(cvLib, batch, scale, tracker, i);
545
- edges.push(...batchEdges);
546
- const progress = Math.min(
547
- 100,
548
- (i + OPENCV_BATCH_SIZE) / (frames.length - 1) * 100
549
- );
550
- ctx.emitProgress(progress);
551
- }
552
- const animations = tracker.flushAndGetAnimations();
553
- logger.debug(
554
- `Computed ${edges.length} score edges and ${animations.length} animations`
555
- );
556
- return { edges, animations };
538
+ const { frames } = ctx;
539
+ if (frames.length < 2) return {
540
+ edges: [],
541
+ animations: [],
542
+ analysisResolution: {
543
+ width: 0,
544
+ height: 0
545
+ }
546
+ };
547
+ logger.debug(`Analyzing ${frames.length} frames in batches of ${10}`);
548
+ const cvLib = await ensureOpenCV();
549
+ const edges = [];
550
+ const tracker = new IoUTracker(ctx.effectiveFps ?? ctx.options.fps, ctx.options.iouThreshold, ctx.options.animationThreshold);
551
+ const scale = ctx.options.scale;
552
+ let akaze = null;
553
+ let carry = null;
554
+ let analysisResolution = {
555
+ width: 0,
556
+ height: 0
557
+ };
558
+ let failures = 0;
559
+ try {
560
+ akaze = new cvLib.AKAZE();
561
+ for (let i = 0; i < frames.length - 1; i += 10) {
562
+ const batch = [frames[i], ...frames.slice(i + 1, i + 1 + 10)];
563
+ const result = await analyzeBatch(cvLib, akaze, batch, carry, scale, tracker, i);
564
+ carry = result.carry;
565
+ failures += result.failures;
566
+ if (i === 0) analysisResolution = result.analysisResolution;
567
+ edges.push(...result.edges);
568
+ const progress = Math.min(100, (i + 10) / (frames.length - 1) * 100);
569
+ ctx.emitProgress(progress);
570
+ }
571
+ } finally {
572
+ carry?.features.delete();
573
+ akaze?.delete();
574
+ }
575
+ const pairs = frames.length - 1;
576
+ if (pairs >= 2 && failures === pairs) throw new Error(`All ${pairs} frame pairs failed analysis`);
577
+ const animations = tracker.flushAndGetAnimations();
578
+ logger.debug(`Computed ${edges.length} score edges and ${animations.length} animations`);
579
+ return {
580
+ edges,
581
+ animations,
582
+ analysisResolution
583
+ };
557
584
  }
558
585
 
559
- // src/core/extractor.ts
560
- import { readdir } from "fs/promises";
561
- import { join as join2 } from "path";
562
- import { path as ffprobePath } from "@ffprobe-installer/ffprobe";
563
- import { filter as filter2, map as map2 } from "@winglet/common-utils";
564
- import { execa } from "execa";
565
- import ffmpegPath from "ffmpeg-static";
586
+ //#endregion
587
+ //#region src/core/utils/metadata/build-video-metadata.ts
588
+ /**
589
+ * Read output dimensions and build consistent video and animation metadata.
590
+ * JPEG finalization does not resize, so the source dimensions match the output.
591
+ * @param ctx Pipeline state with source duration, effective FPS and analysis-space animations.
592
+ * @param selected Selected frames in output order; the first candidate is the fallback.
593
+ * @param analysisResolution Analysis dimensions; absent or zero dimensions imply no scaling.
594
+ * @returns Video metadata and new output-space animations, retaining zero-based frame IDs.
595
+ * @throws If sharp cannot read the selected or fallback image. Empty input performs no image I/O.
596
+ */
597
+ async function buildVideoMetadata(ctx, selected, analysisResolution) {
598
+ const firstFrame = selected[0] ?? ctx.frames[0];
599
+ const dimensions = firstFrame ? await sharp(firstFrame.extractPath).metadata() : void 0;
600
+ const width = dimensions?.width ?? 0;
601
+ const height = dimensions?.height ?? 0;
602
+ const sx = analysisResolution?.width ? width / analysisResolution.width : 1;
603
+ const sy = analysisResolution?.height ? height / analysisResolution.height : 1;
604
+ const lastTimestamp = ctx.frames[ctx.frames.length - 1]?.timestamp ?? 0;
605
+ const duration = ctx.options.mode === "frames" ? lastTimestamp : ctx.sourceDurationSec ?? lastTimestamp;
606
+ return {
607
+ video: {
608
+ originalDurationMs: Math.round(duration * 1e3),
609
+ fps: ctx.options.mode === "frames" ? 1 : ctx.effectiveFps ?? ctx.options.fps,
610
+ resolution: {
611
+ width,
612
+ height
613
+ }
614
+ },
615
+ animations: (ctx.animations ?? []).map((animation) => {
616
+ const box = animation.boundingBox;
617
+ const x = Math.max(0, Math.min(width, Math.round(box.x * sx)));
618
+ const y = Math.max(0, Math.min(height, Math.round(box.y * sy)));
619
+ return {
620
+ ...animation,
621
+ boundingBox: {
622
+ x,
623
+ y,
624
+ width: Math.max(0, Math.min(width - x, Math.round(box.width * sx))),
625
+ height: Math.max(0, Math.min(height - y, Math.round(box.height * sy)))
626
+ }
627
+ };
628
+ })
629
+ };
630
+ }
566
631
 
567
- // src/utils/paths.ts
568
- import { mkdir, stat } from "fs/promises";
569
- import { homedir } from "os";
570
- import { basename, extname, resolve } from "path";
632
+ //#endregion
633
+ //#region src/core/constants/workspace-layout.ts
634
+ /**
635
+ * Temp workspace naming and frame file layout for pipeline runs.
636
+ */
637
+ const APP_NAME = "scene-sieve";
638
+ const WORKSPACE_PREFIX = `${APP_NAME}-`;
639
+ const TEMP_BASE_DIR = tmpdir();
640
+ const FRAME_OUTPUT_EXTENSION = ".jpg";
641
+ const FRAME_FILENAME_PATTERN = "frame_%06d.jpg";
642
+ function getTempWorkspaceDir(sessionId) {
643
+ return join(TEMP_BASE_DIR, `${WORKSPACE_PREFIX}${sessionId}`);
644
+ }
645
+
646
+ //#endregion
647
+ //#region src/core/utils/filesystem/paths.ts
571
648
  async function ensureDir(dirPath) {
572
- await mkdir(dirPath, { recursive: true });
649
+ await mkdir(dirPath, { recursive: true });
573
650
  }
574
651
  async function fileExists(filePath) {
575
- try {
576
- await stat(filePath);
577
- return true;
578
- } catch {
579
- return false;
580
- }
652
+ try {
653
+ await stat(filePath);
654
+ return true;
655
+ } catch {
656
+ return false;
657
+ }
581
658
  }
659
+ /**
660
+ * Expand leading ~ to homedir. Node's path.resolve() does not expand ~,
661
+ * so paths like ~/Desktop/foo depend on process.cwd() and can produce
662
+ * different results when run from different directories.
663
+ */
582
664
  function expandTilde(p) {
583
- if (p === "~") return homedir();
584
- if (p.startsWith("~/") || p.startsWith("~\\")) {
585
- return resolve(homedir(), p.slice(2));
586
- }
587
- return p;
665
+ if (p === "~") return homedir();
666
+ if (p.startsWith("~/") || p.startsWith("~\\")) return resolve(homedir(), p.slice(2));
667
+ return p;
588
668
  }
669
+ /**
670
+ * Resolve path to absolute. Expands ~ to homedir first so that the result
671
+ * does not depend on process.cwd().
672
+ */
589
673
  function resolveAbsolute(p) {
590
- return resolve(expandTilde(p));
674
+ return resolve(expandTilde(p));
591
675
  }
676
+ /**
677
+ * Derive default output directory name from input file path.
678
+ * e.g., /path/to/video.mp4 -> /path/to/video_scenes
679
+ */
592
680
  function deriveOutputPath(inputPath) {
593
- const dir = resolve(inputPath, "..");
594
- const name = basename(inputPath, extname(inputPath));
595
- return resolve(dir, `${name}_scenes`);
681
+ return resolve(resolve(inputPath, ".."), `${basename(inputPath, extname(inputPath))}_scenes`);
596
682
  }
597
683
 
598
- // src/core/extractor.ts
684
+ //#endregion
685
+ //#region src/core/extractor/extractor.ts
686
+ /**
687
+ * Extract frames from video/GIF using FFmpeg.
688
+ * @param ctx Pipeline context; records effectiveFps and sourceDurationSec for video input.
689
+ * @returns Extracted candidates, or the unchanged input array in frames mode.
690
+ * @throws When the input is missing, metadata has no video stream, or FFmpeg fails.
691
+ */
599
692
  async function extractFrames(ctx) {
600
- const framesDir = join2(ctx.workspacePath, "frames");
601
- const { inputPath, fps, maxFrames, scale } = ctx.options;
602
- if (!inputPath) {
603
- throw new Error("inputPath is required for frame extraction");
604
- }
605
- const exists = await fileExists(inputPath);
606
- if (!exists) {
607
- throw new Error(`Input file not found: ${inputPath}`);
608
- }
609
- const metadata = await getVideoMetadata(inputPath).catch((err) => {
610
- logger.debug(`ffprobe failed: ${err.message}`);
611
- return null;
612
- });
613
- if (!metadata || !metadata.format) {
614
- throw new Error(`Could not read file metadata: ${inputPath}`);
615
- }
616
- const formatName = metadata.format.format_name ?? "";
617
- const duration = parseFloat(metadata.format.duration ?? "0");
618
- const hasVideoStream = metadata.streams?.some((s) => s.codec_type === "video") ?? false;
619
- if (!hasVideoStream) {
620
- throw new Error(
621
- `No video stream found in file: ${inputPath} (detected format: ${formatName})`
622
- );
623
- }
624
- logger.debug(
625
- `Detected format: ${formatName} (Duration: ${duration.toFixed(1)}s), path: ${inputPath}`
626
- );
627
- await ensureDir(framesDir);
628
- let effectiveFps = fps;
629
- if (duration > 0) {
630
- const fpsCap = maxFrames / duration;
631
- effectiveFps = Math.min(fps, fpsCap);
632
- effectiveFps = Math.max(0.5, effectiveFps);
633
- logger.debug(
634
- `FPS: ${fps} \u2192 effective: ${effectiveFps.toFixed(2)} (maxFrames: ${maxFrames})`
635
- );
636
- }
637
- const frames = await extractByFps(
638
- inputPath,
639
- framesDir,
640
- effectiveFps,
641
- scale,
642
- duration
643
- );
644
- ctx.emitProgress(100);
645
- logger.debug(`Extracted ${frames.length} frames`);
646
- return frames;
693
+ if (ctx.options.mode === "frames") {
694
+ ctx.effectiveFps = 1;
695
+ return ctx.frames;
696
+ }
697
+ const framesDir = join(ctx.workspacePath, "frames");
698
+ const { inputPath, fps, maxFrames, scale } = ctx.options;
699
+ if (!inputPath) throw new Error("inputPath is required for frame extraction");
700
+ if (!await fileExists(inputPath)) throw new Error(`Input file not found: ${inputPath}`);
701
+ const metadata = await getVideoMetadata(inputPath).catch((err) => {
702
+ logger.debug(`ffprobe failed: ${err.message}`);
703
+ return null;
704
+ });
705
+ if (!metadata || !metadata.format) throw new Error(`Could not read file metadata: ${inputPath}`);
706
+ const formatName = metadata.format.format_name ?? "";
707
+ const duration = parseFloat(metadata.format.duration ?? "0");
708
+ if (!(metadata.streams?.some((s) => s.codec_type === "video") ?? false)) throw new Error(`No video stream found in file: ${inputPath} (detected format: ${formatName})`);
709
+ logger.debug(`Detected format: ${formatName} (Duration: ${duration.toFixed(1)}s), path: ${inputPath}`);
710
+ await ensureDir(framesDir);
711
+ const frameLimit = Math.max(2, maxFrames);
712
+ let effectiveFps = fps;
713
+ if (duration > 0) {
714
+ const fpsCap = frameLimit / duration;
715
+ effectiveFps = Math.min(fps, fpsCap);
716
+ logger.debug(`FPS: ${fps} → effective: ${effectiveFps.toFixed(2)} (maxFrames: ${maxFrames})`);
717
+ }
718
+ ctx.effectiveFps = effectiveFps;
719
+ ctx.sourceDurationSec = duration;
720
+ const frames = await extractByFps(inputPath, framesDir, effectiveFps, scale, frameLimit);
721
+ ctx.emitProgress(100);
722
+ logger.debug(`Extracted ${frames.length} frames`);
723
+ return frames;
647
724
  }
648
- async function extractByFps(inputPath, outputDir, fps, scale, duration) {
649
- const outputPattern = join2(outputDir, FRAME_FILENAME_PATTERN);
650
- await execa(ffmpegPath, [
651
- "-i",
652
- inputPath,
653
- "-vf",
654
- `fps=${fps},scale=-1:${scale}`,
655
- "-q:v",
656
- "2",
657
- outputPattern
658
- ]);
659
- return buildFrameList(outputDir, duration);
725
+ /**
726
+ * Write scaled JPEG candidates through the bundled FFmpeg runtime.
727
+ * @param inputPath Readable video input.
728
+ * @param outputDir Existing frame directory.
729
+ * @param fps Positive effective sampling frequency.
730
+ * @param scale Output image height.
731
+ * @param frameLimit Maximum number of output frames.
732
+ * @returns Candidates with local output-grid timestamps; rejects on extraction failure.
733
+ */
734
+ async function extractByFps(inputPath, outputDir, fps, scale, frameLimit) {
735
+ const outputPattern = join(outputDir, FRAME_FILENAME_PATTERN);
736
+ await execa(ffmpegPath, [
737
+ "-i",
738
+ inputPath,
739
+ "-vf",
740
+ `fps=${fps},scale=-1:${scale}`,
741
+ "-q:v",
742
+ "2",
743
+ "-frames:v",
744
+ String(frameLimit),
745
+ outputPattern
746
+ ]);
747
+ return buildFrameList(outputDir, fps);
660
748
  }
661
749
  async function getVideoMetadata(inputPath) {
662
- const { stdout } = await execa(ffprobePath, [
663
- "-v",
664
- "quiet",
665
- "-print_format",
666
- "json",
667
- "-show_format",
668
- "-show_streams",
669
- inputPath
670
- ]);
671
- return JSON.parse(stdout);
750
+ const { stdout } = await execa(path, [
751
+ "-v",
752
+ "quiet",
753
+ "-print_format",
754
+ "json",
755
+ "-show_format",
756
+ "-show_streams",
757
+ inputPath
758
+ ]);
759
+ return JSON.parse(stdout);
672
760
  }
673
- async function buildFrameList(framesDir, duration) {
674
- const files = await readdir(framesDir);
675
- const jpgFiles = filter2(files, (f) => f.endsWith(".jpg")).sort();
676
- if (jpgFiles.length === 0) {
677
- return [];
678
- }
679
- return map2(jpgFiles, (file, index) => ({
680
- id: index,
681
- timestamp: duration > 0 && jpgFiles.length > 1 ? duration * index / (jpgFiles.length - 1) : index,
682
- extractPath: join2(framesDir, file)
683
- }));
761
+ /**
762
+ * Read sorted JPEG paths and attach local output-grid times.
763
+ * @param framesDir Extracted frame directory; filesystem errors propagate.
764
+ * @param effectiveFps Positive frequency used by the fps filter.
765
+ * @returns Zero-based candidates without a segment seek offset.
766
+ */
767
+ async function buildFrameList(framesDir, effectiveFps) {
768
+ const jpgFiles = filter(await readdir(framesDir), (f) => f.endsWith(".jpg")).sort();
769
+ if (jpgFiles.length === 0) return [];
770
+ return map(jpgFiles, (file, index) => ({
771
+ id: index,
772
+ timestamp: index / effectiveFps,
773
+ extractPath: join(framesDir, file)
774
+ }));
684
775
  }
685
- async function extractFramesForRange(inputPath, outputDir, fps, scale, startTime, duration) {
686
- const outputPattern = join2(outputDir, FRAME_FILENAME_PATTERN);
687
- await execa(ffmpegPath, [
688
- "-ss",
689
- String(startTime),
690
- "-i",
691
- inputPath,
692
- "-t",
693
- String(duration),
694
- "-vf",
695
- `fps=${fps},scale=-1:${scale}`,
696
- "-q:v",
697
- "2",
698
- outputPattern
699
- ]);
700
- return buildFrameList(outputDir, duration);
776
+ /**
777
+ * Extract frames from a specific time range of a video using FFmpeg.
778
+ * Uses input seeking (-ss before -i) for fast seek + -t for duration.
779
+ *
780
+ * @param inputPath - Path to the video file
781
+ * @param outputDir - Directory to write extracted frames
782
+ * @param fps - Frames per second for extraction
783
+ * @param scale - Height scale for vision analysis
784
+ * @param startTime - Start time in seconds
785
+ * @param duration - Duration in seconds to extract
786
+ * @param frameLimit - Positive output limit; defaults to the range's grid capacity
787
+ * @returns Array of FrameNode with segment-local timestamps (starting from 0)
788
+ */
789
+ async function extractFramesForRange(inputPath, outputDir, fps, scale, startTime, duration, frameLimit = Math.ceil(duration * fps)) {
790
+ const outputPattern = join(outputDir, FRAME_FILENAME_PATTERN);
791
+ await execa(ffmpegPath, [
792
+ "-ss",
793
+ String(startTime),
794
+ "-i",
795
+ inputPath,
796
+ "-t",
797
+ String(duration),
798
+ "-vf",
799
+ `fps=${fps},scale=-1:${scale}`,
800
+ "-q:v",
801
+ "2",
802
+ "-frames:v",
803
+ String(frameLimit),
804
+ outputPattern
805
+ ]);
806
+ return buildFrameList(outputDir, fps);
701
807
  }
702
808
 
703
- // src/core/input-resolver.ts
704
- import { join as join4 } from "path";
809
+ //#endregion
810
+ //#region src/core/input-resolver/validation/validate-options.ts
811
+ /**
812
+ * Reject invalid numeric options before defaults or pipeline effects are applied.
813
+ * @param options - Supplied options; omitted numeric fields use pipeline defaults.
814
+ * @returns Nothing when all supplied numeric fields satisfy their contracts.
815
+ * @throws An input error naming the invalid option and its received value.
816
+ */
817
+ function validateOptions(options) {
818
+ for (const [name, min, max, integer, exclusiveMin, requirement] of [
819
+ [
820
+ "count",
821
+ 1,
822
+ Infinity,
823
+ true,
824
+ false,
825
+ "an integer >= 1"
826
+ ],
827
+ [
828
+ "threshold",
829
+ 0,
830
+ 1,
831
+ false,
832
+ true,
833
+ "in range (0, 1] and finite"
834
+ ],
835
+ [
836
+ "fps",
837
+ 0,
838
+ Infinity,
839
+ false,
840
+ true,
841
+ "finite and > 0"
842
+ ],
843
+ [
844
+ "maxFrames",
845
+ 2,
846
+ Infinity,
847
+ true,
848
+ false,
849
+ "an integer >= 2"
850
+ ],
851
+ [
852
+ "scale",
853
+ 16,
854
+ Infinity,
855
+ true,
856
+ false,
857
+ "an integer >= 16"
858
+ ],
859
+ [
860
+ "quality",
861
+ 1,
862
+ 100,
863
+ true,
864
+ false,
865
+ "an integer in range [1, 100]"
866
+ ],
867
+ [
868
+ "iouThreshold",
869
+ 0,
870
+ 1,
871
+ false,
872
+ false,
873
+ "finite and in range [0, 1]"
874
+ ],
875
+ [
876
+ "animationThreshold",
877
+ 1,
878
+ Infinity,
879
+ true,
880
+ false,
881
+ "an integer >= 1"
882
+ ],
883
+ [
884
+ "maxSegmentDuration",
885
+ 0,
886
+ Infinity,
887
+ false,
888
+ true,
889
+ "finite and > 0"
890
+ ],
891
+ [
892
+ "concurrency",
893
+ 1,
894
+ Infinity,
895
+ true,
896
+ false,
897
+ "an integer >= 1"
898
+ ]
899
+ ]) {
900
+ const value = options[name];
901
+ if (value === void 0) continue;
902
+ if (!Number.isFinite(value) || integer && !Number.isInteger(value) || (exclusiveMin ? value <= min : value < min) || value > max) throw new Error(`${name} must be ${requirement}, received: ${value}`);
903
+ }
904
+ }
705
905
 
706
- // src/core/workspace.ts
707
- import { readdir as readdir2, rename, rm, stat as stat2, writeFile } from "fs/promises";
708
- import { join as join3 } from "path";
709
- import { map as map3 } from "@winglet/common-utils";
710
- import sharp2 from "sharp";
906
+ //#endregion
907
+ //#region src/core/workspace/workspace.ts
711
908
  async function createWorkspace(sessionId) {
712
- const workspacePath = getTempWorkspaceDir(sessionId);
713
- await ensureDir(join3(workspacePath, "frames"));
714
- await ensureDir(join3(workspacePath, "output"));
715
- return workspacePath;
909
+ const workspacePath = getTempWorkspaceDir(sessionId);
910
+ await ensureDir(join(workspacePath, "frames"));
911
+ await ensureDir(join(workspacePath, "output"));
912
+ return workspacePath;
716
913
  }
717
914
  async function finalizeOutput(ctx, selectedFrames) {
718
- const stagingDir = join3(ctx.workspacePath, "output");
719
- const outputPath = ctx.options.outputPath;
720
- const quality = ctx.options.quality;
721
- const outputFiles = [];
722
- const framesMetadata = [];
723
- const totalFramesCount = ctx.frames.length;
724
- const padding = Math.max(4, String(totalFramesCount).length);
725
- for (let i = 0; i < selectedFrames.length; i++) {
726
- const frame = selectedFrames[i];
727
- const fileName = `frame_${String(frame.id + 1).padStart(padding, "0")}.jpg`;
728
- const destPath = join3(stagingDir, fileName);
729
- await sharp2(frame.extractPath).jpeg({ quality, mozjpeg: true }).toFile(destPath);
730
- outputFiles.push(join3(outputPath, fileName));
731
- framesMetadata.push({
732
- step: i + 1,
733
- fileName,
734
- frameId: frame.id + 1,
735
- timestampMs: Math.round(frame.timestamp * 1e3)
736
- });
737
- }
738
- const metadata = {
739
- video: {
740
- originalDurationMs: Math.round(
741
- (ctx.frames.length > 0 ? ctx.frames[ctx.frames.length - 1].timestamp : 0) * 1e3
742
- ),
743
- fps: ctx.options.fps,
744
- resolution: {
745
- width: ctx.options.scale,
746
- height: Math.round(ctx.options.scale * 9 / 16)
747
- }
748
- },
749
- frames: framesMetadata,
750
- animations: map3(ctx.animations || [], (anim) => ({
751
- ...anim,
752
- startFrameId: anim.startFrameId + 1,
753
- endFrameId: anim.endFrameId + 1,
754
- durationMs: Math.round(anim.durationMs)
755
- }))
756
- };
757
- const metadataPath = join3(stagingDir, ".metadata.json");
758
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
759
- outputFiles.push(join3(outputPath, ".metadata.json"));
760
- await ensureDir(join3(outputPath, ".."));
761
- await rm(outputPath, { recursive: true, force: true });
762
- await rename(stagingDir, outputPath);
763
- return outputFiles;
915
+ const stagingDir = join(ctx.workspacePath, "output");
916
+ const outputPath = ctx.options.outputPath;
917
+ const quality = ctx.options.quality;
918
+ const outputFiles = [];
919
+ const framesMetadata = [];
920
+ const totalFramesCount = ctx.frames.length;
921
+ const padding = Math.max(4, String(totalFramesCount).length);
922
+ for (let i = 0; i < selectedFrames.length; i++) {
923
+ const frame = selectedFrames[i];
924
+ const fileName = `frame_${String(frame.id + 1).padStart(padding, "0")}.jpg`;
925
+ const destPath = join(stagingDir, fileName);
926
+ await sharp(frame.extractPath).jpeg({
927
+ quality,
928
+ mozjpeg: true
929
+ }).toFile(destPath);
930
+ outputFiles.push(join(outputPath, fileName));
931
+ framesMetadata.push({
932
+ step: i + 1,
933
+ fileName,
934
+ frameId: frame.id + 1,
935
+ timestampMs: Math.round(frame.timestamp * 1e3)
936
+ });
937
+ }
938
+ const { video, animations } = await buildVideoMetadata(ctx, selectedFrames, ctx.analysisResolution);
939
+ const metadata = {
940
+ video,
941
+ frames: framesMetadata,
942
+ animations: map(animations, (anim) => ({
943
+ ...anim,
944
+ startFrameId: anim.startFrameId + 1,
945
+ endFrameId: anim.endFrameId + 1,
946
+ durationMs: Math.round(anim.durationMs)
947
+ }))
948
+ };
949
+ await writeFile(join(stagingDir, ".metadata.json"), JSON.stringify(metadata, null, 2));
950
+ outputFiles.push(join(outputPath, ".metadata.json"));
951
+ await ensureDir(join(outputPath, ".."));
952
+ await rm(outputPath, {
953
+ recursive: true,
954
+ force: true
955
+ });
956
+ await rename(stagingDir, outputPath);
957
+ return outputFiles;
764
958
  }
765
959
  async function createSegmentWorkspace(parentWorkspacePath, segmentIndex) {
766
- const segmentPath = join3(
767
- parentWorkspacePath,
768
- "segments",
769
- String(segmentIndex)
770
- );
771
- await ensureDir(join3(segmentPath, "frames"));
772
- return segmentPath;
960
+ const segmentPath = join(parentWorkspacePath, "segments", String(segmentIndex));
961
+ await ensureDir(join(segmentPath, "frames"));
962
+ return segmentPath;
773
963
  }
774
964
  async function cleanupWorkspace(workspacePath) {
775
- if (!workspacePath) return;
776
- try {
777
- await rm(workspacePath, { recursive: true, force: true });
778
- } catch {
779
- }
965
+ if (!workspacePath) return;
966
+ try {
967
+ await rm(workspacePath, {
968
+ recursive: true,
969
+ force: true
970
+ });
971
+ } catch {}
780
972
  }
781
- var STALE_THRESHOLD_MS = 60 * 60 * 1e3;
973
+ /**
974
+ * Write a video buffer to a temp file in the workspace and return the path.
975
+ * Used by 'buffer' input mode.
976
+ */
782
977
  async function writeInputBuffer(buffer, workspacePath) {
783
- const inputDir = join3(workspacePath, "input");
784
- await ensureDir(inputDir);
785
- const tempPath = join3(inputDir, "input.mp4");
786
- await writeFile(tempPath, buffer);
787
- return tempPath;
978
+ const inputDir = join(workspacePath, "input");
979
+ await ensureDir(inputDir);
980
+ const tempPath = join(inputDir, "input.mp4");
981
+ await writeFile(tempPath, buffer);
982
+ return tempPath;
788
983
  }
984
+ /**
985
+ * Write an array of frame Buffers as JPG files and return FrameNode[].
986
+ * Used by 'frames' input mode.
987
+ */
789
988
  async function writeInputFrames(frames, workspacePath) {
790
- const framesDir = join3(workspacePath, "frames");
791
- await ensureDir(framesDir);
792
- const frameNodes = [];
793
- for (let i = 0; i < frames.length; i++) {
794
- const filename = `frame_${String(i).padStart(6, "0")}${FRAME_OUTPUT_EXTENSION}`;
795
- const extractPath = join3(framesDir, filename);
796
- await writeFile(extractPath, frames[i]);
797
- frameNodes.push({ id: i, timestamp: i, extractPath });
798
- }
799
- return frameNodes;
989
+ const framesDir = join(workspacePath, "frames");
990
+ await ensureDir(framesDir);
991
+ const frameNodes = [];
992
+ for (let i = 0; i < frames.length; i++) {
993
+ const extractPath = join(framesDir, `frame_${String(i).padStart(6, "0")}${FRAME_OUTPUT_EXTENSION}`);
994
+ await writeFile(extractPath, frames[i]);
995
+ frameNodes.push({
996
+ id: i,
997
+ timestamp: i,
998
+ extractPath
999
+ });
1000
+ }
1001
+ return frameNodes;
800
1002
  }
1003
+ /**
1004
+ * Read selected FrameNode files as Buffers with JPEG compression.
1005
+ * Used to return output buffers in 'buffer' and 'frames' modes.
1006
+ */
801
1007
  async function readFramesAsBuffers(frameNodes, quality) {
802
- return Promise.all(
803
- map3(
804
- frameNodes,
805
- (f) => sharp2(f.extractPath).jpeg({ quality, mozjpeg: true }).toBuffer()
806
- )
807
- );
1008
+ return Promise.all(map(frameNodes, (f) => sharp(f.extractPath).jpeg({
1009
+ quality,
1010
+ mozjpeg: true
1011
+ }).toBuffer()));
808
1012
  }
809
1013
 
810
- // src/core/input-resolver.ts
811
- function resolveOptions(options2) {
812
- const mode = options2.mode;
813
- const inputPath = mode === "file" ? resolveAbsolute(options2.inputPath) : void 0;
814
- const outputPath = options2.outputPath ?? (inputPath ? deriveOutputPath(inputPath) : join4(process.cwd(), "scene-sieve-output"));
815
- const threshold = options2.threshold ?? DEFAULT_THRESHOLD;
816
- if (threshold <= 0 || threshold > 1) {
817
- throw new Error(
818
- `threshold must be in range (0, 1], received: ${threshold}`
819
- );
820
- }
821
- const pruneMode = "threshold-with-cap";
822
- return {
823
- mode,
824
- inputPath,
825
- count: options2.count ?? DEFAULT_COUNT,
826
- threshold,
827
- pruneMode,
828
- outputPath,
829
- fps: options2.fps ?? DEFAULT_FPS,
830
- maxFrames: options2.maxFrames ?? DEFAULT_MAX_FRAMES,
831
- scale: options2.scale ?? DEFAULT_SCALE,
832
- quality: options2.quality ?? DEFAULT_QUALITY,
833
- iouThreshold: options2.iouThreshold ?? IOU_THRESHOLD,
834
- animationThreshold: options2.animationThreshold ?? ANIMATION_FRAME_THRESHOLD,
835
- debug: options2.debug ?? false,
836
- maxSegmentDuration: options2.maxSegmentDuration ?? DEFAULT_MAX_SEGMENT_DURATION,
837
- concurrency: options2.concurrency ?? DEFAULT_SEGMENT_CONCURRENCY
838
- };
1014
+ //#endregion
1015
+ //#region src/core/input-resolver/input-resolver.ts
1016
+ /**
1017
+ * Validate supplied options and resolve defaults and paths for the pipeline.
1018
+ * @param options - Mode-specific input and optional numeric settings.
1019
+ * @returns Complete pipeline settings with absolute file input paths.
1020
+ * @throws An input error if a supplied numeric setting is invalid.
1021
+ */
1022
+ function resolveOptions(options) {
1023
+ validateOptions(options);
1024
+ const mode = options.mode;
1025
+ const inputPath = mode === "file" ? resolveAbsolute(options.inputPath) : void 0;
1026
+ const outputPath = options.outputPath ?? (inputPath ? deriveOutputPath(inputPath) : join(process.cwd(), "scene-sieve-output"));
1027
+ const threshold = options.threshold ?? .5;
1028
+ return {
1029
+ mode,
1030
+ inputPath,
1031
+ count: options.count ?? 20,
1032
+ threshold,
1033
+ pruneMode: "threshold-with-cap",
1034
+ outputPath,
1035
+ fps: options.fps ?? 5,
1036
+ maxFrames: options.maxFrames ?? 300,
1037
+ scale: options.scale ?? 720,
1038
+ quality: options.quality ?? 80,
1039
+ iouThreshold: options.iouThreshold ?? .9,
1040
+ animationThreshold: options.animationThreshold ?? 5,
1041
+ debug: options.debug ?? false,
1042
+ maxSegmentDuration: options.maxSegmentDuration ?? 300,
1043
+ concurrency: options.concurrency ?? 2
1044
+ };
839
1045
  }
840
- async function resolveInput(options2, workspacePath) {
841
- if (options2.mode === "file") {
842
- return {
843
- frames: [],
844
- resolvedInputPath: resolveAbsolute(options2.inputPath)
845
- };
846
- }
847
- if (options2.mode === "buffer") {
848
- const resolvedInputPath = await writeInputBuffer(
849
- options2.inputBuffer,
850
- workspacePath
851
- );
852
- return { frames: [], resolvedInputPath };
853
- }
854
- if (options2.mode === "frames") {
855
- const frames = await writeInputFrames(options2.inputFrames, workspacePath);
856
- return { frames };
857
- }
858
- throw new Error(`Unsupported input mode: ${options2.mode}`);
1046
+ /**
1047
+ * Resolve the input source to a list of FrameNode[].
1048
+ *
1049
+ * - 'file' mode: validate file exists and delegate to extractor (caller's responsibility)
1050
+ * - 'buffer' mode: write buffer as temp video file, return path via FrameNode trick (empty list)
1051
+ * - 'frames' mode: write frame buffers as JPGs, return FrameNode[]
1052
+ * @param options - Input source; encoded frames must have matching dimensions.
1053
+ * @param workspacePath - Workspace receiving temporary input files.
1054
+ * @returns Frame nodes or a resolved video path for extraction.
1055
+ * @throws Propagates metadata or write errors and rejects mismatched frame sizes.
1056
+ */
1057
+ async function resolveInput(options, workspacePath) {
1058
+ if (options.mode === "file") return {
1059
+ frames: [],
1060
+ resolvedInputPath: resolveAbsolute(options.inputPath)
1061
+ };
1062
+ if (options.mode === "buffer") return {
1063
+ frames: [],
1064
+ resolvedInputPath: await writeInputBuffer(options.inputBuffer, workspacePath)
1065
+ };
1066
+ if (options.mode === "frames") {
1067
+ let dimensions;
1068
+ for (const buffer of options.inputFrames) {
1069
+ const { width, height } = await sharp(buffer).metadata();
1070
+ if (dimensions && (width !== dimensions.width || height !== dimensions.height)) throw new Error(`inputFrames must be the same size (${dimensions.width}x${dimensions.height}), received: ${width}x${height}`);
1071
+ dimensions = {
1072
+ width,
1073
+ height
1074
+ };
1075
+ }
1076
+ return { frames: await writeInputFrames(options.inputFrames, workspacePath) };
1077
+ }
1078
+ throw new Error(`Unsupported input mode: ${options.mode}`);
859
1079
  }
860
1080
 
861
- // src/core/pruner.ts
862
- import { filter as filter4, map as map5 } from "@winglet/common-utils";
863
-
864
- // src/utils/math.ts
865
- import { filter as filter3, map as map4 } from "@winglet/common-utils";
1081
+ //#endregion
1082
+ //#region src/core/pruner/scoring/normalize-scores.ts
1083
+ const NORMALIZATION_ALPHA = .4;
1084
+ const NORMALIZATION_MAD_COEFFICIENT = 1.4826;
1085
+ const NORMALIZATION_MIN_SAMPLE_SIZE = 10;
1086
+ /**
1087
+ * Find the first position whose score is at least the requested value.
1088
+ * @param sorted - Finite positive scores sorted in ascending order.
1089
+ * @param value - A finite positive score present in sorted.
1090
+ * @returns The first matching rank, including the first position of any tie.
1091
+ */
1092
+ function lowerBound(sorted, value) {
1093
+ let low = 0;
1094
+ let high = sorted.length;
1095
+ while (low < high) {
1096
+ const mid = Math.floor((low + high) / 2);
1097
+ if (sorted[mid] < value) low = mid + 1;
1098
+ else high = mid;
1099
+ }
1100
+ return low;
1101
+ }
1102
+ /**
1103
+ * Normalize raw scores to [0, 1] range via Robust Hybrid Normalization.
1104
+ *
1105
+ * This model combines two mathematical approaches to provide a stable "relative" threshold:
1106
+ *
1107
+ * 1. Logistic-Robust-Z (Intensity):
1108
+ * Calculates Z-scores using Median and Median Absolute Deviation (MAD).
1109
+ * Maps these to a sigmoid (logistic) curve. This suppresses noise (scores near median)
1110
+ * and highlights significant signals (outliers) without letting extreme outliers
1111
+ * crush other meaningful transitions.
1112
+ *
1113
+ * 2. CDF / Percentile Rank (Relative Position):
1114
+ * Maps each score to its percentile rank in the sequence. This ensures that 't'
1115
+ * always has a consistent meaning as a "relative rank" regardless of absolute values.
1116
+ *
1117
+ * The final score is a weighted sum (NORMALIZATION_ALPHA) of both.
1118
+ *
1119
+ * @param items - Array of items with scores to normalize
1120
+ * @returns normalized scores array (same length as input)
1121
+ */
866
1122
  function normalizeScores(items) {
867
- if (items.length === 0) return [];
868
- const safeScores = map4(
869
- items,
870
- (e) => Number.isFinite(e.score) && e.score > 0 ? e.score : 0
871
- );
872
- const positiveScores = filter3(safeScores, (s) => s > 0);
873
- if (positiveScores.length === 0) return safeScores;
874
- const sorted = [...positiveScores].sort((a, b) => a - b);
875
- if (positiveScores.length <= NORMALIZATION_MIN_SAMPLE_SIZE) {
876
- const min = sorted[0];
877
- const max = sorted[sorted.length - 1];
878
- if (max === min) return map4(safeScores, (s) => s > 0 ? 1 : 0);
879
- return map4(
880
- safeScores,
881
- (s) => s <= 0 ? 0 : Math.max(0, Math.min((s - min) / (max - min), 1))
882
- );
883
- }
884
- const median = sorted[Math.floor(sorted.length / 2)];
885
- const absoluteDiffs = map4(positiveScores, (v) => Math.abs(v - median));
886
- const mad = [...absoluteDiffs].sort((a, b) => a - b)[Math.floor(absoluteDiffs.length / 2)];
887
- const scale = mad === 0 ? median : mad * NORMALIZATION_MAD_COEFFICIENT;
888
- const logisticZ = map4(safeScores, (s) => {
889
- if (s <= 0) return 0;
890
- if (scale === 0) return 1;
891
- const z = (s - median) / scale;
892
- return 1 / (1 + Math.exp(-NORMALIZATION_LOGISTIC_K * z));
893
- });
894
- const cdf = map4(safeScores, (s) => {
895
- if (s <= 0) return 0;
896
- const rank = sorted.findIndex((v) => v >= s);
897
- return rank / sorted.length;
898
- });
899
- return map4(
900
- logisticZ,
901
- (z, i) => z * (1 - NORMALIZATION_ALPHA) + cdf[i] * NORMALIZATION_ALPHA
902
- );
1123
+ if (items.length === 0) return [];
1124
+ const safeScores = map(items, (e) => Number.isFinite(e.score) && e.score > 0 ? e.score : 0);
1125
+ const positiveScores = filter(safeScores, (s) => s > 0);
1126
+ if (positiveScores.length === 0) return safeScores;
1127
+ const sorted = [...positiveScores].sort((a, b) => a - b);
1128
+ if (positiveScores.length <= 10) {
1129
+ const min = sorted[0];
1130
+ const max = sorted[sorted.length - 1];
1131
+ if (max === min) return map(safeScores, (s) => s > 0 ? 1 : 0);
1132
+ return map(safeScores, (s) => s <= 0 ? 0 : Math.max(0, Math.min((s - min) / (max - min), 1)));
1133
+ }
1134
+ const median = sorted[Math.floor(sorted.length / 2)];
1135
+ const absoluteDiffs = map(positiveScores, (v) => Math.abs(v - median));
1136
+ const mad = [...absoluteDiffs].sort((a, b) => a - b)[Math.floor(absoluteDiffs.length / 2)];
1137
+ const scale = mad === 0 ? median : mad * NORMALIZATION_MAD_COEFFICIENT;
1138
+ const logisticZ = map(safeScores, (s) => {
1139
+ if (s <= 0) return 0;
1140
+ if (scale === 0) return 1;
1141
+ const z = (s - median) / scale;
1142
+ return 1 / (1 + Math.exp(-3 * z));
1143
+ });
1144
+ const cdf = map(safeScores, (s) => {
1145
+ if (s <= 0) return 0;
1146
+ return lowerBound(sorted, s) / sorted.length;
1147
+ });
1148
+ return map(logisticZ, (z, i) => z * (1 - NORMALIZATION_ALPHA) + cdf[i] * NORMALIZATION_ALPHA);
903
1149
  }
904
1150
 
905
- // src/utils/min-heap.ts
1151
+ //#endregion
1152
+ //#region src/core/pruner/heap/min-heap.ts
1153
+ /**
1154
+ * Generic binary min-heap.
1155
+ *
1156
+ * Elements are ordered by a numeric `score` field.
1157
+ * push/pop: O(log N), size: O(1).
1158
+ */
906
1159
  var MinHeap = class {
907
- h = [];
908
- get size() {
909
- return this.h.length;
910
- }
911
- push(entry) {
912
- this.h.push(entry);
913
- this.siftUp(this.h.length - 1);
914
- }
915
- pop() {
916
- const n = this.h.length;
917
- if (n === 0) return void 0;
918
- const top = this.h[0];
919
- const last = this.h.pop();
920
- if (n > 1) {
921
- this.h[0] = last;
922
- this.siftDown(0);
923
- }
924
- return top;
925
- }
926
- siftUp(i) {
927
- while (i > 0) {
928
- const p = i - 1 >> 1;
929
- if (this.h[p].score <= this.h[i].score) break;
930
- [this.h[p], this.h[i]] = [this.h[i], this.h[p]];
931
- i = p;
932
- }
933
- }
934
- siftDown(i) {
935
- const n = this.h.length;
936
- for (; ; ) {
937
- let m = i;
938
- const l = 2 * i + 1;
939
- const r = 2 * i + 2;
940
- if (l < n && this.h[l].score < this.h[m].score) m = l;
941
- if (r < n && this.h[r].score < this.h[m].score) m = r;
942
- if (m === i) break;
943
- [this.h[m], this.h[i]] = [this.h[i], this.h[m]];
944
- i = m;
945
- }
946
- }
1160
+ h = [];
1161
+ get size() {
1162
+ return this.h.length;
1163
+ }
1164
+ push(entry) {
1165
+ this.h.push(entry);
1166
+ this.siftUp(this.h.length - 1);
1167
+ }
1168
+ pop() {
1169
+ const n = this.h.length;
1170
+ if (n === 0) return void 0;
1171
+ const top = this.h[0];
1172
+ const last = this.h.pop();
1173
+ if (n > 1) {
1174
+ this.h[0] = last;
1175
+ this.siftDown(0);
1176
+ }
1177
+ return top;
1178
+ }
1179
+ siftUp(i) {
1180
+ while (i > 0) {
1181
+ const p = i - 1 >> 1;
1182
+ if (this.h[p].score <= this.h[i].score) break;
1183
+ [this.h[p], this.h[i]] = [this.h[i], this.h[p]];
1184
+ i = p;
1185
+ }
1186
+ }
1187
+ siftDown(i) {
1188
+ const n = this.h.length;
1189
+ for (;;) {
1190
+ let m = i;
1191
+ const l = 2 * i + 1;
1192
+ const r = 2 * i + 2;
1193
+ if (l < n && this.h[l].score < this.h[m].score) m = l;
1194
+ if (r < n && this.h[r].score < this.h[m].score) m = r;
1195
+ if (m === i) break;
1196
+ [this.h[m], this.h[i]] = [this.h[i], this.h[m]];
1197
+ i = m;
1198
+ }
1199
+ }
947
1200
  };
948
1201
 
949
- // src/core/pruner.ts
1202
+ //#endregion
1203
+ //#region src/core/pruner/pruner.ts
1204
+ /**
1205
+ * Edge-aware greedy merge with re-linking — O(N log N).
1206
+ *
1207
+ * 1. Build a doubly-linked list of frames
1208
+ * 2. Insert all edges into a min-heap
1209
+ * 3. Pop the lowest-score edge (most similar pair)
1210
+ * 4. Remove the later frame (tgtId), re-link neighbors
1211
+ * 5. Push synthetic edge with score = max(left, right)
1212
+ * 6. Repeat until surviving count === targetCount
1213
+ * 7. First and last frames are never removed (boundary preservation)
1214
+ *
1215
+ * Stale heap entries (involving removed frames) are lazily skipped on pop.
1216
+ */
950
1217
  function pruneTo(graph, frames, targetCount) {
951
- if (frames.length <= targetCount) {
952
- return new Set(map5(frames, (f) => f.id));
953
- }
954
- const prev = /* @__PURE__ */ new Map();
955
- const next = /* @__PURE__ */ new Map();
956
- for (let i = 0; i < frames.length; i++) {
957
- if (i > 0) prev.set(frames[i].id, frames[i - 1].id);
958
- if (i < frames.length - 1) next.set(frames[i].id, frames[i + 1].id);
959
- }
960
- const edgeScore = /* @__PURE__ */ new Map();
961
- const heap = new MinHeap();
962
- for (const edge of graph) {
963
- edgeScore.set(`${edge.sourceId}:${edge.targetId}`, edge.score);
964
- heap.push({
965
- score: edge.score,
966
- srcId: edge.sourceId,
967
- tgtId: edge.targetId
968
- });
969
- }
970
- const surviving = new Set(map5(frames, (f) => f.id));
971
- const firstId = frames[0].id;
972
- const lastId = frames[frames.length - 1].id;
973
- while (surviving.size > targetCount && heap.size > 0) {
974
- const entry = heap.pop();
975
- if (!surviving.has(entry.srcId) || !surviving.has(entry.tgtId)) continue;
976
- const key = `${entry.srcId}:${entry.tgtId}`;
977
- if (edgeScore.get(key) !== entry.score) continue;
978
- if (entry.tgtId === firstId || entry.tgtId === lastId) continue;
979
- surviving.delete(entry.tgtId);
980
- edgeScore.delete(key);
981
- const tgtNext = next.get(entry.tgtId);
982
- if (tgtNext !== void 0) {
983
- const rightKey = `${entry.tgtId}:${tgtNext}`;
984
- const rightScore = edgeScore.get(rightKey) ?? 0;
985
- edgeScore.delete(rightKey);
986
- const newScore = Math.max(entry.score, rightScore);
987
- edgeScore.set(`${entry.srcId}:${tgtNext}`, newScore);
988
- heap.push({ score: newScore, srcId: entry.srcId, tgtId: tgtNext });
989
- next.set(entry.srcId, tgtNext);
990
- prev.set(tgtNext, entry.srcId);
991
- } else {
992
- next.delete(entry.srcId);
993
- }
994
- prev.delete(entry.tgtId);
995
- next.delete(entry.tgtId);
996
- }
997
- return surviving;
1218
+ if (frames.length <= targetCount) return new Set(map(frames, (f) => f.id));
1219
+ const prev = /* @__PURE__ */ new Map();
1220
+ const next = /* @__PURE__ */ new Map();
1221
+ for (let i = 0; i < frames.length; i++) {
1222
+ if (i > 0) prev.set(frames[i].id, frames[i - 1].id);
1223
+ if (i < frames.length - 1) next.set(frames[i].id, frames[i + 1].id);
1224
+ }
1225
+ const edgeScore = /* @__PURE__ */ new Map();
1226
+ const heap = new MinHeap();
1227
+ for (const edge of graph) {
1228
+ edgeScore.set(`${edge.sourceId}:${edge.targetId}`, edge.score);
1229
+ heap.push({
1230
+ score: edge.score,
1231
+ srcId: edge.sourceId,
1232
+ tgtId: edge.targetId
1233
+ });
1234
+ }
1235
+ const surviving = new Set(map(frames, (f) => f.id));
1236
+ const firstId = frames[0].id;
1237
+ const lastId = frames[frames.length - 1].id;
1238
+ while (surviving.size > targetCount && heap.size > 0) {
1239
+ const entry = heap.pop();
1240
+ if (!surviving.has(entry.srcId) || !surviving.has(entry.tgtId)) continue;
1241
+ const key = `${entry.srcId}:${entry.tgtId}`;
1242
+ if (edgeScore.get(key) !== entry.score) continue;
1243
+ if (entry.tgtId === firstId || entry.tgtId === lastId) continue;
1244
+ surviving.delete(entry.tgtId);
1245
+ edgeScore.delete(key);
1246
+ const tgtNext = next.get(entry.tgtId);
1247
+ if (tgtNext !== void 0) {
1248
+ const rightKey = `${entry.tgtId}:${tgtNext}`;
1249
+ const rightScore = edgeScore.get(rightKey) ?? 0;
1250
+ edgeScore.delete(rightKey);
1251
+ const newScore = Math.max(entry.score, rightScore);
1252
+ edgeScore.set(`${entry.srcId}:${tgtNext}`, newScore);
1253
+ heap.push({
1254
+ score: newScore,
1255
+ srcId: entry.srcId,
1256
+ tgtId: tgtNext
1257
+ });
1258
+ next.set(entry.srcId, tgtNext);
1259
+ prev.set(tgtNext, entry.srcId);
1260
+ } else next.delete(entry.srcId);
1261
+ prev.delete(entry.tgtId);
1262
+ next.delete(entry.tgtId);
1263
+ }
1264
+ return surviving;
998
1265
  }
1266
+ /**
1267
+ * Non-Maximum Suppression (NMS) for consecutive edge runs.
1268
+ *
1269
+ * Consecutive edges share overlapping frames (edge i: frame i->i+1,
1270
+ * edge i+1: frame i+1->i+2), so consecutive passing edges indicate
1271
+ * the same visual transition region. This function groups consecutive
1272
+ * passing edge indices into "runs" and keeps all distinct peaks per run.
1273
+ *
1274
+ * Multi-peak detection: within each run, strict local maxima (score higher
1275
+ * than both neighbors) are identified. Each local maximum represents a
1276
+ * distinct visual transition. If no strict local maxima exist (plateau or
1277
+ * monotonic sequence), the global peak of the run is selected as fallback.
1278
+ *
1279
+ * Single-element runs are unaffected (isolated transitions preserved).
1280
+ *
1281
+ * @param graph - full ScoreEdge array (for targetId lookup)
1282
+ * @param passingIndices - edge indices that passed threshold filtering (sorted ascending)
1283
+ * @param normalizedScores - normalized score array (same length as graph)
1284
+ * @returns Set of targetIds to add to surviving set (one or more per run)
1285
+ */
999
1286
  function suppressConsecutiveRuns(graph, passingIndices, normalizedScores) {
1000
- const result = /* @__PURE__ */ new Set();
1001
- let runStart = 0;
1002
- while (runStart < passingIndices.length) {
1003
- let runEnd = runStart;
1004
- while (runEnd + 1 < passingIndices.length && passingIndices[runEnd + 1] === passingIndices[runEnd] + 1) {
1005
- runEnd++;
1006
- }
1007
- const runLen = runEnd - runStart + 1;
1008
- if (runLen === 1) {
1009
- result.add(graph[passingIndices[runStart]].targetId);
1010
- } else {
1011
- const peaks = [];
1012
- for (let j = runStart; j <= runEnd; j++) {
1013
- const idx = passingIndices[j];
1014
- const score = normalizedScores[idx];
1015
- const prevScore = j > runStart ? normalizedScores[passingIndices[j - 1]] : -Infinity;
1016
- const nextScore = j < runEnd ? normalizedScores[passingIndices[j + 1]] : -Infinity;
1017
- if (score > prevScore && score > nextScore) {
1018
- peaks.push(idx);
1019
- }
1020
- }
1021
- if (peaks.length > 0) {
1022
- for (const peakIdx of peaks) {
1023
- result.add(graph[peakIdx].targetId);
1024
- }
1025
- } else {
1026
- let peakIdx = passingIndices[runStart];
1027
- for (let j = runStart + 1; j <= runEnd; j++) {
1028
- const idx = passingIndices[j];
1029
- if (normalizedScores[idx] > normalizedScores[peakIdx]) {
1030
- peakIdx = idx;
1031
- }
1032
- }
1033
- result.add(graph[peakIdx].targetId);
1034
- }
1035
- }
1036
- runStart = runEnd + 1;
1037
- }
1038
- return result;
1287
+ const result = /* @__PURE__ */ new Set();
1288
+ let runStart = 0;
1289
+ while (runStart < passingIndices.length) {
1290
+ let runEnd = runStart;
1291
+ while (runEnd + 1 < passingIndices.length && passingIndices[runEnd + 1] === passingIndices[runEnd] + 1) runEnd++;
1292
+ if (runEnd - runStart + 1 === 1) result.add(graph[passingIndices[runStart]].targetId);
1293
+ else {
1294
+ const peaks = [];
1295
+ for (let j = runStart; j <= runEnd; j++) {
1296
+ const idx = passingIndices[j];
1297
+ const score = normalizedScores[idx];
1298
+ const prevScore = j > runStart ? normalizedScores[passingIndices[j - 1]] : -Infinity;
1299
+ const nextScore = j < runEnd ? normalizedScores[passingIndices[j + 1]] : -Infinity;
1300
+ if (score > prevScore && score > nextScore) peaks.push(idx);
1301
+ }
1302
+ if (peaks.length > 0) for (const peakIdx of peaks) result.add(graph[peakIdx].targetId);
1303
+ else {
1304
+ let peakIdx = passingIndices[runStart];
1305
+ for (let j = runStart + 1; j <= runEnd; j++) {
1306
+ const idx = passingIndices[j];
1307
+ if (normalizedScores[idx] > normalizedScores[peakIdx]) peakIdx = idx;
1308
+ }
1309
+ result.add(graph[peakIdx].targetId);
1310
+ }
1311
+ }
1312
+ runStart = runEnd + 1;
1313
+ }
1314
+ return result;
1039
1315
  }
1316
+ /**
1317
+ * Threshold-based pruning with NMS -- including normalization, O(N log N).
1318
+ *
1319
+ * 1. Scores are normalized to [0, 1] via percentile normalization.
1320
+ * 2. Edges with normalized score >= threshold are collected.
1321
+ * 3. Non-Maximum Suppression groups consecutive passing edges and keeps
1322
+ * only the peak per run, preventing near-duplicate frame selection
1323
+ * from a single visual transition.
1324
+ *
1325
+ * First and last frames are always preserved (boundary protection).
1326
+ */
1040
1327
  function pruneByThreshold(graph, frames, threshold) {
1041
- if (frames.length === 0) return /* @__PURE__ */ new Set();
1042
- const surviving = /* @__PURE__ */ new Set();
1043
- surviving.add(frames[0].id);
1044
- surviving.add(frames[frames.length - 1].id);
1045
- const normalized = normalizeScores(graph);
1046
- const passingIndices = [];
1047
- for (let i = 0; i < graph.length; i++) {
1048
- if (normalized[i] >= threshold) {
1049
- passingIndices.push(i);
1050
- }
1051
- }
1052
- const nmsTargets = suppressConsecutiveRuns(graph, passingIndices, normalized);
1053
- for (const id of nmsTargets) {
1054
- surviving.add(id);
1055
- }
1056
- return surviving;
1328
+ if (frames.length === 0) return /* @__PURE__ */ new Set();
1329
+ const surviving = /* @__PURE__ */ new Set();
1330
+ surviving.add(frames[0].id);
1331
+ surviving.add(frames[frames.length - 1].id);
1332
+ const normalized = normalizeScores(graph);
1333
+ const passingIndices = [];
1334
+ for (let i = 0; i < graph.length; i++) if (normalized[i] >= threshold) passingIndices.push(i);
1335
+ const nmsTargets = suppressConsecutiveRuns(graph, passingIndices, normalized);
1336
+ for (const id of nmsTargets) surviving.add(id);
1337
+ return surviving;
1057
1338
  }
1339
+ /**
1340
+ * Combined threshold + count pruning -- 2-stage pipeline.
1341
+ *
1342
+ * Stage 1: pruneByThreshold -- keep all frames with normalized score >= threshold
1343
+ * Stage 2: if result exceeds maxCount, rebuild subgraph with synthetic edges
1344
+ * (min-score over each gap) and apply pruneTo on the surviving subset
1345
+ *
1346
+ * Edge reconstruction: for consecutive survivors A, B with removed frames
1347
+ * [x1, x2, ...] between them, the synthetic edge score is:
1348
+ * min(score(A->x1), score(x1->x2), ..., score(xN->B))
1349
+ * This preserves the "weakest link" semantics.
1350
+ */
1058
1351
  function pruneByThresholdWithCap(graph, frames, threshold, maxCount) {
1059
- const thresholdSurvivors = pruneByThreshold(graph, frames, threshold);
1060
- if (thresholdSurvivors.size <= maxCount) {
1061
- return thresholdSurvivors;
1062
- }
1063
- const survivingFrames = filter4(frames, (f) => thresholdSurvivors.has(f.id));
1064
- const idToOrigIdx = /* @__PURE__ */ new Map();
1065
- for (let i = 0; i < frames.length; i++) {
1066
- idToOrigIdx.set(frames[i].id, i);
1067
- }
1068
- const edgeLookup = /* @__PURE__ */ new Map();
1069
- for (const e of graph) {
1070
- edgeLookup.set(`${e.sourceId}:${e.targetId}`, e.score);
1071
- }
1072
- const syntheticEdges = [];
1073
- for (let i = 0; i < survivingFrames.length - 1; i++) {
1074
- const srcSurvivor = survivingFrames[i];
1075
- const tgtSurvivor = survivingFrames[i + 1];
1076
- const srcOrigIdx = idToOrigIdx.get(srcSurvivor.id);
1077
- const tgtOrigIdx = idToOrigIdx.get(tgtSurvivor.id);
1078
- let minScore = Infinity;
1079
- for (let j = srcOrigIdx; j < tgtOrigIdx; j++) {
1080
- const fromId = frames[j].id;
1081
- const toId = frames[j + 1].id;
1082
- const score = edgeLookup.get(`${fromId}:${toId}`) ?? 0;
1083
- if (score < minScore) {
1084
- minScore = score;
1085
- }
1086
- }
1087
- syntheticEdges.push({
1088
- sourceId: srcSurvivor.id,
1089
- targetId: tgtSurvivor.id,
1090
- score: minScore === Infinity ? 0 : minScore
1091
- });
1092
- }
1093
- return pruneTo(syntheticEdges, survivingFrames, maxCount);
1352
+ const thresholdSurvivors = pruneByThreshold(graph, frames, threshold);
1353
+ if (thresholdSurvivors.size <= maxCount) return thresholdSurvivors;
1354
+ const survivingFrames = filter(frames, (f) => thresholdSurvivors.has(f.id));
1355
+ const idToOrigIdx = /* @__PURE__ */ new Map();
1356
+ for (let i = 0; i < frames.length; i++) idToOrigIdx.set(frames[i].id, i);
1357
+ const edgeLookup = /* @__PURE__ */ new Map();
1358
+ for (const e of graph) edgeLookup.set(`${e.sourceId}:${e.targetId}`, e.score);
1359
+ const syntheticEdges = [];
1360
+ for (let i = 0; i < survivingFrames.length - 1; i++) {
1361
+ const srcSurvivor = survivingFrames[i];
1362
+ const tgtSurvivor = survivingFrames[i + 1];
1363
+ const srcOrigIdx = idToOrigIdx.get(srcSurvivor.id);
1364
+ const tgtOrigIdx = idToOrigIdx.get(tgtSurvivor.id);
1365
+ let minScore = Infinity;
1366
+ for (let j = srcOrigIdx; j < tgtOrigIdx; j++) {
1367
+ const fromId = frames[j].id;
1368
+ const toId = frames[j + 1].id;
1369
+ const score = edgeLookup.get(`${fromId}:${toId}`) ?? 0;
1370
+ if (score < minScore) minScore = score;
1371
+ }
1372
+ syntheticEdges.push({
1373
+ sourceId: srcSurvivor.id,
1374
+ targetId: tgtSurvivor.id,
1375
+ score: minScore === Infinity ? 0 : minScore
1376
+ });
1377
+ }
1378
+ return pruneTo(syntheticEdges, survivingFrames, maxCount);
1094
1379
  }
1095
1380
 
1096
- // src/core/segmenter.ts
1097
- import { randomUUID } from "crypto";
1098
- import { join as join5 } from "path";
1099
- import { filter as filter5, map as map6 } from "@winglet/common-utils";
1100
-
1101
- // src/utils/concurrency.ts
1381
+ //#endregion
1382
+ //#region src/core/segmenter/scheduling/concurrency.ts
1383
+ /**
1384
+ * Creates a concurrency limiter that runs at most `limit` tasks in parallel.
1385
+ * Lightweight replacement for p-limit to avoid external dependency.
1386
+ */
1102
1387
  function concurrencyLimit(limit) {
1103
- limit = Math.max(1, limit);
1104
- let active = 0;
1105
- const queue = [];
1106
- return async (fn) => {
1107
- while (active >= limit) {
1108
- await new Promise((resolve2) => queue.push(resolve2));
1109
- }
1110
- active++;
1111
- try {
1112
- return await fn();
1113
- } finally {
1114
- active--;
1115
- queue.shift()?.();
1116
- }
1117
- };
1388
+ limit = Math.max(1, limit);
1389
+ let active = 0;
1390
+ const queue = [];
1391
+ return async (fn) => {
1392
+ while (active >= limit) await new Promise((resolve) => queue.push(resolve));
1393
+ active++;
1394
+ try {
1395
+ return await fn();
1396
+ } finally {
1397
+ active--;
1398
+ queue.shift()?.();
1399
+ }
1400
+ };
1118
1401
  }
1119
1402
 
1120
- // src/core/segmenter.ts
1403
+ //#endregion
1404
+ //#region src/core/segmenter/segmenter.ts
1405
+ /**
1406
+ * Determine whether segmentation should be used.
1407
+ * Returns false for frames mode and GIF files.
1408
+ * Actual duration check happens inside runSegmentedPipeline after metadata fetch.
1409
+ */
1121
1410
  function shouldSegment(resolvedOptions, originalOptions) {
1122
- if (resolvedOptions.mode === "frames") return false;
1123
- if (originalOptions.mode === "file") {
1124
- if (originalOptions.inputPath.toLowerCase().endsWith(".gif")) return false;
1125
- }
1126
- return true;
1411
+ if (resolvedOptions.mode === "frames") return false;
1412
+ if (originalOptions.mode === "file") {
1413
+ if (originalOptions.inputPath.toLowerCase().endsWith(".gif")) return false;
1414
+ }
1415
+ return true;
1127
1416
  }
1417
+ /**
1418
+ * Partition the global extraction grid into nonempty logical segments.
1419
+ * @param totalDuration Positive source duration in seconds.
1420
+ * @param maxSegmentDuration Positive logical segment width in seconds.
1421
+ * @param maxFrames Candidate budget, defensively raised to at least two.
1422
+ * @param fps Positive requested sampling frequency.
1423
+ * @returns Contiguous plan indices with grid-aligned seeks and overlap-inclusive limits.
1424
+ */
1128
1425
  function computeSegmentPlan(totalDuration, maxSegmentDuration, maxFrames, fps) {
1129
- const effectiveFps = Math.max(0.5, Math.min(fps, maxFrames / totalDuration));
1130
- if (totalDuration <= maxSegmentDuration) {
1131
- return [
1132
- {
1133
- index: 0,
1134
- startTime: 0,
1135
- endTime: totalDuration,
1136
- duration: totalDuration,
1137
- allocatedFrames: Math.min(
1138
- Math.ceil(effectiveFps * totalDuration),
1139
- maxFrames
1140
- ),
1141
- effectiveFps,
1142
- overlapBefore: 0,
1143
- overlapAfter: 0,
1144
- extractStartTime: 0,
1145
- extractDuration: totalDuration
1146
- }
1147
- ];
1148
- }
1149
- const segmentCount = Math.ceil(totalDuration / maxSegmentDuration);
1150
- const overlapTime = 1 / effectiveFps;
1151
- const segments = [];
1152
- for (let i = 0; i < segmentCount; i++) {
1153
- const startTime = i * maxSegmentDuration;
1154
- const endTime = Math.min((i + 1) * maxSegmentDuration, totalDuration);
1155
- const duration = endTime - startTime;
1156
- const overlapBefore = i > 0 ? 1 : 0;
1157
- const overlapAfter = i < segmentCount - 1 ? 1 : 0;
1158
- const extractStartTime = Math.max(
1159
- 0,
1160
- startTime - overlapBefore * overlapTime
1161
- );
1162
- const extractEndTime = Math.min(
1163
- totalDuration,
1164
- endTime + overlapAfter * overlapTime
1165
- );
1166
- const extractDuration = extractEndTime - extractStartTime;
1167
- segments.push({
1168
- index: i,
1169
- startTime,
1170
- endTime,
1171
- duration,
1172
- allocatedFrames: Math.ceil(effectiveFps * duration),
1173
- effectiveFps,
1174
- overlapBefore,
1175
- overlapAfter,
1176
- extractStartTime,
1177
- extractDuration
1178
- });
1179
- }
1180
- const totalAllocated = segments.reduce(
1181
- (sum, s) => sum + s.allocatedFrames,
1182
- 0
1183
- );
1184
- if (totalAllocated > maxFrames) {
1185
- segments[segments.length - 1].allocatedFrames -= totalAllocated - maxFrames;
1186
- }
1187
- return segments;
1426
+ const frameLimit = Math.max(2, maxFrames);
1427
+ const effectiveFps = Math.min(fps, frameLimit / totalDuration);
1428
+ if (totalDuration <= maxSegmentDuration) return [{
1429
+ index: 0,
1430
+ startTime: 0,
1431
+ endTime: totalDuration,
1432
+ duration: totalDuration,
1433
+ allocatedFrames: frameLimit,
1434
+ effectiveFps,
1435
+ overlapBefore: 0,
1436
+ overlapAfter: 0,
1437
+ extractStartTime: 0,
1438
+ extractDuration: totalDuration
1439
+ }];
1440
+ const segments = [];
1441
+ for (let slot = 0; slot < frameLimit; slot++) {
1442
+ const timestamp = slot / effectiveFps;
1443
+ if (timestamp >= totalDuration) break;
1444
+ const startTime = Math.floor(timestamp / maxSegmentDuration) * maxSegmentDuration;
1445
+ const previous = segments[segments.length - 1];
1446
+ if (previous?.startTime === startTime) {
1447
+ previous.allocatedFrames++;
1448
+ continue;
1449
+ }
1450
+ const endTime = Math.min(startTime + maxSegmentDuration, totalDuration);
1451
+ segments.push({
1452
+ index: segments.length,
1453
+ startTime,
1454
+ endTime,
1455
+ duration: endTime - startTime,
1456
+ allocatedFrames: 1,
1457
+ effectiveFps,
1458
+ overlapBefore: 0,
1459
+ overlapAfter: 0,
1460
+ extractStartTime: timestamp,
1461
+ extractDuration: 0
1462
+ });
1463
+ }
1464
+ let firstSlot = 0;
1465
+ for (const segment of segments) {
1466
+ const nextSlot = firstSlot + segment.allocatedFrames;
1467
+ segment.overlapBefore = segment.index > 0 ? 1 : 0;
1468
+ segment.overlapAfter = segment.index < segments.length - 1 ? 1 : 0;
1469
+ segment.extractStartTime = (firstSlot - segment.overlapBefore) / effectiveFps;
1470
+ segment.extractDuration = (segment.overlapAfter ? Math.min(totalDuration, (nextSlot + 1) / effectiveFps) : totalDuration) - segment.extractStartTime;
1471
+ segment.allocatedFrames += segment.overlapBefore + segment.overlapAfter;
1472
+ firstSlot = nextSlot;
1473
+ }
1474
+ return segments;
1188
1475
  }
1476
+ /**
1477
+ * Collect all frames from every segment, adjusting timestamps by extractStartTime.
1478
+ */
1189
1479
  function collectAllFrames(segmentResults) {
1190
- const allFrames = [];
1191
- for (const result of segmentResults) {
1192
- for (const frame of result.frames) {
1193
- allFrames.push({
1194
- frame: {
1195
- ...frame,
1196
- // Use extractStartTime for timestamp correction (Section 18 note 1)
1197
- timestamp: frame.timestamp + result.segment.extractStartTime
1198
- },
1199
- segmentIndex: result.segment.index,
1200
- localId: frame.id
1201
- });
1202
- }
1203
- }
1204
- return allFrames;
1480
+ const allFrames = [];
1481
+ for (const result of segmentResults) for (const frame of result.frames) allFrames.push({
1482
+ frame: {
1483
+ ...frame,
1484
+ timestamp: frame.timestamp + result.segment.extractStartTime
1485
+ },
1486
+ segmentIndex: result.segment.index,
1487
+ localId: frame.id
1488
+ });
1489
+ return allFrames;
1205
1490
  }
1491
+ /**
1492
+ * Sort frames in place and alias overlap duplicates to the first survivor.
1493
+ * @param frames Collected entries whose segment index and local ID identify a frame.
1494
+ * @param effectiveFps Positive sampling frequency; half a frame interval is the threshold.
1495
+ * @returns Timestamp-ordered survivors and duplicate keys pointing directly to survivor keys.
1496
+ */
1206
1497
  function deduplicateFrames(frames, effectiveFps) {
1207
- frames.sort((a, b) => a.frame.timestamp - b.frame.timestamp);
1208
- const dupThreshold = 1 / (effectiveFps * 2);
1209
- const unique = [];
1210
- for (const entry of frames) {
1211
- if (unique.length > 0) {
1212
- const last = unique[unique.length - 1];
1213
- if (Math.abs(entry.frame.timestamp - last.frame.timestamp) < dupThreshold) {
1214
- continue;
1215
- }
1216
- }
1217
- unique.push(entry);
1218
- }
1219
- return unique;
1498
+ frames.sort((a, b) => a.frame.timestamp - b.frame.timestamp);
1499
+ const dupThreshold = 1 / (effectiveFps * 2);
1500
+ const unique = [];
1501
+ const aliases = /* @__PURE__ */ new Map();
1502
+ for (const entry of frames) {
1503
+ if (unique.length > 0) {
1504
+ const last = unique[unique.length - 1];
1505
+ if (Math.abs(entry.frame.timestamp - last.frame.timestamp) < dupThreshold) {
1506
+ aliases.set(`${entry.segmentIndex}:${entry.localId}`, `${last.segmentIndex}:${last.localId}`);
1507
+ continue;
1508
+ }
1509
+ }
1510
+ unique.push(entry);
1511
+ }
1512
+ return {
1513
+ unique,
1514
+ aliases
1515
+ };
1220
1516
  }
1221
- function remapFrameIds(uniqueFrames) {
1222
- const globalIdMap = /* @__PURE__ */ new Map();
1223
- const frames = uniqueFrames.map((entry, globalId) => {
1224
- globalIdMap.set(`${entry.segmentIndex}:${entry.localId}`, globalId);
1225
- return {
1226
- id: globalId,
1227
- timestamp: entry.frame.timestamp,
1228
- extractPath: entry.frame.extractPath
1229
- };
1230
- });
1231
- return { frames, globalIdMap };
1517
+ /**
1518
+ * Assign sequential global IDs and retain duplicate local IDs as aliases.
1519
+ * @param uniqueFrames Timestamp-ordered survivors with distinct segment/local keys.
1520
+ * @param aliases Duplicate keys pointing directly to keys in uniqueFrames.
1521
+ * @returns Remapped frames and a global ID lookup covering survivors and duplicates.
1522
+ */
1523
+ function remapFrameIds(uniqueFrames, aliases) {
1524
+ const globalIdMap = /* @__PURE__ */ new Map();
1525
+ const frames = uniqueFrames.map((entry, globalId) => {
1526
+ globalIdMap.set(`${entry.segmentIndex}:${entry.localId}`, globalId);
1527
+ return {
1528
+ id: globalId,
1529
+ timestamp: entry.frame.timestamp,
1530
+ extractPath: entry.frame.extractPath
1531
+ };
1532
+ });
1533
+ for (const [alias, survivor] of aliases) globalIdMap.set(alias, globalIdMap.get(survivor));
1534
+ return {
1535
+ frames,
1536
+ globalIdMap
1537
+ };
1232
1538
  }
1539
+ /**
1540
+ * Remap edges, dropping missing endpoints and self loops while keeping the highest pair score.
1541
+ * @param segmentResults Segment-local edges in encounter order.
1542
+ * @param globalIdMap Survivor and duplicate local keys mapped to global IDs.
1543
+ * @returns One edge per surviving directed pair without changing its score.
1544
+ */
1233
1545
  function remapEdges(segmentResults, globalIdMap) {
1234
- const edges = [];
1235
- const edgeMap = /* @__PURE__ */ new Map();
1236
- for (const result of segmentResults) {
1237
- for (const edge of result.edges) {
1238
- const newSourceId = globalIdMap.get(
1239
- `${result.segment.index}:${edge.sourceId}`
1240
- );
1241
- const newTargetId = globalIdMap.get(
1242
- `${result.segment.index}:${edge.targetId}`
1243
- );
1244
- if (newSourceId === void 0 || newTargetId === void 0) continue;
1245
- const edgeKey = `${newSourceId}-${newTargetId}`;
1246
- const existingIdx = edgeMap.get(edgeKey);
1247
- if (existingIdx !== void 0) {
1248
- if (edges[existingIdx].score < edge.score) {
1249
- edges[existingIdx] = {
1250
- sourceId: newSourceId,
1251
- targetId: newTargetId,
1252
- score: edge.score
1253
- };
1254
- }
1255
- } else {
1256
- edgeMap.set(edgeKey, edges.length);
1257
- edges.push({
1258
- sourceId: newSourceId,
1259
- targetId: newTargetId,
1260
- score: edge.score
1261
- });
1262
- }
1263
- }
1264
- }
1265
- return edges;
1546
+ const edges = [];
1547
+ const edgeMap = /* @__PURE__ */ new Map();
1548
+ for (const result of segmentResults) for (const edge of result.edges) {
1549
+ const newSourceId = globalIdMap.get(`${result.segment.index}:${edge.sourceId}`);
1550
+ const newTargetId = globalIdMap.get(`${result.segment.index}:${edge.targetId}`);
1551
+ if (newSourceId === void 0 || newTargetId === void 0) continue;
1552
+ if (newSourceId === newTargetId) continue;
1553
+ const edgeKey = `${newSourceId}-${newTargetId}`;
1554
+ const existingIdx = edgeMap.get(edgeKey);
1555
+ if (existingIdx !== void 0) {
1556
+ if (edges[existingIdx].score < edge.score) edges[existingIdx] = {
1557
+ sourceId: newSourceId,
1558
+ targetId: newTargetId,
1559
+ score: edge.score
1560
+ };
1561
+ } else {
1562
+ edgeMap.set(edgeKey, edges.length);
1563
+ edges.push({
1564
+ sourceId: newSourceId,
1565
+ targetId: newTargetId,
1566
+ score: edge.score
1567
+ });
1568
+ }
1569
+ }
1570
+ return edges;
1266
1571
  }
1572
+ /**
1573
+ * Remap animations, dropping missing or collapsed endpoints and retaining the first pair entry.
1574
+ * @param segmentResults Segment-local tracker entries in encounter order.
1575
+ * @param globalIdMap Survivor and duplicate local keys mapped to global IDs.
1576
+ * @returns One animation per directed pair with its original tracker duration and metadata.
1577
+ */
1267
1578
  function remapAnimations(segmentResults, globalIdMap) {
1268
- const animations = [];
1269
- for (const result of segmentResults) {
1270
- for (const anim of result.animations) {
1271
- const newStartId = globalIdMap.get(
1272
- `${result.segment.index}:${anim.startFrameId}`
1273
- );
1274
- const newEndId = globalIdMap.get(
1275
- `${result.segment.index}:${anim.endFrameId}`
1276
- );
1277
- if (newStartId === void 0 || newEndId === void 0) continue;
1278
- animations.push({
1279
- ...anim,
1280
- startFrameId: newStartId,
1281
- endFrameId: newEndId
1282
- });
1283
- }
1284
- }
1285
- return animations;
1579
+ const animations = /* @__PURE__ */ new Map();
1580
+ for (const result of segmentResults) for (const anim of result.animations) {
1581
+ const newStartId = globalIdMap.get(`${result.segment.index}:${anim.startFrameId}`);
1582
+ const newEndId = globalIdMap.get(`${result.segment.index}:${anim.endFrameId}`);
1583
+ if (newStartId === void 0 || newEndId === void 0) continue;
1584
+ if (newStartId === newEndId) continue;
1585
+ const animationKey = `${newStartId}-${newEndId}`;
1586
+ if (animations.has(animationKey)) continue;
1587
+ animations.set(animationKey, {
1588
+ ...anim,
1589
+ startFrameId: newStartId,
1590
+ endFrameId: newEndId
1591
+ });
1592
+ }
1593
+ return [...animations.values()];
1286
1594
  }
1595
+ /**
1596
+ * Merge multiple segment results into a single unified frame/edge/animation set.
1597
+ * @param segmentResults Local frames, edges and tracker entries with distinct segment indices.
1598
+ * @returns Global timestamp-ordered frames, aliased edges and animations without self loops.
1599
+ * Duplicate edges keep the higher score; duplicate animations keep the first tracker entry.
1600
+ */
1287
1601
  function mergeSegmentFrames(segmentResults) {
1288
- if (segmentResults.length === 0) {
1289
- return { frames: [], edges: [], animations: [] };
1290
- }
1291
- const effectiveFps = segmentResults[0].segment.effectiveFps;
1292
- const allFrames = collectAllFrames(segmentResults);
1293
- const uniqueFrames = deduplicateFrames(allFrames, effectiveFps);
1294
- const { frames, globalIdMap } = remapFrameIds(uniqueFrames);
1295
- const edges = remapEdges(segmentResults, globalIdMap);
1296
- const animations = remapAnimations(segmentResults, globalIdMap);
1297
- return { frames, edges, animations };
1602
+ if (segmentResults.length === 0) return {
1603
+ frames: [],
1604
+ edges: [],
1605
+ animations: [],
1606
+ analysisResolution: {
1607
+ width: 0,
1608
+ height: 0
1609
+ }
1610
+ };
1611
+ const effectiveFps = segmentResults[0].segment.effectiveFps;
1612
+ const { unique, aliases } = deduplicateFrames(collectAllFrames(segmentResults), effectiveFps);
1613
+ const { frames, globalIdMap } = remapFrameIds(unique, aliases);
1614
+ return {
1615
+ frames,
1616
+ edges: remapEdges(segmentResults, globalIdMap),
1617
+ animations: remapAnimations(segmentResults, globalIdMap),
1618
+ analysisResolution: segmentResults[0].analysisResolution
1619
+ };
1298
1620
  }
1299
1621
  function buildSegmentContext(segment, frames, segmentWorkspacePath, resolvedOptions, onProgress) {
1300
- return {
1301
- options: {
1302
- ...resolvedOptions,
1303
- fps: segment.effectiveFps,
1304
- maxFrames: segment.allocatedFrames
1305
- },
1306
- workspacePath: segmentWorkspacePath,
1307
- frames,
1308
- graph: [],
1309
- status: "ANALYZING",
1310
- emitProgress: onProgress
1311
- };
1622
+ return {
1623
+ options: {
1624
+ ...resolvedOptions,
1625
+ fps: segment.effectiveFps,
1626
+ maxFrames: segment.allocatedFrames
1627
+ },
1628
+ workspacePath: segmentWorkspacePath,
1629
+ effectiveFps: segment.effectiveFps,
1630
+ frames,
1631
+ graph: [],
1632
+ status: "ANALYZING",
1633
+ emitProgress: onProgress
1634
+ };
1312
1635
  }
1636
+ /**
1637
+ * Extract frames for a single segment and analyze them.
1638
+ * Each segment uses an isolated workspace directory.
1639
+ */
1313
1640
  async function processSegment(inputPath, segment, workspacePath, resolvedOptions, onProgress) {
1314
- const framesDir = join5(workspacePath, "frames");
1315
- const frames = await extractFramesForRange(
1316
- inputPath,
1317
- framesDir,
1318
- segment.effectiveFps,
1319
- resolvedOptions.scale,
1320
- segment.extractStartTime,
1321
- segment.extractDuration
1322
- );
1323
- if (frames.length < 2) {
1324
- return { segment, frames, edges: [], animations: [] };
1325
- }
1326
- const ctx = buildSegmentContext(
1327
- segment,
1328
- frames,
1329
- workspacePath,
1330
- resolvedOptions,
1331
- onProgress
1332
- );
1333
- const { edges, animations } = await analyzeFrames(ctx);
1334
- return { segment, frames, edges, animations };
1641
+ const frames = await extractFramesForRange(inputPath, join(workspacePath, "frames"), segment.effectiveFps, resolvedOptions.scale, segment.extractStartTime, segment.extractDuration, segment.allocatedFrames);
1642
+ if (frames.length < 2) return {
1643
+ segment,
1644
+ frames,
1645
+ edges: [],
1646
+ animations: [],
1647
+ analysisResolution: {
1648
+ width: 0,
1649
+ height: 0
1650
+ }
1651
+ };
1652
+ const { edges, animations, analysisResolution } = await analyzeFrames(buildSegmentContext(segment, frames, workspacePath, resolvedOptions, onProgress));
1653
+ return {
1654
+ segment,
1655
+ frames,
1656
+ edges,
1657
+ animations,
1658
+ analysisResolution
1659
+ };
1335
1660
  }
1336
- async function runSegmentedPipeline(options2, resolvedOptions) {
1337
- const pipelineStart = Date.now();
1338
- const sessionId = randomUUID();
1339
- let mainWorkspace = "";
1340
- try {
1341
- mainWorkspace = await createWorkspace(sessionId);
1342
- logger.debug(`Segmented pipeline: workspace at ${mainWorkspace}`);
1343
- const { resolvedInputPath } = await resolveInput(options2, mainWorkspace);
1344
- const inputPath = resolvedInputPath ?? resolvedOptions.inputPath;
1345
- if (!inputPath) {
1346
- throw new Error("No input path available for segmented pipeline");
1347
- }
1348
- const metadata = await getVideoMetadata(inputPath);
1349
- const totalDuration = parseFloat(metadata.format?.duration ?? "0");
1350
- if (totalDuration <= 0) {
1351
- throw new Error(`Invalid video duration: ${totalDuration}`);
1352
- }
1353
- logger.debug(`Video duration: ${totalDuration}s`);
1354
- const segments = computeSegmentPlan(
1355
- totalDuration,
1356
- resolvedOptions.maxSegmentDuration,
1357
- resolvedOptions.maxFrames,
1358
- resolvedOptions.fps
1359
- );
1360
- logger.debug(`Segment plan: ${segments.length} segments`);
1361
- const limit = concurrencyLimit(resolvedOptions.concurrency);
1362
- const segmentProgresses = new Array(segments.length).fill(0);
1363
- const weights = map6(segments, (s) => s.duration / totalDuration);
1364
- const emitOverallProgress = (phase) => {
1365
- if (!options2.onProgress) return;
1366
- const overall = weights.reduce(
1367
- (sum, w, i) => sum + w * (segmentProgresses[i] ?? 0),
1368
- 0
1369
- );
1370
- options2.onProgress(phase, Math.min(100, overall));
1371
- };
1372
- options2.onProgress?.("EXTRACTING", 0);
1373
- const results = await Promise.all(
1374
- map6(
1375
- segments,
1376
- (segment) => limit(async () => {
1377
- const segWorkspace = await createSegmentWorkspace(
1378
- mainWorkspace,
1379
- segment.index
1380
- );
1381
- const result = await processSegment(
1382
- inputPath,
1383
- segment,
1384
- segWorkspace,
1385
- resolvedOptions,
1386
- (percent) => {
1387
- segmentProgresses[segment.index] = percent;
1388
- emitOverallProgress("ANALYZING");
1389
- }
1390
- );
1391
- return result;
1392
- })
1393
- )
1394
- );
1395
- options2.onProgress?.("ANALYZING", 100);
1396
- const { frames, edges, animations } = mergeSegmentFrames(results);
1397
- logger.debug(
1398
- `Merged: ${frames.length} frames, ${edges.length} edges, ${animations.length} animations`
1399
- );
1400
- options2.onProgress?.("PRUNING", 0);
1401
- const survivingIds = pruneByThresholdWithCap(
1402
- edges,
1403
- frames,
1404
- resolvedOptions.threshold,
1405
- resolvedOptions.count
1406
- );
1407
- const prunedFrames = filter5(frames, (f) => survivingIds.has(f.id));
1408
- options2.onProgress?.("PRUNING", 100);
1409
- options2.onProgress?.("FINALIZING", 0);
1410
- const ctx = {
1411
- options: resolvedOptions,
1412
- workspacePath: mainWorkspace,
1413
- frames,
1414
- graph: edges,
1415
- animations,
1416
- status: "FINALIZING",
1417
- emitProgress: (percent) => options2.onProgress?.("FINALIZING", percent)
1418
- };
1419
- let outputFiles = [];
1420
- let outputBuffers;
1421
- if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") {
1422
- outputBuffers = await readFramesAsBuffers(
1423
- prunedFrames,
1424
- resolvedOptions.quality
1425
- );
1426
- } else {
1427
- outputFiles = await finalizeOutput(ctx, prunedFrames);
1428
- }
1429
- options2.onProgress?.("FINALIZING", 100);
1430
- logger.success(
1431
- `Segmented pipeline: ${prunedFrames.length} scenes from ${frames.length} frames (${segments.length} segments)`
1432
- );
1433
- return {
1434
- success: true,
1435
- originalFramesCount: frames.length,
1436
- prunedFramesCount: prunedFrames.length,
1437
- outputFiles,
1438
- outputBuffers,
1439
- animations,
1440
- video: {
1441
- originalDurationMs: totalDuration * 1e3,
1442
- fps: resolvedOptions.fps,
1443
- resolution: {
1444
- width: resolvedOptions.scale,
1445
- height: Math.round(resolvedOptions.scale * 9 / 16)
1446
- }
1447
- },
1448
- executionTimeMs: Date.now() - pipelineStart
1449
- };
1450
- } catch (error) {
1451
- const err = error instanceof Error ? error : new Error(String(error));
1452
- logger.error(`Segmented pipeline failed: ${err.message}`);
1453
- throw err;
1454
- } finally {
1455
- if (!resolvedOptions.debug) {
1456
- await cleanupWorkspace(mainWorkspace);
1457
- } else {
1458
- logger.debug(`Debug mode: workspace preserved at ${mainWorkspace}`);
1459
- }
1460
- }
1661
+ /**
1662
+ * Full segmented pipeline: metadata → plan → parallel extract+analyze → merge → prune → finalize.
1663
+ * Called from runPipeline when shouldSegment() returns true.
1664
+ */
1665
+ async function runSegmentedPipeline(options, resolvedOptions) {
1666
+ const pipelineStart = Date.now();
1667
+ const sessionId = randomUUID();
1668
+ let mainWorkspace = "";
1669
+ try {
1670
+ mainWorkspace = await createWorkspace(sessionId);
1671
+ logger.debug(`Segmented pipeline: workspace at ${mainWorkspace}`);
1672
+ const { resolvedInputPath } = await resolveInput(options, mainWorkspace);
1673
+ const inputPath = resolvedInputPath ?? resolvedOptions.inputPath;
1674
+ if (!inputPath) throw new Error("No input path available for segmented pipeline");
1675
+ const metadata = await getVideoMetadata(inputPath);
1676
+ const totalDuration = parseFloat(metadata.format?.duration ?? "0");
1677
+ if (totalDuration <= 0) throw new Error(`Invalid video duration: ${totalDuration}`);
1678
+ logger.debug(`Video duration: ${totalDuration}s`);
1679
+ const segments = computeSegmentPlan(totalDuration, resolvedOptions.maxSegmentDuration, resolvedOptions.maxFrames, resolvedOptions.fps);
1680
+ logger.debug(`Segment plan: ${segments.length} segments`);
1681
+ const limit = concurrencyLimit(resolvedOptions.concurrency);
1682
+ const segmentProgresses = new Array(segments.length).fill(0);
1683
+ const weights = map(segments, (s) => s.duration / totalDuration);
1684
+ const emitOverallProgress = (phase) => {
1685
+ if (!options.onProgress) return;
1686
+ const overall = weights.reduce((sum, w, i) => sum + w * (segmentProgresses[i] ?? 0), 0);
1687
+ options.onProgress(phase, Math.min(100, overall));
1688
+ };
1689
+ options.onProgress?.("EXTRACTING", 0);
1690
+ const results = await Promise.all(map(segments, (segment) => limit(async () => {
1691
+ const segWorkspace = await createSegmentWorkspace(mainWorkspace, segment.index);
1692
+ return await processSegment(inputPath, segment, segWorkspace, resolvedOptions, (percent) => {
1693
+ segmentProgresses[segment.index] = percent;
1694
+ emitOverallProgress("ANALYZING");
1695
+ });
1696
+ })));
1697
+ options.onProgress?.("ANALYZING", 100);
1698
+ const { frames, edges, animations, analysisResolution } = mergeSegmentFrames(results);
1699
+ logger.debug(`Merged: ${frames.length} frames, ${edges.length} edges, ${animations.length} animations`);
1700
+ options.onProgress?.("PRUNING", 0);
1701
+ const survivingIds = pruneByThresholdWithCap(edges, frames, resolvedOptions.threshold, resolvedOptions.count);
1702
+ const prunedFrames = filter(frames, (f) => survivingIds.has(f.id));
1703
+ options.onProgress?.("PRUNING", 100);
1704
+ options.onProgress?.("FINALIZING", 0);
1705
+ const ctx = {
1706
+ options: resolvedOptions,
1707
+ effectiveFps: segments[0]?.effectiveFps,
1708
+ sourceDurationSec: totalDuration,
1709
+ analysisResolution,
1710
+ workspacePath: mainWorkspace,
1711
+ frames,
1712
+ graph: edges,
1713
+ animations,
1714
+ status: "FINALIZING",
1715
+ emitProgress: (percent) => options.onProgress?.("FINALIZING", percent)
1716
+ };
1717
+ let outputFiles = [];
1718
+ let outputBuffers;
1719
+ if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") outputBuffers = await readFramesAsBuffers(prunedFrames, resolvedOptions.quality);
1720
+ else outputFiles = await finalizeOutput(ctx, prunedFrames);
1721
+ options.onProgress?.("FINALIZING", 100);
1722
+ logger.success(`Segmented pipeline: ${prunedFrames.length} scenes from ${frames.length} frames (${segments.length} segments)`);
1723
+ const outputMetadata = await buildVideoMetadata(ctx, prunedFrames, analysisResolution);
1724
+ return {
1725
+ success: true,
1726
+ originalFramesCount: frames.length,
1727
+ prunedFramesCount: prunedFrames.length,
1728
+ outputFiles,
1729
+ outputBuffers,
1730
+ ...outputMetadata,
1731
+ executionTimeMs: Date.now() - pipelineStart
1732
+ };
1733
+ } catch (error) {
1734
+ const err = error instanceof Error ? error : new Error(String(error));
1735
+ logger.error(`Segmented pipeline failed: ${err.message}`);
1736
+ throw err;
1737
+ } finally {
1738
+ if (!resolvedOptions.debug) await cleanupWorkspace(mainWorkspace);
1739
+ else logger.debug(`Debug mode: workspace preserved at ${mainWorkspace}`);
1740
+ }
1461
1741
  }
1462
1742
 
1463
- // src/core/orchestrator.ts
1464
- async function runPipeline(options2) {
1465
- const debug = options2.debug ?? false;
1466
- if (debug) setDebugMode(true);
1467
- const resolvedOptions = resolveOptions(options2);
1468
- if (shouldSegment(resolvedOptions, options2)) {
1469
- return runSegmentedPipeline(options2, resolvedOptions);
1470
- }
1471
- const startTime = Date.now();
1472
- const sessionId = randomUUID2();
1473
- const ctx = {
1474
- options: resolvedOptions,
1475
- workspacePath: "",
1476
- frames: [],
1477
- graph: [],
1478
- status: "INIT",
1479
- emitProgress: (percent) => {
1480
- if (options2.onProgress && ctx.status !== "INIT" && ctx.status !== "SUCCESS" && ctx.status !== "FAILED") {
1481
- options2.onProgress(ctx.status, percent);
1482
- }
1483
- }
1484
- };
1485
- try {
1486
- ctx.workspacePath = await createWorkspace(sessionId);
1487
- logger.debug(`Workspace created: ${ctx.workspacePath}`);
1488
- ctx.status = "EXTRACTING";
1489
- const { frames: resolvedFrames, resolvedInputPath } = await resolveInput(
1490
- options2,
1491
- ctx.workspacePath
1492
- );
1493
- if (resolvedOptions.mode === "frames") {
1494
- ctx.frames = resolvedFrames;
1495
- } else {
1496
- const extractCtx = {
1497
- ...ctx,
1498
- options: {
1499
- ...resolvedOptions,
1500
- inputPath: resolvedInputPath
1501
- }
1502
- };
1503
- ctx.frames = await extractFrames(extractCtx);
1504
- }
1505
- ctx.emitProgress(100);
1506
- ctx.status = "ANALYZING";
1507
- const { edges, animations } = await analyzeFrames(ctx);
1508
- ctx.graph = edges;
1509
- ctx.animations = animations;
1510
- ctx.status = "PRUNING";
1511
- const survivingIds = pruneByThresholdWithCap(
1512
- ctx.graph,
1513
- ctx.frames,
1514
- resolvedOptions.threshold,
1515
- resolvedOptions.count
1516
- );
1517
- const prunedFrames = filter6(ctx.frames, (f) => survivingIds.has(f.id));
1518
- ctx.emitProgress(100);
1519
- ctx.status = "FINALIZING";
1520
- let outputFiles = [];
1521
- let outputBuffers;
1522
- if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") {
1523
- outputBuffers = await readFramesAsBuffers(
1524
- prunedFrames,
1525
- resolvedOptions.quality
1526
- );
1527
- ctx.emitProgress(100);
1528
- } else {
1529
- outputFiles = await finalizeOutput(ctx, prunedFrames);
1530
- ctx.emitProgress(100);
1531
- }
1532
- ctx.status = "SUCCESS";
1533
- logger.success(
1534
- `Extracted ${prunedFrames.length} scenes from ${ctx.frames.length} frames`
1535
- );
1536
- return {
1537
- success: true,
1538
- originalFramesCount: ctx.frames.length,
1539
- prunedFramesCount: prunedFrames.length,
1540
- outputFiles,
1541
- outputBuffers,
1542
- animations: ctx.animations,
1543
- video: {
1544
- originalDurationMs: ctx.frames.length / ctx.options.fps * 1e3,
1545
- fps: ctx.options.fps,
1546
- resolution: {
1547
- width: ctx.options.scale,
1548
- height: Math.round(ctx.options.scale * 9 / 16)
1549
- }
1550
- },
1551
- executionTimeMs: Date.now() - startTime
1552
- };
1553
- } catch (error) {
1554
- ctx.status = "FAILED";
1555
- ctx.error = error instanceof Error ? error : new Error(String(error));
1556
- logger.error(`Pipeline failed: ${ctx.error.message}`);
1557
- throw ctx.error;
1558
- } finally {
1559
- if (!resolvedOptions.debug) {
1560
- await cleanupWorkspace(ctx.workspacePath);
1561
- } else {
1562
- logger.debug(`Debug mode: workspace preserved at ${ctx.workspacePath}`);
1563
- }
1564
- }
1743
+ //#endregion
1744
+ //#region src/core/orchestrator/orchestrator.ts
1745
+ async function runPipeline(options) {
1746
+ setDebugMode(options.debug ?? false);
1747
+ const resolvedOptions = resolveOptions(options);
1748
+ if (shouldSegment(resolvedOptions, options)) return runSegmentedPipeline(options, resolvedOptions);
1749
+ const startTime = Date.now();
1750
+ const sessionId = randomUUID();
1751
+ const ctx = {
1752
+ options: resolvedOptions,
1753
+ workspacePath: "",
1754
+ frames: [],
1755
+ graph: [],
1756
+ status: "INIT",
1757
+ emitProgress: (percent) => {
1758
+ if (options.onProgress && ctx.status !== "INIT" && ctx.status !== "SUCCESS" && ctx.status !== "FAILED") options.onProgress(ctx.status, percent);
1759
+ }
1760
+ };
1761
+ try {
1762
+ ctx.workspacePath = await createWorkspace(sessionId);
1763
+ logger.debug(`Workspace created: ${ctx.workspacePath}`);
1764
+ ctx.status = "EXTRACTING";
1765
+ const { frames: resolvedFrames, resolvedInputPath } = await resolveInput(options, ctx.workspacePath);
1766
+ if (resolvedOptions.mode === "frames") {
1767
+ ctx.frames = resolvedFrames;
1768
+ ctx.effectiveFps = 1;
1769
+ } else {
1770
+ const extractCtx = {
1771
+ ...ctx,
1772
+ options: {
1773
+ ...resolvedOptions,
1774
+ inputPath: resolvedInputPath
1775
+ }
1776
+ };
1777
+ ctx.frames = await extractFrames(extractCtx);
1778
+ ctx.effectiveFps = extractCtx.effectiveFps;
1779
+ ctx.sourceDurationSec = extractCtx.sourceDurationSec;
1780
+ }
1781
+ ctx.emitProgress(100);
1782
+ ctx.status = "ANALYZING";
1783
+ const { edges, animations, analysisResolution } = await analyzeFrames(ctx);
1784
+ ctx.graph = edges;
1785
+ ctx.animations = animations;
1786
+ ctx.analysisResolution = analysisResolution;
1787
+ ctx.status = "PRUNING";
1788
+ const survivingIds = pruneByThresholdWithCap(ctx.graph, ctx.frames, resolvedOptions.threshold, resolvedOptions.count);
1789
+ const prunedFrames = filter(ctx.frames, (f) => survivingIds.has(f.id));
1790
+ ctx.emitProgress(100);
1791
+ ctx.status = "FINALIZING";
1792
+ let outputFiles = [];
1793
+ let outputBuffers;
1794
+ if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") {
1795
+ outputBuffers = await readFramesAsBuffers(prunedFrames, resolvedOptions.quality);
1796
+ ctx.emitProgress(100);
1797
+ } else {
1798
+ outputFiles = await finalizeOutput(ctx, prunedFrames);
1799
+ ctx.emitProgress(100);
1800
+ }
1801
+ ctx.status = "SUCCESS";
1802
+ logger.success(`Extracted ${prunedFrames.length} scenes from ${ctx.frames.length} frames`);
1803
+ const metadata = await buildVideoMetadata(ctx, prunedFrames, analysisResolution);
1804
+ return {
1805
+ success: true,
1806
+ originalFramesCount: ctx.frames.length,
1807
+ prunedFramesCount: prunedFrames.length,
1808
+ outputFiles,
1809
+ outputBuffers,
1810
+ ...metadata,
1811
+ executionTimeMs: Date.now() - startTime
1812
+ };
1813
+ } catch (error) {
1814
+ ctx.status = "FAILED";
1815
+ ctx.error = error instanceof Error ? error : new Error(String(error));
1816
+ logger.error(`Pipeline failed: ${ctx.error.message}`);
1817
+ throw ctx.error;
1818
+ } finally {
1819
+ if (!resolvedOptions.debug) await cleanupWorkspace(ctx.workspacePath);
1820
+ else logger.debug(`Debug mode: workspace preserved at ${ctx.workspacePath}`);
1821
+ }
1565
1822
  }
1566
1823
 
1567
- // src/core/pipeline-worker.ts
1568
- var options = workerData;
1824
+ //#endregion
1825
+ //#region src/core/orchestrator/worker/pipeline-worker.ts
1569
1826
  runPipeline({
1570
- ...options,
1571
- onProgress: (phase, percent) => {
1572
- parentPort?.postMessage({
1573
- type: "progress",
1574
- phase,
1575
- percent
1576
- });
1577
- }
1827
+ ...workerData,
1828
+ onProgress: (phase, percent) => {
1829
+ parentPort?.postMessage({
1830
+ type: "progress",
1831
+ phase,
1832
+ percent
1833
+ });
1834
+ }
1578
1835
  }).then((result) => {
1579
- parentPort?.postMessage({
1580
- type: "result",
1581
- result
1582
- });
1836
+ parentPort?.postMessage({
1837
+ type: "result",
1838
+ result
1839
+ });
1583
1840
  }).catch((error) => {
1584
- parentPort?.postMessage({
1585
- type: "error",
1586
- message: error instanceof Error ? error.message : String(error)
1587
- });
1841
+ parentPort?.postMessage({
1842
+ type: "error",
1843
+ message: error instanceof Error ? error.message : String(error)
1844
+ });
1588
1845
  });
1846
+
1847
+ //#endregion
1848
+ export { };