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