@lumy-pack/scene-sieve 0.0.13 → 0.1.0

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