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