mcp-extract-video-frames 0.0.0-stage → 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/.env.example ADDED
@@ -0,0 +1,6 @@
1
+ EXTRACT_VIDEO_FRAMES_FRAME_MODE=changes
2
+ EXTRACT_VIDEO_FRAMES_FRAME_INTERVAL_SECONDS=0
3
+ EXTRACT_VIDEO_FRAMES_FRAME_MAX_COUNT=120
4
+ EXTRACT_VIDEO_FRAMES_FRAME_MAX_HEIGHT=1080
5
+ EXTRACT_VIDEO_FRAMES_FRAME_CHANGE_THRESHOLD=4.5
6
+ EXTRACT_VIDEO_FRAMES_DISCOVERY_CACHE_TTL_MS=600000
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Speechmatics Transcribe contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
1
+ # Extract Video Frames
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Turn local videos into a small, configurable set of PNG screenshots for slide
4
+ references, illustrated notes, and visual review. Use the same extraction engine
5
+ from JavaScript, the command line, or an MCP client.
6
+
7
+ Requires Node.js 22.18+ and npm. FFmpeg is resolved from
8
+ `@seydx/node-av-ffmpeg@latest` through npm exec at first media use in each process.
9
+ The provider uses npm's download cache. Subsequent FFmpeg calls in that process
10
+ reuse the resolved binary; a new process checks for the current provider version.
11
+ System FFmpeg and FFprobe are not required. Keep npm optional dependencies enabled.
12
+ FFmpeg is distributed under its provider's licenses.
13
+
14
+ ## CLI
15
+
16
+ ```sh
17
+ npx -y --prefer-online mcp-extract-video-frames@latest recording.mp4 --frame-max-count 40
18
+ npx -y --prefer-online mcp-extract-video-frames@latest --help
19
+ ```
20
+
21
+ The command returns JSON containing the output directory, manifest path, saved
22
+ count, selection settings, cache status, and FFmpeg log path. Images are prepared
23
+ for later inspection; extraction does not interpret their content.
24
+
25
+ ## JavaScript
26
+
27
+ ```sh
28
+ npm install mcp-extract-video-frames
29
+ ```
30
+
31
+ ```js
32
+ import { extractFrames } from 'mcp-extract-video-frames';
33
+
34
+ const result = await extractFrames('/recordings/lecture.mp4', {
35
+ frameMode: 'changes',
36
+ frameMaxCount: 80,
37
+ frameMaxHeight: 1080,
38
+ });
39
+ console.log(result.directory, result.manifest, result.count);
40
+ ```
41
+
42
+ Optional `outputDir` selects an explicit output directory. Otherwise artifacts are
43
+ stored in an identifiable folder under the operating system temporary directory.
44
+ Pass an AbortSignal as `signal` to cancel extraction.
45
+
46
+ ## MCP
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "extract-video-frames": {
52
+ "command": "npx",
53
+ "args": ["-y", "--prefer-online", "mcp-extract-video-frames@latest"]
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ Clients requiring a Windows executable path can use `npx.cmd`.
60
+ The `extract_frames` tool takes an absolute `file` path and the same frame settings
61
+ as the JavaScript API. Each setting describes its configured default in discovery.
62
+ With no file argument, the CLI starts MCP over stdio; `mcp` is also an explicit
63
+ subcommand. Local installations delegate to their installed CLI. An npx-managed
64
+ MCP installation resolves the current published CLI for tool calls.
65
+
66
+ ## Selection and defaults
67
+
68
+ | Option | Default | Purpose |
69
+ | --- | --- | --- |
70
+ | frameMode | changes | Adaptive visual selection, or interval for evenly distributed images |
71
+ | frameIntervalSeconds | 0 | Candidate spacing; 0 chooses automatically |
72
+ | frameMaxCount | 120 | Maximum images across the whole retained video |
73
+ | frameMaxHeight | 1080 | Maximum PNG height, without upscaling |
74
+ | frameChangeThreshold | 4.5 | Nearby grayscale similarity threshold; higher treats more images as duplicates |
75
+
76
+ Adaptive selection allocates a budget across the complete video, favoring visual
77
+ activity and local changes. Static footage can produce a single image. The limit
78
+ is an upper bound, not a cutoff that discards the end of the video. Interval mode
79
+ spreads its limited selection over the full candidate timeline.
80
+
81
+ Candidate scanning is bounded to about 20,000 frames. A short change between
82
+ samples can be missed; moving overlays can produce extra images. Selection is a
83
+ visual heuristic, not semantic slide recognition or a guarantee of completeness.
84
+ The source is decoded during scanning, and selected images are rendered in a
85
+ separate pass. Sparse output does not imply sparse decoding.
86
+
87
+ ## Configuration
88
+
89
+ Invocation settings override process environment, then the selected env file,
90
+ then built-in defaults. An optional `.env` in the working directory is loaded by
91
+ default. Use `--env-file /path/to/.env`, `EXTRACT_VIDEO_FRAMES_ENV_FILE`, or the
92
+ library's `envFile` option to select another file. Explicit missing files are errors.
93
+
94
+ | Variable | Default |
95
+ | --- | --- |
96
+ | EXTRACT_VIDEO_FRAMES_FRAME_MODE | changes |
97
+ | EXTRACT_VIDEO_FRAMES_FRAME_INTERVAL_SECONDS | 0 |
98
+ | EXTRACT_VIDEO_FRAMES_FRAME_MAX_COUNT | 120 |
99
+ | EXTRACT_VIDEO_FRAMES_FRAME_MAX_HEIGHT | 1080 |
100
+ | EXTRACT_VIDEO_FRAMES_FRAME_CHANGE_THRESHOLD | 4.5 |
101
+ | EXTRACT_VIDEO_FRAMES_DISCOVERY_CACHE_TTL_MS | 600000 |
102
+
103
+ ## Timestamps and output
104
+
105
+ PNG names use `frame-HH-MM-SS-mmm-NNNN.png`. The manifest preserves precise source
106
+ seconds, sampled compact seconds, selection settings, and source identity. These
107
+ are recording-relative timestamps, not meeting wall-clock times. Sources are not
108
+ modified, and matching completed runs are reused while their images still exist.
109
+ Missing images cause regeneration. Operating system temporary files can be removed
110
+ at any time; copy selected images into permanent notes when needed.
111
+
112
+ For integrations that remove parts of a recording, pass an optional `timeline`:
113
+
114
+ ```js
115
+ const timeline = {
116
+ originalSeconds: 100,
117
+ compactSeconds: 40,
118
+ segments: [
119
+ { originalStart: 0, originalEnd: 20, compactStart: 0, compactEnd: 20 },
120
+ { originalStart: 80, originalEnd: 100, compactStart: 20, compactEnd: 40 },
121
+ ],
122
+ };
123
+ ```
124
+
125
+ Frames are extracted from retained source intervals; filenames and `sourceSeconds`
126
+ refer to the original recording. `compactSeconds` records the corresponding time
127
+ after removal. CLI users can supply a timeline JSON with `--timeline-file`.
128
+
129
+ An existing output directory from a different run is rejected. An active or stale
130
+ `.lock` blocks writes; check that no extraction is running before removing a stale
131
+ lock. Failed runs are not cached as complete. Read `ffmpeg.log` for media errors.
132
+
133
+ ## License
134
+
135
+ MIT.
package/bin/cli.js ADDED
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { Command, Option } from "commander";
5
+ import { extractFrames } from "../src/index.js";
6
+ import { defaults } from "../src/options.js";
7
+ const {version} = JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8"));
8
+ const program = new Command().name("mcp-extract-video-frames").version(version)
9
+ .description("Extract adaptive video screenshots to PNG images and a timestamp manifest.")
10
+ .argument("[file]","Local video path")
11
+ .option("--env-file <path>","Load explicit environment defaults")
12
+ .option("--output-dir <path>","Output directory; otherwise use the operating system temporary directory")
13
+ .option("--timeline-file <path>","Retained-interval timeline JSON; filenames use original recording times")
14
+ .addOption(new Option("--frame-mode <mode>",`Selection mode (default: ${defaults.frameMode})`).choices(["changes","interval"]))
15
+ .option("--frame-interval-seconds <seconds>","Candidate spacing; 0 selects automatically",Number)
16
+ .option("--frame-max-count <count>","Maximum image count over the whole retained video",Number)
17
+ .option("--frame-max-height <pixels>","Maximum PNG height without upscaling",Number)
18
+ .option("--frame-change-threshold <value>","Near-duplicate similarity threshold",Number)
19
+ .option("--tool-manifest","Print tool catalog and JSON Schemas")
20
+ .option("--execute-tool","Execute a JSON tool request read from stdin")
21
+ .action(async(file,{toolManifest,executeTool,envFile,timelineFile,outputDir,...options})=>{
22
+ if(envFile)process.env.EXTRACT_VIDEO_FRAMES_ENV_FILE=resolve(envFile);
23
+ if(toolManifest){const {getToolManifest}=await import("../src/tools.js");console.log(JSON.stringify(await getToolManifest()));return;}
24
+ if(executeTool){const {serveExecution}=await import("../src/cli-protocol.js");await serveExecution();return;}
25
+ if(!file){await import("./mcp.js");return;}
26
+ try{
27
+ const timeline=timelineFile?JSON.parse(await readFile(timelineFile,"utf8")):undefined;
28
+ console.log(JSON.stringify(await extractFrames(file,{...options,outputDir,timeline}),null,2));
29
+ }catch(error){console.error(JSON.stringify({message:error.message}));process.exitCode=1;}
30
+ });
31
+ program.command("mcp").description("Start the MCP server over stdio").action(async()=>{if(program.opts().envFile)process.env.EXTRACT_VIDEO_FRAMES_ENV_FILE=resolve(program.opts().envFile);await import("./mcp.js");});
32
+ await program.parseAsync();
package/bin/mcp.js ADDED
@@ -0,0 +1,62 @@
1
+ import { Server, PROTOCOL_VERSION_META_KEY } from "@modelcontextprotocol/server";
2
+ import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
3
+ import { runCli, resolveCliLaunch } from "../src/mcp/cli-process.js";
4
+ import { createDiscoveryCache } from "../src/mcp/discovery-cache.js";
5
+
6
+ const launch = resolveCliLaunch();
7
+ const discovery = createDiscoveryCache(launch, () => runCli("--tool-manifest", undefined, { launch }));
8
+ let era;
9
+ let invalidation = Promise.resolve();
10
+ class LocalTransport extends StdioServerTransport {
11
+ async start() {
12
+ const dispatch = this.onmessage;
13
+ this.onmessage = (message, extra) => {
14
+ const modern = message.params?._meta && Object.hasOwn(message.params._meta, PROTOCOL_VERSION_META_KEY);
15
+ if (era !== "modern" && !modern && message.jsonrpc === "2.0" && message.method === "ping"
16
+ && (typeof message.id === "string" || typeof message.id === "number")) {
17
+ this.send({ jsonrpc: "2.0", id: message.id, result: {} }).catch((error) => this.onerror?.(error));
18
+ return;
19
+ }
20
+ if (message.method === "notifications/tools/list_changed" && message.id === undefined) {
21
+ invalidation = discovery.invalidate();
22
+ return;
23
+ }
24
+ dispatch?.(message, extra);
25
+ };
26
+ return super.start();
27
+ }
28
+ }
29
+
30
+ async function createServer(context) {
31
+ era = context.era;
32
+ await invalidation;
33
+ let manifest = await discovery.get();
34
+ const server = new Server(manifest.serverInfo, {
35
+ instructions: manifest.serverInfo.description,
36
+ capabilities: { tools: { listChanged: true } },
37
+ });
38
+ server.setRequestHandler("tools/list", async () => {
39
+ await invalidation;
40
+ const latest = await discovery.get();
41
+ const changed = JSON.stringify(latest.tools) !== JSON.stringify(manifest.tools);
42
+ manifest = latest;
43
+ if (changed) {
44
+ await discovery.invalidate();
45
+ await server.sendToolListChanged();
46
+ }
47
+ const { protocol, serverInfo, ...result } = manifest;
48
+ return result;
49
+ });
50
+ server.setRequestHandler("tools/call", async ({ params }, context) => {
51
+ try {
52
+ return await runCli("--execute-tool", {
53
+ protocol: 1, name: params.name, arguments: params.arguments ?? {},
54
+ }, { signal: context?.mcpReq.signal });
55
+ } catch (error) {
56
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ message: error.message }) }] };
57
+ }
58
+ });
59
+ return server;
60
+ }
61
+
62
+ serveStdio(createServer, { transport: new LocalTransport() });
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "mcp-extract-video-frames",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Extract adaptive video screenshots through a JavaScript library, CLI, or MCP server.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Łukasz Kucharski",
8
+ "repository": { "type": "git", "url": "git+https://github.com/kucharskill/mcp-extract-video-frames.git" },
9
+ "homepage": "https://github.com/kucharskill/mcp-extract-video-frames#readme",
10
+ "bugs": { "url": "https://github.com/kucharskill/mcp-extract-video-frames/issues" },
11
+ "keywords": ["mcp", "video", "ffmpeg", "screenshots", "frames"],
12
+ "engines": { "node": ">=22.18.0" },
13
+ "bin": { "mcp-extract-video-frames": "bin/cli.js" },
14
+ "exports": { ".": "./src/index.js", "./options": "./src/options.js" },
15
+ "files": ["bin/", "src/", "README.md", "LICENSE", ".env.example"],
16
+ "publishConfig": { "access": "public" },
17
+ "scripts": {
18
+ "check": "node scripts/check.mjs",
19
+ "test": "node --test tests/*.test.mjs",
20
+ "release:prepare": "npm run check && node scripts/prepare-release.mjs",
21
+ "release:publish": "node scripts/publish-release.mjs",
22
+ "release:auto": "node scripts/automatic-release.mjs"
23
+ },
24
+ "dependencies": {
25
+ "@modelcontextprotocol/server": "^2.4.0",
26
+ "commander": "^15.1.0",
27
+ "dotenv": "^18.0.10",
28
+ "zod": "^4.6.7"
29
+ },
30
+ "devDependencies": { "@modelcontextprotocol/client": "^2.4.0" }
31
+ }
@@ -0,0 +1,21 @@
1
+ import { executeTool } from "./tools.js";
2
+
3
+ export async function serveExecution() {
4
+ try {
5
+ let input = "";
6
+ process.stdin.setEncoding("utf8");
7
+ for await (const chunk of process.stdin) {
8
+ input += chunk;
9
+ if (input.length > 1024 * 1024) throw new Error("Worker request exceeded 1 MiB.");
10
+ }
11
+ const request = JSON.parse(input);
12
+ if (request.protocol !== 1) throw new Error("Unsupported worker protocol.");
13
+ const result = await executeTool(request.name, request.arguments);
14
+ process.stdout.write(JSON.stringify(result) + "\n");
15
+ } catch (error) {
16
+ process.stdout.write(JSON.stringify({
17
+ isError: true,
18
+ content: [{ type: "text", text: JSON.stringify(error.result ?? { message: error.message }) }],
19
+ }) + "\n");
20
+ }
21
+ }
package/src/config.js ADDED
@@ -0,0 +1,27 @@
1
+ import dotenv from "dotenv";
2
+ import { resolve } from "node:path";
3
+ import { defaults, optionsSchema } from "./options.js";
4
+
5
+ const variables = {
6
+ frameMode: "FRAME_MODE", frameIntervalSeconds: "FRAME_INTERVAL_SECONDS",
7
+ frameMaxCount: "FRAME_MAX_COUNT", frameMaxHeight: "FRAME_MAX_HEIGHT",
8
+ frameChangeThreshold: "FRAME_CHANGE_THRESHOLD",
9
+ };
10
+ export function loadConfig(overrides = {}, { env = process.env, envFile } = {}) {
11
+ const environment = { ...env };
12
+ const explicit = envFile ?? environment.EXTRACT_VIDEO_FRAMES_ENV_FILE;
13
+ const path = explicit ?? resolve(".env");
14
+ if (path) {
15
+ const result = dotenv.config({path:resolve(path),processEnv:environment,quiet:true});
16
+ if (result.error && (explicit || result.error.code !== "ENOENT")) throw result.error;
17
+ }
18
+ const settings = {};
19
+ for (const [option, suffix] of Object.entries(variables)) {
20
+ const value = environment["EXTRACT_VIDEO_FRAMES_" + suffix];
21
+ if (value !== undefined) {
22
+ if (!String(value).trim()) throw new Error("EXTRACT_VIDEO_FRAMES_" + suffix + " must not be empty.");
23
+ settings[option] = option === "frameMode" ? value : Number(value);
24
+ }
25
+ }
26
+ return optionsSchema.parse({...defaults,...settings,...Object.fromEntries(Object.entries(overrides).filter(([,v])=>v!==undefined))});
27
+ }
@@ -0,0 +1,31 @@
1
+ import { accessSync, constants, existsSync, mkdirSync } from "node:fs";
2
+ import { execFileSync } from "node:child_process";
3
+ import { dirname, delimiter, join, resolve } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ let command;
8
+ export function getFfmpegCommand() {
9
+ if (command) return command;
10
+ const candidates = [process.env.npm_execpath,
11
+ join(dirname(process.execPath), "node_modules/npm/bin/npm-cli.js"),
12
+ resolve(dirname(process.execPath), "../lib/node_modules/npm/bin/npm-cli.js"),
13
+ ...(process.env.PATH ?? "").split(delimiter).map(directory => join(directory, "node_modules/npm/bin/npm-cli.js")),
14
+ ].filter(Boolean);
15
+ const npm = candidates.find(file => /npm-cli\.js$/i.test(file) && existsSync(file));
16
+ if (!npm) throw new Error("FFmpeg provider requires npm. Install Node.js with npm available.");
17
+ const cwd = join(tmpdir(), "extract-video-frames", "ffmpeg");
18
+ mkdirSync(cwd, { recursive: true });
19
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^npm_config_(package|call)$/i.test(key)));
20
+ try {
21
+ const output = execFileSync(process.execPath, [npm, "exec", "--yes", "--prefer-online", "--package=@seydx/node-av-ffmpeg@latest", "--", process.execPath, fileURLToPath(new URL("./ffmpeg-provider.cjs", import.meta.url))], {
22
+ cwd, env, stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true, encoding: "utf8", timeout: 180000, maxBuffer: 1024 * 1024,
23
+ });
24
+ const result = JSON.parse(output.trim());
25
+ accessSync(result.command, constants.X_OK);
26
+ command = result.command;
27
+ return command;
28
+ } catch (error) {
29
+ throw new Error(`FFmpeg provider could not resolve @seydx/node-av-ffmpeg@latest through npm exec. Check npm connectivity and optional dependencies. ${error.message}`);
30
+ }
31
+ }
@@ -0,0 +1,18 @@
1
+ const { createRequire } = require("node:module");
2
+ const { delimiter, dirname, join } = require("node:path");
3
+ const { platform, arch } = process;
4
+ const musl = platform === "linux" && !process.report.getReport().header.glibcVersionRuntime;
5
+ const variant = `${platform}-${arch}${musl ? "-musl" : ""}`;
6
+ let provider;
7
+ for (const directory of process.env.PATH.split(delimiter)) {
8
+ if (!/[\\/]node_modules[\\/]\.bin$/.test(directory)) continue;
9
+ try {
10
+ const candidate = createRequire(join(dirname(directory), "@seydx/node-av-ffmpeg/package.json"));
11
+ candidate.resolve("./package.json");
12
+ provider = candidate;
13
+ break;
14
+ } catch { /* Continue through npm's injected dependency directories. */ }
15
+ }
16
+ if (!provider) throw new Error("npm exec did not provide the FFmpeg package.");
17
+ const command = provider.resolve(`@seydx/node-av-ffmpeg-${variant}/ffmpeg${platform === "win32" ? ".exe" : ""}`);
18
+ process.stdout.write(JSON.stringify({ command }));
package/src/ffmpeg.js ADDED
@@ -0,0 +1,10 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { getFfmpegCommand } from "./ffmpeg-command.js";
4
+ const execute = promisify(execFile);
5
+ export async function runFfmpeg(args, { signal } = {}) {
6
+ signal?.throwIfAborted();
7
+ return execute(getFfmpegCommand(), ["-nostdin", "-hide_banner", "-nostats", ...args], {
8
+ windowsHide: true, shell: false, maxBuffer: 16 * 1024 * 1024, signal,
9
+ });
10
+ }
@@ -0,0 +1,157 @@
1
+ const scanSize = 96;
2
+ const sampleSize = scanSize ** 2;
3
+
4
+ export function describeSample(current, previous) {
5
+ const signature = new Uint8Array(sampleSize / 9);
6
+ let change = 0;
7
+ let left = scanSize;
8
+ let top = scanSize;
9
+ let right = -1;
10
+ let bottom = -1;
11
+ for (let y = 0; y < scanSize; y += 3) {
12
+ for (let x = 0; x < scanSize; x += 3) {
13
+ let sum = 0;
14
+ for (let dy = 0; dy < 3; dy++) {
15
+ for (let dx = 0; dx < 3; dx++) {
16
+ const index = (y + dy) * scanSize + x + dx;
17
+ const difference = Math.abs(current[index] - previous[index]);
18
+ sum += current[index];
19
+ change += difference;
20
+ if (difference >= 24) {
21
+ left = Math.min(left, x + dx);
22
+ right = Math.max(right, x + dx);
23
+ top = Math.min(top, y + dy);
24
+ bottom = Math.max(bottom, y + dy);
25
+ }
26
+ }
27
+ }
28
+ signature[(y / 3) * (scanSize / 3) + x / 3] = Math.round(sum / 9);
29
+ }
30
+ }
31
+ const width = right - left + 1;
32
+ const height = bottom - top + 1;
33
+ const bounds = width >= 3 && height >= 3 ? { left, top, width, height } : null;
34
+ return { signature, change: change / sampleSize, bounds };
35
+ }
36
+
37
+ function quantile(values, fraction) {
38
+ return values.toSorted((a, b) => a - b)[Math.floor((values.length - 1) * fraction)];
39
+ }
40
+
41
+ function frameDifference(a, b) {
42
+ let difference = 0;
43
+ let local = 0;
44
+ const stride = scanSize / 3;
45
+ for (let y = 0; y < stride; y += 4) {
46
+ for (let x = 0; x < stride; x += 4) {
47
+ let block = 0;
48
+ for (let dy = 0; dy < 4; dy++) {
49
+ for (let dx = 0; dx < 4; dx++) {
50
+ const i = (y + dy) * stride + x + dx;
51
+ block += Math.abs(a.signature[i] - b.signature[i]);
52
+ }
53
+ }
54
+ difference += block;
55
+ local = Math.max(local, block / 16);
56
+ }
57
+ }
58
+ return { average: difference / a.signature.length, local };
59
+ }
60
+
61
+ function similar(a, b, detail = false, threshold = 4.5) {
62
+ const { average, local } = frameDifference(a, b);
63
+ return average < threshold && (!detail || local < threshold * 2);
64
+ }
65
+
66
+ export function selectFrames(samples, options) {
67
+ if (!samples.length) return [];
68
+ if (options.frameMode === "interval") {
69
+ const count = Math.min(samples.length, options.frameMaxCount);
70
+ return Array.from({length: count}, (_, i) => samples[count === 1 ? 0 : Math.round(i * (samples.length - 1) / (count - 1))]);
71
+ }
72
+ const duration = samples.at(-1).time;
73
+ const budget = Math.min(options.frameMaxCount, 12 + 4 * Math.ceil(Math.log2(Math.max(1, duration / 30))));
74
+ const activity = samples.map((sample, i) => {
75
+ const neighborhood = samples.slice(Math.max(0, i - 1), i + 2).map(other => other.change);
76
+ return Math.max(quantile(neighborhood, 0.5), sample.change * 0.55);
77
+ });
78
+ const baseline = quantile(activity, 0.25);
79
+ const floor = Math.max(0.5, baseline * 1.25);
80
+ const active = activity.filter(change => change > floor);
81
+ const selected = [samples[0]];
82
+ if (!active.length) return selected;
83
+ const ceiling = quantile(active, 0.90);
84
+ const strong = activity.map(change => Math.max(0, Math.min(ceiling, change) - floor));
85
+ const quiet = activity.map(change => Math.sqrt(Math.max(0, Math.min(ceiling, change) - baseline * 0.7)));
86
+ const strongTotal = strong.reduce((sum, change) => sum + change, 0);
87
+ const quietTotal = quiet.reduce((sum, change) => sum + change, 0);
88
+ const minGap = Math.min(0.85, duration / 24);
89
+
90
+ const cumulative = [];
91
+ let total = 0;
92
+ for (let i = 0; i < samples.length; i++) {
93
+ total += 0.65 * strong[i] / Math.max(strongTotal, 1e-9) + 0.35 * quiet[i] / Math.max(quietTotal, 1e-9);
94
+ cumulative.push(total);
95
+ }
96
+ function eligible(sample, detail = false) {
97
+ return selected.every(other => {
98
+ const distance = Math.abs(other.time - sample.time);
99
+ return distance >= minGap && (distance >= 4 || !similar(sample, other, detail, options.frameChangeThreshold));
100
+ });
101
+ }
102
+ function add(sample, detail = false) {
103
+ if (selected.length < budget && eligible(sample, detail)) selected.push(sample);
104
+ }
105
+
106
+ // Small follow-through changes are easily missed by a score averaged over the whole frame.
107
+ const cuts = samples.filter(({ index, change }) =>
108
+ change > Math.max(12, ceiling * 1.5)
109
+ && change > 1.6 * Math.max(samples[index - 1]?.change ?? 0, samples[index + 1]?.change ?? 0),
110
+ );
111
+ const transitions = [];
112
+ for (const [cutIndex, cut] of cuts.entries()) {
113
+ const nextCut = cuts[cutIndex + 1]?.time ?? Infinity;
114
+ for (let i = cut.index + 1; i < samples.length; i++) {
115
+ const after = samples[i];
116
+ if (after.time >= nextCut || after.time > cut.time + 1.8) break;
117
+ if (after.time < cut.time + 1.1) continue;
118
+ const { average, local } = frameDifference(cut, after);
119
+ if (average < 4.5 && local >= 9) {
120
+ transitions.push({ cut, after, score: local / (1 + average) });
121
+ }
122
+ }
123
+ }
124
+ transitions.sort((a, b) => b.score - a.score);
125
+ const followed = [];
126
+ for (const { cut, after } of transitions) {
127
+ if (followed.length >= Math.ceil(budget / 8)) break;
128
+ if (followed.some(other => Math.abs(other.time - cut.time) < 2)) continue;
129
+ add(cut, true);
130
+ add(after, true);
131
+ followed.push(cut);
132
+ }
133
+
134
+ let index = 0;
135
+ for (let i = 0; i < budget - 1; i++) {
136
+ const target = (i + 0.5) / (budget - 1);
137
+ while (index < samples.length - 1 && cumulative[index] < target) index++;
138
+ add(samples[index]);
139
+ }
140
+ while (selected.length < budget) {
141
+ let best;
142
+ let bestScore = 0;
143
+ for (const sample of samples) {
144
+ if (!eligible(sample)) continue;
145
+ const distance = Math.min(...selected.map(other => Math.abs(sample.time - other.time)));
146
+ const motion = Math.min(ceiling, activity[sample.index]);
147
+ const score = distance * Math.sqrt(Math.max(0, motion - baseline * 0.7));
148
+ if (score > bestScore) {
149
+ best = sample;
150
+ bestScore = score;
151
+ }
152
+ }
153
+ if (!best) break;
154
+ add(best);
155
+ }
156
+ return selected.sort((a, b) => a.time - b.time);
157
+ }
package/src/frames.js ADDED
@@ -0,0 +1,70 @@
1
+ import { mkdir, readdir, rename, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { originalTime } from "./timeline.js";
4
+ import { formatTime } from "./time-format.js";
5
+ import { createReadStream } from "node:fs";
6
+ import { rm } from "node:fs/promises";
7
+ import { describeSample, selectFrames } from "./frame-selection.js";
8
+ import { runFfmpeg } from "./ffmpeg.js";
9
+
10
+ export function frameFilter(timeline, options) {
11
+ const segments = timeline.segments;
12
+ const retained = segments.map((s) => `gte(t,${s.originalStart})*lt(t,${s.originalEnd})`).join("+");
13
+ let removed = 0;
14
+ const offsets = segments.map((segment) => {
15
+ const total = segment.originalStart - segment.compactStart;
16
+ const gap = total - removed; removed = total;
17
+ return gap > 0 ? `gte(T,${segment.originalStart})*${gap}` : null;
18
+ }).filter(Boolean);
19
+ const mapping = offsets.length ? `T-(${offsets.join("+")})` : "T";
20
+ const interval = Math.max(options.frameIntervalSeconds || (options.frameMode === "changes" ? 0.2 : Math.min(60, Math.max(0.2, timeline.compactSeconds / 20))), timeline.compactSeconds / 19999);
21
+ const filters = [`select='${retained}'`, `setpts='(${mapping})/TB'`, `select='isnan(prev_selected_t)+gte(t-prev_selected_t,${interval})'`];
22
+ return { filter: filters.join(","), intervalSeconds: interval };
23
+ }
24
+
25
+ export async function finishFrames(directory, source, timeline, settings, selected) {
26
+ const frames = [];
27
+ for (const name of (await readdir(directory)).filter((name) => /^sample-\d+\.png$/.test(name)).sort()) {
28
+ const compactSeconds = selected?.[frames.length]?.time ?? Number(name.match(/\d+/)[0]) / 1000;
29
+ const sourceSeconds = originalTime(compactSeconds, timeline);
30
+ const stem = `frame-${formatTime(sourceSeconds, { filename: true, milliseconds: true })}`;
31
+ const file = `${stem}-${String(frames.length + 1).padStart(4, "0")}.png`;
32
+ await rename(join(directory, name), join(directory, file));
33
+ frames.push({ file, sourceSeconds, compactSeconds });
34
+ }
35
+ const manifest = join(directory, "manifest.json");
36
+ await writeFile(manifest, JSON.stringify({ source, timestamps: "original", settings, frames }, null, 2) + "\n", { flag: "wx" });
37
+ return { directory, manifest, count: frames.length, status: "complete" };
38
+ }
39
+ export const createFrameDirectory = (directory) => mkdir(directory, { recursive: true });
40
+
41
+ export async function renderSelectedFrames(source, directory, timeline, options, scanFile, scanLog, settings) {
42
+ const times = [...scanLog.matchAll(/\bn:\s*\d+\s+pts:\s*-?\d+\s+pts_time:\s*([\d.e+-]+)/g)].map((match) => Number(match[1]));
43
+ const samples = [];
44
+ let frame = Buffer.alloc(96 * 96), previous = Buffer.alloc(96 * 96), offset = 0;
45
+ try {
46
+ for await (const chunk of createReadStream(scanFile)) {
47
+ let cursor = 0;
48
+ while (cursor < chunk.length) {
49
+ const copied = chunk.copy(frame, offset, cursor, cursor + frame.length - offset);
50
+ cursor += copied; offset += copied;
51
+ if (offset === frame.length) {
52
+ samples.push({ ...describeSample(frame, samples.length ? previous : frame), index: samples.length, time: times[samples.length] });
53
+ [previous, frame] = [frame, previous]; offset = 0;
54
+ }
55
+ }
56
+ }
57
+ if (offset || samples.length !== times.length || !samples.every((sample) => Number.isFinite(sample.time))) throw new Error("Incomplete frame scan timestamps.");
58
+ const selected = selectFrames(samples, options);
59
+ if (!selected.length) return { directory, count: 0, status: "no_frames" };
60
+ const script = join(directory, "render-filter.txt");
61
+ const indices = selected.map((sample) => `eq(n,${sample.index})`).join("+");
62
+ await writeFile(script, `[0:V:0]${settings.filter},select='${indices}',scale=-2:'min(ih,${options.frameMaxHeight})'[frames]`);
63
+ try {
64
+ await runFfmpeg(["-loglevel", "error", "-y", "-i", source, "-filter_complex_script", script, "-map", "[frames]", "-fps_mode", "vfr", "-enc_time_base", "1:1000", join(directory, "sample-%012d.png")], { signal: options.signal });
65
+ } finally { await rm(script, { force: true }); }
66
+ const files = (await readdir(directory)).filter((name) => /^sample-\d+\.png$/.test(name));
67
+ if (files.length !== selected.length) throw new Error("Selected frame count does not match extracted images.");
68
+ return await finishFrames(directory, source, timeline, { mode: options.frameMode, intervalSeconds: settings.intervalSeconds, maxCount: options.frameMaxCount, maxHeight: options.frameMaxHeight, changeThreshold: options.frameChangeThreshold, scannedFrames: samples.length }, selected);
69
+ } finally { await rm(scanFile, { force: true }); }
70
+ }
package/src/index.js ADDED
@@ -0,0 +1,91 @@
1
+ import { stat, mkdir, readFile, writeFile, readdir, rm, rename } from "node:fs/promises";
2
+ import { basename, resolve, join, parse } from "node:path";
3
+ import { tmpdir } from "node:os";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { loadConfig } from "./config.js";
6
+ import { timelineSchema } from "./options.js";
7
+ import { frameFilter, renderSelectedFrames } from "./frames.js";
8
+ import { buildTimeline } from "./timeline.js";
9
+ import { runFfmpeg } from "./ffmpeg.js";
10
+ export { defaults, optionsSchema, timelineSchema } from "./options.js";
11
+ export { loadConfig } from "./config.js";
12
+
13
+ const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
14
+ async function probe(input, signal) {
15
+ try {
16
+ const result = await runFfmpeg(["-loglevel","info","-i",input,"-map","0:V:0","-frames:v","1","-an","-f","null","-"], {signal});
17
+ const match = /Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/.exec(result.stderr);
18
+ if (match) return Number(match[1])*3600 + Number(match[2])*60 + Number(match[3]);
19
+ const decoded = await runFfmpeg(["-loglevel","error","-i",input,"-map","0:V:0","-an","-progress","pipe:1","-f","null","-"], {signal});
20
+ const times = [...decoded.stdout.matchAll(/^out_time_us=(\d+)/gm)].map(value=>Number(value[1])/1e6);
21
+ const duration = Math.max(...times);
22
+ if (!Number.isFinite(duration) || duration <= 0) throw new Error("Could not determine video duration.");
23
+ return duration;
24
+ } catch (error) {
25
+ if (/matches no streams|does not contain any stream/i.test(error.stderr ?? "")) throw new Error("No video stream was found in the input file.");
26
+ throw error;
27
+ }
28
+ }
29
+ async function cached(directory, identity) {
30
+ try {
31
+ const manifest = JSON.parse(await readFile(join(directory,"manifest.json"),"utf8"));
32
+ if (manifest.identity !== identity || manifest.status !== "complete" || !Array.isArray(manifest.frames)) return null;
33
+ for (const frame of manifest.frames) {
34
+ if (basename(frame.file) !== frame.file || !/^frame-[\d-]+\.png$/.test(frame.file)) return null;
35
+ const image = await stat(join(directory,frame.file));
36
+ if (!image.isFile() || !image.size) return null;
37
+ }
38
+ return {directory,manifest:join(directory,"manifest.json"),count:manifest.frames.length,status:manifest.frames.length?"complete":"no_frames",timestamps:"original",cached:true,log:join(directory,"ffmpeg.log"),settings:manifest.settings};
39
+ } catch { return null; }
40
+ }
41
+ export async function extractFrames(file, { outputDir, timeline, signal, envFile, ...overrides } = {}) {
42
+ const input = resolve(file), source = await stat(input,{bigint:true});
43
+ if (!source.isFile()) throw new Error("Expected a local video file.");
44
+ const options = loadConfig(overrides,{envFile});
45
+ const supplied = timeline === undefined ? null : timelineSchema.parse(timeline);
46
+ const {version} = JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8"));
47
+ const identity = hash({version,input,size:String(source.size),mtime:String(source.mtimeNs),options,timeline:supplied});
48
+ const stem = parse(input).name.replace(/[^\p{L}\p{N}._-]/gu,"_").slice(0,100) || "video";
49
+ const directory = outputDir ? resolve(outputDir) : join(tmpdir(),"extract-video-frames",stem+"--"+hash(input).slice(0,12),identity.slice(0,24));
50
+ if (directory === input) throw new Error("Output directory cannot be the source file.");
51
+ const hit = await cached(directory,identity);
52
+ if (hit) return hit;
53
+ signal?.throwIfAborted();
54
+ await mkdir(directory,{recursive:true});
55
+ const lock = join(directory,".lock");
56
+ try { await mkdir(lock); } catch(error) { if(error.code==="EEXIST")throw new Error("An extraction lock already exists in "+directory+". Check for an active process before removing a stale lock.");throw error; }
57
+ const log = join(directory,"ffmpeg.log"), marker = join(directory,"run.json");
58
+ const scanFile = join(directory,"scan.raw"), script = join(directory,"scan-filter.txt");
59
+ let owned = false;
60
+ try {
61
+ const secondHit = await cached(directory,identity);
62
+ if(secondHit)return secondHit;
63
+ let previous;
64
+ try{previous=JSON.parse(await readFile(marker,"utf8"));}catch{}
65
+ const entries = (await readdir(directory)).filter(name=>name!==".lock");
66
+ if(entries.length && previous?.identity!==identity)throw new Error("Output directory contains files from a different run. Choose an empty directory.");
67
+ owned = true;
68
+ for(const name of entries)if(/^(?:frame-[\d-]+\.png|sample-\d+\.png|scan\.raw|scan-filter\.txt|render-filter\.txt|manifest\.json)$/.test(name))await rm(join(directory,name),{force:true});
69
+ await writeFile(marker,JSON.stringify({identity,source:input,startedAt:new Date().toISOString()})+"\n");
70
+ const duration = await probe(input,signal);
71
+ const retained = supplied ?? buildTimeline(duration,[],0);
72
+ if(retained.originalSeconds > duration + 0.1)throw new Error("Timeline extends beyond the source video duration.");
73
+ const settings = frameFilter(retained,options);
74
+ await writeFile(script,`[0:V:0]${settings.filter},scale=96:96:force_original_aspect_ratio=decrease,format=gray,pad=96:96:(ow-iw)/2:(oh-ih)/2,showinfo=checksum=0[frames]`);
75
+ const scanned = await runFfmpeg(["-loglevel","info","-y","-i",input,"-filter_complex_script",script,"-map","[frames]","-fps_mode","passthrough","-threads","1","-f","rawvideo",scanFile],{signal});
76
+ await writeFile(log,scanned.stderr);
77
+ const result = await renderSelectedFrames(input,directory,retained,{...options,signal},scanFile,scanned.stderr,settings);
78
+ const manifest = result.count ? JSON.parse(await readFile(result.manifest,"utf8")) : {source:input,timestamps:"original",settings:options,frames:[]};
79
+ Object.assign(manifest,{identity,status:"complete",sourceIdentity:{size:String(source.size),mtimeNs:String(source.mtimeNs)},originalSeconds:retained.originalSeconds,retainedSeconds:retained.compactSeconds});
80
+ const temporary = join(directory,"manifest-"+randomUUID()+".tmp");
81
+ await writeFile(temporary,JSON.stringify(manifest,null,2)+"\n");
82
+ await rename(temporary,join(directory,"manifest.json"));
83
+ return {...result,manifest:join(directory,"manifest.json"),timestamps:"original",cached:false,log,settings:manifest.settings};
84
+ } catch(error) {
85
+ if (owned) await writeFile(log,error.stderr || error.stack || error.message).catch(()=>{});
86
+ throw error;
87
+ } finally {
88
+ if (owned) { await rm(script,{force:true});await rm(scanFile,{force:true}); }
89
+ await rm(lock,{recursive:true,force:true});
90
+ }
91
+ }
@@ -0,0 +1,70 @@
1
+ import { spawn, execFile } from "node:child_process";
2
+ import { resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ // Keep arguments and credentials on stdin/environment, outside the shell command.
6
+ export function resolveCliLaunch() {
7
+ const modulePath = fileURLToPath(import.meta.url);
8
+ const cachedPackage = /[\\/]_npx[\\/][^\\/]+[\\/]node_modules[\\/]mcp-extract-video-frames[\\/]/i.test(modulePath);
9
+ const npmExec = process.env.npm_command === "exec"
10
+ || (!process.env.npm_command && process.env.npm_lifecycle_event === "npx");
11
+ const useNpx = cachedPackage && npmExec;
12
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^npm_config_(package|call)$/i.test(key)));
13
+ if (process.env.EXTRACT_VIDEO_FRAMES_ENV_FILE) env.EXTRACT_VIDEO_FRAMES_ENV_FILE = resolve(process.env.EXTRACT_VIDEO_FRAMES_ENV_FILE);
14
+ return {
15
+ command: useNpx ? "npx" : process.execPath,
16
+ args: useNpx ? ["-y", "--prefer-online", "--package=mcp-extract-video-frames@latest", "--", "mcp-extract-video-frames"]
17
+ : [fileURLToPath(new URL("../../bin/cli.js", import.meta.url))],
18
+ cwd: process.cwd(), env, shell: useNpx && process.platform === "win32",
19
+ };
20
+ }
21
+
22
+ export function runCli(mode, request, { launch = resolveCliLaunch(), signal } = {}) {
23
+ return new Promise((done, reject) => {
24
+ if (!["--tool-manifest", "--execute-tool"].includes(mode)) throw new Error("Unsupported CLI mode.");
25
+ signal?.throwIfAborted();
26
+ const launchArgs = [...launch.args, mode];
27
+ const child = spawn(launch.shell ? launch.command + " " + launchArgs.join(" ") : launch.command, launch.shell ? [] : launchArgs, {
28
+ shell: launch.shell, cwd: launch.cwd, windowsHide: true,
29
+ stdio: ["pipe", "pipe", "inherit"], env: launch.env,
30
+ });
31
+ const abort = () => {
32
+ if (launch.shell && process.platform === "win32" && child.pid) {
33
+ execFile("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true }, () => {});
34
+ } else child.kill();
35
+ reject(new DOMException("CLI operation was cancelled.", "AbortError"));
36
+ };
37
+ signal?.addEventListener("abort", abort, { once: true });
38
+ if (signal?.aborted) abort();
39
+ let output = "";
40
+ child.stdout.setEncoding("utf8");
41
+ child.stdout.on("data", (chunk) => {
42
+ output += chunk;
43
+ if (output.length > 1024 * 1024) {
44
+ child.kill();
45
+ reject(new Error("CLI process response exceeded 1 MiB."));
46
+ }
47
+ });
48
+ child.on("error", reject);
49
+ child.stdin.on("error", reject);
50
+ child.once("close", () => signal?.removeEventListener("abort", abort));
51
+ child.on("close", (code, signal) => {
52
+ if (code !== 0) {
53
+ reject(new Error(`CLI process exited with ${signal ?? code}.`));
54
+ return;
55
+ }
56
+ try {
57
+ const result = JSON.parse(output);
58
+ if (mode === "--tool-manifest") {
59
+ if (result.protocol !== 1 || !Array.isArray(result.tools) || !result.serverInfo) throw new Error("Invalid tool manifest.");
60
+ } else if (!Array.isArray(result?.content)) {
61
+ throw new Error("Missing tool content.");
62
+ }
63
+ done(result);
64
+ } catch {
65
+ reject(new Error("CLI process returned an invalid response. Check npm connectivity and the published package version."));
66
+ }
67
+ });
68
+ child.stdin.end(request ? JSON.stringify(request) : undefined);
69
+ });
70
+ }
@@ -0,0 +1,86 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { z } from "zod";
6
+
7
+ const object = z.record(z.string(), z.json());
8
+ const manifestSchema = z.object({
9
+ protocol: z.literal(1),
10
+ serverInfo: z.object({ name: z.string().min(1), version: z.string().min(1), title: z.string().optional(), description: z.string().optional() }).passthrough(),
11
+ tools: z.array(z.object({
12
+ name: z.string().min(1), title: z.string().optional(), description: z.string().optional(),
13
+ inputSchema: object.refine((value) => value.type === "object"),
14
+ outputSchema: object.optional(),
15
+ annotations: z.object({ title: z.string().optional(), readOnlyHint: z.boolean().optional(), destructiveHint: z.boolean().optional(), idempotentHint: z.boolean().optional(), openWorldHint: z.boolean().optional() }).passthrough().optional(),
16
+ }).passthrough()).refine((tools) => new Set(tools.map((tool) => tool.name)).size === tools.length),
17
+ }).passthrough();
18
+
19
+ function validateManifest(value) {
20
+ z.json().parse(value);
21
+ manifestSchema.parse(value);
22
+ return value;
23
+ }
24
+
25
+ // Request/session-bound discovery is returned intact but cannot be replayed.
26
+ function hasRequestState(value) {
27
+ if (!value || typeof value !== "object") return false;
28
+ return Object.entries(value).some(([name, child]) =>
29
+ /(?:^|\/)(?:sessionId|session_id|progressToken|requestId|requestState|inputRequests|relatedTask|related-task)$/i.test(name)
30
+ || (name === "cacheScope" && child === "session")
31
+ || hasRequestState(child));
32
+ }
33
+
34
+ export function discoveryKey(launch, platform = process.platform) {
35
+ const normalize = (key) => platform === "win32" ? key.toUpperCase() : key;
36
+ const excluded = new Set(["CODEX_TOOL_CALL_ID", ...(launch.env.EXTRACT_VIDEO_FRAMES_DISCOVERY_CACHE_KEY_EXCLUDE ?? "").split(",").map((key) => key.trim()).filter(Boolean)].map(normalize));
37
+ const env = Object.entries(launch.env).map(([key, value]) => [normalize(key), value])
38
+ .filter(([key]) => !excluded.has(key) && !/^(?:CODEX_TOOL_CALL_ID$|PATH$|INIT_|NPM_)/i.test(key)).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
39
+ return createHash("sha256").update(JSON.stringify({ version: 1, command: launch.command, args: launch.args, cwd: launch.cwd, shell: launch.shell, env })).digest("hex");
40
+ }
41
+
42
+ export function createDiscoveryCache(launch, load, { directory = join(tmpdir(), "extract-video-frames", "discovery"), now = Date.now } = {}) {
43
+ const raw = launch.env.EXTRACT_VIDEO_FRAMES_DISCOVERY_CACHE_TTL_MS ?? "600000";
44
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Error("EXTRACT_VIDEO_FRAMES_DISCOVERY_CACHE_TTL_MS must be a nonnegative integer.");
45
+ const ttl = Number(raw), key = discoveryKey(launch), file = join(directory, key + ".json");
46
+ let pending, generation = 0;
47
+ const invalidate = async () => { generation++; await rm(file, { force: true }).catch(() => {}); };
48
+ return {
49
+ file, invalidate,
50
+ async get() {
51
+ if (ttl) {
52
+ try {
53
+ const bytes = await readFile(file);
54
+ if (bytes.length > 1024 * 1024) throw new Error("Oversized cache.");
55
+ const entry = JSON.parse(bytes);
56
+ if (entry.version !== 1 || entry.key !== key || !Number.isFinite(entry.createdAt) || !Number.isFinite(entry.expiresAt)
57
+ || entry.createdAt > now() || entry.expiresAt <= now() || entry.expiresAt - entry.createdAt > ttl) throw new Error("Expired cache.");
58
+ if (hasRequestState(entry.manifest)) throw new Error("Request-bound discovery.");
59
+ return validateManifest(entry.manifest);
60
+ } catch { /* Invalid or unavailable cache entries are misses. */ }
61
+ }
62
+ if (pending) return pending;
63
+ const revision = generation;
64
+ pending = (async () => {
65
+ const manifest = validateManifest(await load());
66
+ const serialized = JSON.stringify(manifest);
67
+ const privateValues = Object.entries(launch.env).filter(([name]) => /token|secret|password|session|CODEX_TOOL_CALL_ID/i.test(name))
68
+ .flatMap(([name, value]) => /EXTRACT_VIDEO_FRAMES_TOKENS/i.test(name)
69
+ ? [value, ...value.split(",").flatMap((entry) => entry.includes(":") ? [entry.slice(entry.indexOf(":") + 1)] : [entry])]
70
+ : [value]).filter((value) => value.length >= 8);
71
+ if (ttl && revision === generation && !hasRequestState(manifest) && !privateValues.some((value) => serialized.includes(value))) {
72
+ const temporary = file + "." + randomUUID() + ".tmp";
73
+ try {
74
+ await mkdir(directory, { recursive: true, mode: 0o700 });
75
+ const createdAt = now();
76
+ await writeFile(temporary, JSON.stringify({ version: 1, key, createdAt, expiresAt: createdAt + ttl, manifest }), { mode: 0o600 });
77
+ if (revision === generation) await rename(temporary, file);
78
+ } catch { /* Discovery remains available when the cache is unwritable. */ }
79
+ finally { await rm(temporary, { force: true }).catch(() => {}); }
80
+ }
81
+ return manifest;
82
+ })();
83
+ try { return await pending; } finally { pending = undefined; }
84
+ },
85
+ };
86
+ }
package/src/options.js ADDED
@@ -0,0 +1,34 @@
1
+ import { z } from "zod";
2
+
3
+ export const defaults = Object.freeze({
4
+ frameMode: "changes", frameIntervalSeconds: 0, frameMaxCount: 120,
5
+ frameMaxHeight: 1080, frameChangeThreshold: 4.5,
6
+ });
7
+ export const optionFields = {
8
+ frameMode: z.enum(["changes", "interval"]),
9
+ frameIntervalSeconds: z.number().min(0).max(3600),
10
+ frameMaxCount: z.int().min(1).max(1000),
11
+ frameMaxHeight: z.int().min(64).max(2160),
12
+ frameChangeThreshold: z.number().positive().max(255),
13
+ };
14
+ export const optionsSchema = z.strictObject(optionFields);
15
+ export const timelineSchema = z.object({
16
+ originalSeconds: z.number().positive(), compactSeconds: z.number().positive(),
17
+ segments: z.array(z.object({
18
+ originalStart: z.number().nonnegative(), originalEnd: z.number().positive(),
19
+ compactStart: z.number().nonnegative(), compactEnd: z.number().positive(),
20
+ })).min(1),
21
+ }).passthrough().superRefine((timeline, context) => {
22
+ let originalEnd = 0, compactEnd = 0;
23
+ for (const segment of timeline.segments) {
24
+ if (segment.originalStart < originalEnd || segment.originalEnd <= segment.originalStart
25
+ || Math.abs(segment.compactStart - compactEnd) > 1e-6
26
+ || Math.abs((segment.originalEnd - segment.originalStart) - (segment.compactEnd - segment.compactStart)) > 1e-6) {
27
+ context.addIssue({code:"custom",message:"Timeline segments must preserve duration and have contiguous compact times."});
28
+ }
29
+ originalEnd = segment.originalEnd; compactEnd = segment.compactEnd;
30
+ }
31
+ if (originalEnd > timeline.originalSeconds + 1e-6 || Math.abs(compactEnd - timeline.compactSeconds) > 1e-6) {
32
+ context.addIssue({code:"custom",message:"Timeline duration does not match its segments."});
33
+ }
34
+ });
@@ -0,0 +1,6 @@
1
+ export function formatTime(seconds, { filename = false, milliseconds = false } = {}) {
2
+ const value = milliseconds ? Math.round(Math.max(0, seconds) * 1000) : Math.floor(Math.max(0, seconds)) * 1000;
3
+ const parts = [Math.floor(value / 3600000), Math.floor(value / 60000) % 60, Math.floor(value / 1000) % 60].map((n) => String(n).padStart(2, "0"));
4
+ const text = parts.join(filename ? "-" : ":");
5
+ return milliseconds ? text + (filename ? "-" : ".") + String(value % 1000).padStart(3, "0") : text;
6
+ }
@@ -0,0 +1,27 @@
1
+ export function buildTimeline(duration, silences, margin = 0.3) {
2
+ if (!Number.isFinite(duration) || duration <= 0) throw new Error("Invalid audio duration.");
3
+ const segments = [];
4
+ let cursor = 0, compact = 0;
5
+ const append = (start, end) => {
6
+ if (end - start < 0.000001) return;
7
+ segments.push({ originalStart: start, originalEnd: end, compactStart: compact, compactEnd: compact + end - start });
8
+ compact += end - start;
9
+ };
10
+ for (const [start, end] of silences) {
11
+ const from = Math.max(cursor, Math.min(duration, start + margin));
12
+ const to = Math.max(from, Math.min(duration, end - margin));
13
+ if (to <= from) continue;
14
+ append(cursor, from); cursor = to;
15
+ }
16
+ append(cursor, duration);
17
+ return { originalSeconds: duration, compactSeconds: compact, segments, timestamps: "original" };
18
+ }
19
+
20
+ export function originalTime(time, timeline, boundary = "start") {
21
+ if (!Number.isFinite(time) || time < 0 || !timeline.segments.length) throw new Error("Invalid compact timestamp.");
22
+ const tolerance = 0.1;
23
+ if (time > timeline.compactSeconds + tolerance) throw new Error("Transcript timestamp exceeds the prepared audio duration.");
24
+ const clipped = Math.min(time, timeline.compactSeconds);
25
+ const segment = timeline.segments.find((entry) => boundary === "end" ? clipped <= entry.compactEnd : clipped < entry.compactEnd) ?? timeline.segments.at(-1);
26
+ return segment.originalStart + Math.max(0, clipped - segment.compactStart);
27
+ }
package/src/tools.js ADDED
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+ import { readFile } from "node:fs/promises";
3
+ import { loadConfig } from "./config.js";
4
+ import { optionFields, timelineSchema } from "./options.js";
5
+ import { extractFrames } from "./index.js";
6
+
7
+ function tool(defaults){
8
+ return {
9
+ name:"extract_frames",
10
+ description:"Extract PNG screenshots from a local video for slide references, illustrated notes, or later review. Adaptive selection favors visual changes across the entire retained video. Images are not interpreted. Returns an output directory, manifest, and frame count. Candidate sampling can miss brief changes.",
11
+ inputSchema:z.strictObject({
12
+ file:z.string().min(1).describe("Absolute path to a local video file."),
13
+ outputDir:z.string().min(1).optional().describe("Optional output directory; defaults to an identifiable folder in the operating system temporary directory."),
14
+ timeline:timelineSchema.optional().describe("Optional retained-interval timeline. Frames are sampled from retained source intervals and named using original recording times."),
15
+ frameMode:optionFields.frameMode.optional().describe(`Configured default: ${defaults.frameMode}. changes uses an adaptive budget and visual deduplication; interval spreads images evenly.`),
16
+ frameIntervalSeconds:optionFields.frameIntervalSeconds.optional().describe(`Configured default: ${defaults.frameIntervalSeconds}. Candidate spacing in seconds; 0 is automatic.`),
17
+ frameMaxCount:optionFields.frameMaxCount.optional().describe(`Configured default: ${defaults.frameMaxCount}. Maximum images across the whole retained video, not a cutoff at the beginning.`),
18
+ frameMaxHeight:optionFields.frameMaxHeight.optional().describe(`Configured default: ${defaults.frameMaxHeight}. Maximum PNG height without upscaling.`),
19
+ frameChangeThreshold:optionFields.frameChangeThreshold.optional().describe(`Configured default: ${defaults.frameChangeThreshold}. Nearby grayscale similarity threshold; higher treats more images as duplicates.`),
20
+ }),
21
+ };
22
+ }
23
+ export async function getToolManifest(){
24
+ const {name,version,description}=JSON.parse(await readFile(new URL("../package.json",import.meta.url),"utf8"));
25
+ const definition=tool(loadConfig());
26
+ return {protocol:1,serverInfo:{name,version,title:"Extract Video Frames",description},tools:[{...definition,inputSchema:z.toJSONSchema(definition.inputSchema,{target:"draft-7"})}]};
27
+ }
28
+ export async function executeTool(name,args){
29
+ if(name!=="extract_frames")throw new Error("Unknown tool: "+name);
30
+ const {file,...options}=tool(loadConfig()).inputSchema.parse(args);
31
+ try{const result=await extractFrames(file,options);return{content:[{type:"text",text:JSON.stringify(result)}],structuredContent:result};}
32
+ catch(error){return{isError:true,content:[{type:"text",text:JSON.stringify({message:error.message})}]};}
33
+ }