@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.
- package/dist/cli.mjs +1979 -2081
- package/dist/index.cjs +1370 -1462
- package/dist/index.mjs +1348 -1430
- package/dist/pipeline-worker.mjs +1371 -1452
- package/dist/utils/logger.d.ts +1 -0
- package/package.json +5 -4
package/dist/pipeline-worker.mjs
CHANGED
|
@@ -1,1572 +1,1491 @@
|
|
|
1
|
-
|
|
2
|
-
import { parentPort, workerData } from "worker_threads";
|
|
3
|
-
|
|
4
|
-
|
|
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
|
-
|
|
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
|
-
|
|
18
|
+
debugMode = enabled;
|
|
13
19
|
}
|
|
14
20
|
function timestamp() {
|
|
15
|
-
|
|
21
|
+
return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
|
|
16
22
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
59
|
+
return join(TEMP_BASE_DIR, `${WORKSPACE_PREFIX}${sessionId}`);
|
|
76
60
|
}
|
|
77
61
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
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
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
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
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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
|
-
|
|
544
|
-
|
|
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
|
-
|
|
487
|
+
await mkdir(dirPath, { recursive: true });
|
|
557
488
|
}
|
|
558
489
|
async function fileExists(filePath) {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
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
|
-
|
|
568
|
-
|
|
569
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
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
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
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
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
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
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
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
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
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
|
-
|
|
688
|
-
|
|
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
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
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
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
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
|
-
|
|
751
|
-
|
|
752
|
-
|
|
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
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
685
|
+
if (!workspacePath) return;
|
|
686
|
+
try {
|
|
687
|
+
await rm(workspacePath, {
|
|
688
|
+
recursive: true,
|
|
689
|
+
force: true
|
|
690
|
+
});
|
|
691
|
+
} catch {}
|
|
764
692
|
}
|
|
765
|
-
|
|
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
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
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
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
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
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
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
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
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
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
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
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
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
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
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
|
-
|
|
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
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
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
|
-
|
|
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
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
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
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
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
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
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
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
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
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
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
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
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
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
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
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
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
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
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
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
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
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
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
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
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
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
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
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
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
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
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
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
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
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
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
|
-
|
|
1552
|
-
|
|
1467
|
+
//#endregion
|
|
1468
|
+
//#region src/core/pipeline-worker.ts
|
|
1553
1469
|
runPipeline({
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
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
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1479
|
+
parentPort?.postMessage({
|
|
1480
|
+
type: "result",
|
|
1481
|
+
result
|
|
1482
|
+
});
|
|
1567
1483
|
}).catch((error) => {
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1484
|
+
parentPort?.postMessage({
|
|
1485
|
+
type: "error",
|
|
1486
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1487
|
+
});
|
|
1572
1488
|
});
|
|
1489
|
+
|
|
1490
|
+
//#endregion
|
|
1491
|
+
export { };
|