@ash_j1997/ffmpeg-mcp-server 0.4.2 → 0.5.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.
@@ -2,23 +2,102 @@ import { spawn } from "node:child_process";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  /**
5
- * Execute a command using spawn, capturing stdout and stderr.
5
+ * Execute a command using spawn, capturing stdout and stderr with cancellation and timeout support.
6
6
  */
7
- export async function runCommand(command, args) {
7
+ export async function runCommand(command, args, options) {
8
+ if (options?.signal?.aborted) {
9
+ throw new Error(`Command cancelled before launch: ${command}`);
10
+ }
8
11
  return new Promise((resolve, reject) => {
9
12
  const child = spawn(command, args);
10
13
  let stdout = "";
11
14
  let stderr = "";
15
+ let stdoutBuffer = "";
16
+ let stderrBuffer = "";
17
+ let timer = null;
18
+ let isCancelled = false;
19
+ const cleanup = () => {
20
+ if (timer) {
21
+ clearTimeout(timer);
22
+ timer = null;
23
+ }
24
+ if (options?.signal) {
25
+ options.signal.removeEventListener("abort", onAbort);
26
+ }
27
+ };
28
+ const onAbort = () => {
29
+ isCancelled = true;
30
+ try {
31
+ child.kill("SIGTERM");
32
+ setTimeout(() => {
33
+ try {
34
+ child.kill("SIGKILL");
35
+ }
36
+ catch { }
37
+ }, 1500);
38
+ }
39
+ catch { }
40
+ };
41
+ if (options?.signal) {
42
+ options.signal.addEventListener("abort", onAbort, { once: true });
43
+ }
44
+ if (options?.timeoutMs && options.timeoutMs > 0) {
45
+ timer = setTimeout(() => {
46
+ isCancelled = true;
47
+ try {
48
+ child.kill("SIGTERM");
49
+ setTimeout(() => {
50
+ try {
51
+ child.kill("SIGKILL");
52
+ }
53
+ catch { }
54
+ }, 1500);
55
+ }
56
+ catch { }
57
+ cleanup();
58
+ reject(new Error(`Command timed out after ${options.timeoutMs}ms: ${command}`));
59
+ }, options.timeoutMs);
60
+ }
12
61
  child.stdout.on("data", (data) => {
13
- stdout += data.toString();
62
+ const str = data.toString();
63
+ stdout += str;
64
+ if (options?.onStdoutLine) {
65
+ stdoutBuffer += str;
66
+ const lines = stdoutBuffer.split(/\r?\n/);
67
+ stdoutBuffer = lines.pop() || "";
68
+ for (const line of lines) {
69
+ options.onStdoutLine(line);
70
+ }
71
+ }
14
72
  });
15
73
  child.stderr.on("data", (data) => {
16
- stderr += data.toString();
74
+ const str = data.toString();
75
+ stderr += str;
76
+ if (options?.onStderrLine) {
77
+ stderrBuffer += str;
78
+ const lines = stderrBuffer.split(/\r?\n/);
79
+ stderrBuffer = lines.pop() || "";
80
+ for (const line of lines) {
81
+ options.onStderrLine(line);
82
+ }
83
+ }
17
84
  });
18
85
  child.on("error", (error) => {
86
+ cleanup();
19
87
  reject(new Error(`Failed to launch ${command}: ${error.message}`));
20
88
  });
21
89
  child.on("close", (code) => {
90
+ cleanup();
91
+ if (options?.onStdoutLine && stdoutBuffer.length > 0) {
92
+ options.onStdoutLine(stdoutBuffer);
93
+ }
94
+ if (options?.onStderrLine && stderrBuffer.length > 0) {
95
+ options.onStderrLine(stderrBuffer);
96
+ }
97
+ if (isCancelled || options?.signal?.aborted) {
98
+ reject(new Error(`FFmpeg operation was cancelled by client.`));
99
+ return;
100
+ }
22
101
  const exitCode = code ?? 0;
23
102
  if (exitCode !== 0) {
24
103
  reject(new Error(`${command} exited with code ${exitCode}:\n${stderr || stdout}`));
@@ -30,14 +109,66 @@ export async function runCommand(command, args) {
30
109
  });
31
110
  }
32
111
  /**
33
- * Convenience wrapper for running ffmpeg commands with execution timing.
112
+ * Convenience wrapper for running ffmpeg commands with execution timing,
113
+ * progress tracking (-progress pipe:1), and cancellation.
34
114
  */
35
- export async function runFfmpeg(args) {
115
+ export async function runFfmpeg(args, options) {
36
116
  const startTime = Date.now();
37
- const res = await runCommand("ffmpeg", args);
117
+ const effectiveArgs = [...args];
118
+ let currentProgress = {};
119
+ const onStdoutLine = (line) => {
120
+ const trimmed = line.trim();
121
+ if (!trimmed)
122
+ return;
123
+ const [key, value] = trimmed.split("=");
124
+ if (!key || value === undefined)
125
+ return;
126
+ if (key === "frame") {
127
+ const frameNum = parseInt(value, 10);
128
+ if (!isNaN(frameNum))
129
+ currentProgress.frame = frameNum;
130
+ }
131
+ else if (key === "fps") {
132
+ const fpsNum = parseFloat(value);
133
+ if (!isNaN(fpsNum))
134
+ currentProgress.fps = fpsNum;
135
+ }
136
+ else if (key === "speed") {
137
+ currentProgress.speed = value.trim();
138
+ }
139
+ else if (key === "out_time_us") {
140
+ const us = parseInt(value, 10);
141
+ if (!isNaN(us)) {
142
+ currentProgress.timeSeconds = Number((us / 1_000_000).toFixed(2));
143
+ if (options?.expectedDurationSeconds && options.expectedDurationSeconds > 0) {
144
+ const pct = Math.min(100, Math.max(0, Math.round((currentProgress.timeSeconds / options.expectedDurationSeconds) * 100)));
145
+ currentProgress.percent = pct;
146
+ }
147
+ }
148
+ }
149
+ else if (key === "progress") {
150
+ if (value === "end") {
151
+ currentProgress.isEnd = true;
152
+ if (options?.expectedDurationSeconds) {
153
+ currentProgress.percent = 100;
154
+ }
155
+ }
156
+ if (options?.onProgress) {
157
+ options.onProgress({ ...currentProgress });
158
+ }
159
+ }
160
+ };
161
+ // If progress callback provided, inject -progress pipe:1 before output arguments
162
+ if (options?.onProgress && !effectiveArgs.includes("-progress")) {
163
+ effectiveArgs.unshift("-progress", "pipe:1");
164
+ }
165
+ const res = await runCommand("ffmpeg", effectiveArgs, {
166
+ ...options,
167
+ onStdoutLine: options?.onProgress ? onStdoutLine : options?.onStdoutLine,
168
+ });
38
169
  const durationSeconds = Number(((Date.now() - startTime) / 1000).toFixed(2));
39
170
  return {
40
- command: `ffmpeg ${args.join(" ")}`,
171
+ command: `ffmpeg ${effectiveArgs.join(" ")}`,
41
172
  stdout: res.stdout,
42
173
  stderr: res.stderr,
43
174
  durationSeconds,
@@ -2,44 +2,166 @@ import os from "node:os";
2
2
  import { runCommand } from "./exec.js";
3
3
  let cachedInfo = null;
4
4
  /**
5
- * Detects if hardware-accelerated video encoders (Apple Silicon VideoToolbox) are available.
5
+ * Detects available hardware-accelerated video encoders across macOS, Linux, and Windows.
6
+ * Supports Apple Silicon (VideoToolbox), NVIDIA (NVENC), Intel (QuickSync), AMD (AMF), and Linux (VAAPI).
6
7
  */
7
8
  export async function detectHwAccel() {
8
9
  if (cachedInfo) {
9
10
  return cachedInfo;
10
11
  }
11
- const isDarwin = os.platform() === "darwin";
12
- if (!isDarwin) {
13
- cachedInfo = {
14
- isAvailable: false,
15
- h264Encoder: "libx264",
16
- hevcEncoder: "libx265",
17
- hardwareType: "none",
18
- };
19
- return cachedInfo;
20
- }
12
+ const detectedH264 = [];
13
+ const detectedHevc = [];
14
+ const detectedTypes = [];
21
15
  try {
22
16
  const res = await runCommand("ffmpeg", ["-encoders"]);
23
- const hasVtH264 = res.stdout.includes("h264_videotoolbox") || res.stderr.includes("h264_videotoolbox");
24
- const hasVtHevc = res.stdout.includes("hevc_videotoolbox") || res.stderr.includes("hevc_videotoolbox");
25
- if (hasVtH264) {
26
- cachedInfo = {
27
- isAvailable: true,
28
- h264Encoder: "h264_videotoolbox",
29
- hevcEncoder: hasVtHevc ? "hevc_videotoolbox" : "libx265",
30
- hardwareType: "videotoolbox",
31
- };
32
- return cachedInfo;
17
+ const text = `${res.stdout}\n${res.stderr}`;
18
+ const check = (enc) => text.includes(` ${enc} `) || text.includes(` ${enc}\n`);
19
+ if (check("h264_videotoolbox")) {
20
+ detectedH264.push("h264_videotoolbox");
21
+ if (!detectedTypes.includes("videotoolbox"))
22
+ detectedTypes.push("videotoolbox");
23
+ }
24
+ if (check("hevc_videotoolbox")) {
25
+ detectedHevc.push("hevc_videotoolbox");
26
+ if (!detectedTypes.includes("videotoolbox"))
27
+ detectedTypes.push("videotoolbox");
28
+ }
29
+ if (check("h264_nvenc")) {
30
+ detectedH264.push("h264_nvenc");
31
+ if (!detectedTypes.includes("nvenc"))
32
+ detectedTypes.push("nvenc");
33
+ }
34
+ if (check("hevc_nvenc")) {
35
+ detectedHevc.push("hevc_nvenc");
36
+ if (!detectedTypes.includes("nvenc"))
37
+ detectedTypes.push("nvenc");
38
+ }
39
+ if (check("h264_qsv")) {
40
+ detectedH264.push("h264_qsv");
41
+ if (!detectedTypes.includes("qsv"))
42
+ detectedTypes.push("qsv");
43
+ }
44
+ if (check("hevc_qsv")) {
45
+ detectedHevc.push("hevc_qsv");
46
+ if (!detectedTypes.includes("qsv"))
47
+ detectedTypes.push("qsv");
48
+ }
49
+ if (check("h264_amf")) {
50
+ detectedH264.push("h264_amf");
51
+ if (!detectedTypes.includes("amf"))
52
+ detectedTypes.push("amf");
53
+ }
54
+ if (check("hevc_amf")) {
55
+ detectedHevc.push("hevc_amf");
56
+ if (!detectedTypes.includes("amf"))
57
+ detectedTypes.push("amf");
58
+ }
59
+ if (check("h264_vaapi")) {
60
+ detectedH264.push("h264_vaapi");
61
+ if (!detectedTypes.includes("vaapi"))
62
+ detectedTypes.push("vaapi");
63
+ }
64
+ if (check("hevc_vaapi")) {
65
+ detectedHevc.push("hevc_vaapi");
66
+ if (!detectedTypes.includes("vaapi"))
67
+ detectedTypes.push("vaapi");
33
68
  }
34
69
  }
35
70
  catch {
36
- // Fallback if ffprobe/ffmpeg check fails
71
+ // If probing fails, fall back to software
72
+ }
73
+ const isDarwin = os.platform() === "darwin";
74
+ let chosenType = "none";
75
+ let h264Encoder = "libx264";
76
+ let hevcEncoder = "libx265";
77
+ if (isDarwin && detectedTypes.includes("videotoolbox")) {
78
+ chosenType = "videotoolbox";
79
+ h264Encoder = "h264_videotoolbox";
80
+ hevcEncoder = detectedHevc.includes("hevc_videotoolbox") ? "hevc_videotoolbox" : "libx265";
81
+ }
82
+ else if (detectedTypes.includes("nvenc")) {
83
+ chosenType = "nvenc";
84
+ h264Encoder = "h264_nvenc";
85
+ hevcEncoder = detectedHevc.includes("hevc_nvenc") ? "hevc_nvenc" : "libx265";
86
+ }
87
+ else if (detectedTypes.includes("qsv")) {
88
+ chosenType = "qsv";
89
+ h264Encoder = "h264_qsv";
90
+ hevcEncoder = detectedHevc.includes("hevc_qsv") ? "hevc_qsv" : "libx265";
91
+ }
92
+ else if (detectedTypes.includes("amf")) {
93
+ chosenType = "amf";
94
+ h264Encoder = "h264_amf";
95
+ hevcEncoder = detectedHevc.includes("hevc_amf") ? "hevc_amf" : "libx265";
96
+ }
97
+ else if (detectedTypes.includes("vaapi")) {
98
+ chosenType = "vaapi";
99
+ h264Encoder = "h264_vaapi";
100
+ hevcEncoder = detectedHevc.includes("hevc_vaapi") ? "hevc_vaapi" : "libx265";
101
+ }
102
+ else if (detectedTypes.length > 0) {
103
+ chosenType = detectedTypes[0];
104
+ h264Encoder = detectedH264[0] || "libx264";
105
+ hevcEncoder = detectedHevc[0] || "libx265";
37
106
  }
38
107
  cachedInfo = {
39
- isAvailable: false,
40
- h264Encoder: "libx264",
41
- hevcEncoder: "libx265",
42
- hardwareType: "none",
108
+ isAvailable: chosenType !== "none",
109
+ h264Encoder,
110
+ hevcEncoder,
111
+ hardwareType: chosenType,
112
+ availableTypes: detectedTypes,
113
+ encoders: {
114
+ h264: detectedH264,
115
+ hevc: detectedHevc,
116
+ },
43
117
  };
44
118
  return cachedInfo;
45
119
  }
120
+ /**
121
+ * Helper to generate video encoder command line arguments for either hardware or software encoding.
122
+ */
123
+ export function getVideoEncoderArgs(hwInfo, options) {
124
+ const useHw = options?.useHardware !== false && hwInfo.isAvailable;
125
+ if (useHw) {
126
+ return {
127
+ encoder: hwInfo.h264Encoder,
128
+ isHardware: true,
129
+ args: ["-c:v", hwInfo.h264Encoder, "-b:v", options?.bitrate || "4M"],
130
+ };
131
+ }
132
+ return {
133
+ encoder: "libx264",
134
+ isHardware: false,
135
+ args: [
136
+ "-c:v",
137
+ "libx264",
138
+ "-crf",
139
+ String(options?.crf ?? 22),
140
+ "-preset",
141
+ options?.preset || "medium",
142
+ ],
143
+ };
144
+ }
145
+ /**
146
+ * Check if a specific FFmpeg filter is supported by the local FFmpeg build.
147
+ */
148
+ let cachedFilters = null;
149
+ export async function hasFilter(filterName) {
150
+ if (!cachedFilters) {
151
+ try {
152
+ const res = await runCommand("ffmpeg", ["-filters"]);
153
+ const lines = `${res.stdout}\n${res.stderr}`.split(/\r?\n/);
154
+ cachedFilters = new Set();
155
+ for (const line of lines) {
156
+ const match = line.match(/^\s*[TSC.]{2}\s+([a-zA-Z0-9_]+)/);
157
+ if (match) {
158
+ cachedFilters.add(match[1]);
159
+ }
160
+ }
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ }
166
+ return cachedFilters.has(filterName);
167
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ash_j1997/ffmpeg-mcp-server",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "MCP server for FFmpeg and FFprobe media processing",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -12,6 +12,7 @@
12
12
  ],
13
13
  "scripts": {
14
14
  "build": "tsc",
15
+ "test": "npm run build && node test-tools.js",
15
16
  "start": "node dist/index.js",
16
17
  "prepare": "npm run build"
17
18
  },