@ash_j1997/ffmpeg-mcp-server 0.0.0-stage → 0.4.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
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,117 @@
1
- # Temporary Holding Version
1
+ # ffmpeg-mcp-server
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
+ [![CI](https://github.com/Ashutos1997/ffmpeg-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/Ashutos1997/ffmpeg-mcp-server/actions) [![Release](https://img.shields.io/github/v/release/Ashutos1997/ffmpeg-mcp-server?color=blue)](https://github.com/Ashutos1997/ffmpeg-mcp-server/releases) [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](LICENSE) [![Glama](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server/badge)](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server)
4
+
5
+ A Model Context Protocol (MCP) server that gives AI tools access to FFmpeg and FFprobe to process video and audio locally.
6
+
7
+ Supports Apple Silicon hardware encoding and returns image previews directly to models with vision.
8
+
9
+ ---
10
+
11
+ ## Why This Exists
12
+
13
+ When AI agents process media, they often hallucinate invalid flags, syntax errors, or incompatible pixel formats.
14
+
15
+ This server provides 13 typed tools using Zod schemas. The AI passes parameters (such as `{ inputPath: "video.mov", preset: "web_mp4" }`), and the server runs the valid FFmpeg command locally.
16
+
17
+ ---
18
+
19
+ ## Key Features
20
+
21
+ * **Hardware Encoding:** Uses VideoToolbox on macOS for faster exports with low CPU usage.
22
+ * **Image Responses:** Returns base64 images so vision models can inspect thumbnails and waveforms.
23
+ * **Social Formats:** Reformats landscape video to 9:16 vertical video with blurred background padding.
24
+ * **Split Screen:** Stacks two videos top-and-bottom for Reels and TikTok, with optional subtitles and audio mixing.
25
+ * **Silence Removal:** Detects and trims pauses from speech recordings.
26
+
27
+ ---
28
+
29
+ ## Included Tools (13 Total)
30
+
31
+ | Tool | Description | Key Parameters |
32
+ | :--- | :--- | :--- |
33
+ | **`media_probe`** | Inspects media files with ffprobe. Returns metadata, streams, codecs, resolution, and duration as JSON. | `inputPath` |
34
+ | **`media_convert`** | Converts video and audio formats. Includes presets for web MP4, WebM, and animated GIF. | `inputPath`, `outputPath`, `preset`, `crf`, `resolution`, `fps`, `hardwareAcceleration` |
35
+ | **`trim_media`** | Cuts a segment from a video or audio file using stream copy or re-encoding. | `inputPath`, `outputPath`, `startTime`, `endTime`, `duration`, `accurateReencode` |
36
+ | **`extract_audio`** | Rips audio tracks from video. Includes a 16kHz mono WAV preset for Whisper speech recognition. | `inputPath`, `outputPath`, `format`, `bitrate` |
37
+ | **`extract_thumbnail`** | Captures a still image at a timestamp or midpoint. Returns base64 image data for vision models. | `inputPath`, `outputPath`, `timestamp`, `resolution`, `includeBase64` |
38
+ | **`compress_video`** | Compresses video to fit target sizes (such as GitHub PRs under 10MB or Discord under 25MB). | `inputPath`, `outputPath`, `targetSizeMB`, `preset`, `crf`, `maxWidth`, `hardwareAcceleration` |
39
+ | **`reformat_aspect_ratio`** | Changes video ratio to 9:16 vertical, 1:1 square, or 4:5 portrait with blurred borders or center crop. | `inputPath`, `outputPath`, `targetRatio`, `mode`, `blurAmount`, `padColor` |
40
+ | **`create_split_screen`** | Stacks two videos top-and-bottom (9:16 Reels/TikTok) or side-by-side with audio mixing and subtitles. | `firstVideoPath`, `secondVideoPath`, `outputPath`, `layout`, `audioSource`, `subtitlesPath` |
41
+ | **`trim_silence`** | Detects and removes silent pauses from recordings. Reports duration and seconds saved. | `inputPath`, `outputPath`, `mode`, `thresholdDb`, `minDurationSeconds` |
42
+ | **`concat_media`** | Joins multiple video or audio files in order using stream copy or re-encoding. | `inputPaths`, `outputPath`, `mode` |
43
+ | **`generate_waveform`** | Generates a PNG waveform image. Returns base64 image data for vision models. | `inputPath`, `outputPath`, `width`, `height`, `color`, `scale`, `includeBase64` |
44
+ | **`add_subtitles`** | Embeds SRT or VTT subtitle tracks into video files without re-encoding video. | `videoPath`, `subtitlesPath`, `outputPath`, `language`, `title` |
45
+ | **`change_speed`** | Adjusts playback speed (such as 2x fast forward or 0.5x slow motion) with pitch correction. | `inputPath`, `outputPath`, `speed`, `muteAudio` |
46
+
47
+ ---
48
+
49
+ ## Requirements
50
+
51
+ * **Node.js** >= 18.0.0
52
+ * **FFmpeg & FFprobe** installed locally:
53
+ * **macOS:** `brew install ffmpeg`
54
+ * **Linux (Ubuntu/Debian):** `sudo apt update && sudo apt install ffmpeg`
55
+ * **Windows:** `winget install Gyan.FFmpeg` or `choco install ffmpeg`
56
+
57
+ ---
58
+
59
+ ## Installation
60
+
61
+ ### Antigravity
62
+
63
+ Add to `~/.gemini/config/mcp_config.json`:
64
+
65
+ ```json
66
+ {
67
+ "mcpServers": {
68
+ "ffmpeg": {
69
+ "command": "node",
70
+ "args": ["/Users/ashj/Desktop/Projects/ffmpeg-mcp-server/dist/index.js"]
71
+ }
72
+ }
73
+ }
74
+ ```
75
+
76
+ ### Claude Desktop
77
+
78
+ Add to `claude_desktop_config.json`:
79
+
80
+ * **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
81
+ * **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "ffmpeg": {
87
+ "command": "node",
88
+ "args": ["/Users/ashj/Desktop/Projects/ffmpeg-mcp-server/dist/index.js"]
89
+ }
90
+ }
91
+ }
92
+ ```
93
+
94
+ ---
95
+
96
+ ## Local Development
97
+
98
+ 1. **Install dependencies:**
99
+ ```bash
100
+ npm install
101
+ ```
102
+
103
+ 2. **Build TypeScript:**
104
+ ```bash
105
+ npm run build
106
+ ```
107
+
108
+ 3. **Run tests:**
109
+ ```bash
110
+ node test-tools.js
111
+ ```
112
+
113
+ ---
114
+
115
+ ## License
116
+
117
+ MIT © [Ashutos1997](https://github.com/Ashutos1997)
package/dist/index.js ADDED
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+ import { probeMedia } from "./tools/probe.js";
6
+ import { convertMedia } from "./tools/convert.js";
7
+ import { trimMedia } from "./tools/trim.js";
8
+ import { extractAudio } from "./tools/audio.js";
9
+ import { extractThumbnail } from "./tools/thumbnail.js";
10
+ import { compressMedia, compressMediaSchema } from "./tools/compress.js";
11
+ import { concatMedia, concatMediaSchema } from "./tools/concat.js";
12
+ import { generateWaveform, generateWaveformSchema } from "./tools/waveform.js";
13
+ import { addSubtitles, addSubtitlesSchema } from "./tools/subtitles.js";
14
+ import { changeSpeed, changeSpeedSchema } from "./tools/speed.js";
15
+ import { reformatAspectRatio, reformatAspectSchema } from "./tools/reformat.js";
16
+ import { trimSilence, trimSilenceSchema } from "./tools/silence.js";
17
+ import { createSplitScreen, splitScreenSchema } from "./tools/split.js";
18
+ const server = new McpServer({
19
+ name: "ffmpeg-mcp-server",
20
+ version: "0.4.0",
21
+ });
22
+ // Tool 1: Probe Media
23
+ server.tool("media_probe", "Inspect audio and video files with ffprobe. Returns container metadata, stream details, codecs, resolution, bitrate, and duration as JSON.", {
24
+ inputPath: z.string().describe("Path to the media file to inspect (e.g. './video.mp4')"),
25
+ }, async ({ inputPath }) => {
26
+ try {
27
+ const result = await probeMedia(inputPath);
28
+ return {
29
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
30
+ };
31
+ }
32
+ catch (err) {
33
+ return {
34
+ isError: true,
35
+ content: [{ type: "text", text: `Error probing media: ${err.message}` }],
36
+ };
37
+ }
38
+ });
39
+ // Tool 2: Convert Media
40
+ server.tool("media_convert", "Convert video and audio files between formats. Includes presets for web MP4 (H.264/AAC), WebM (VP9/Opus), and animated GIF. Supports Apple Silicon hardware encoding.", {
41
+ inputPath: z.string().describe("Path to the source media file to convert"),
42
+ outputPath: z.string().describe("Destination path for the converted file (e.g. ./output.mp4, ./output.webm, ./animation.gif)"),
43
+ preset: z
44
+ .enum(["web_mp4", "webm", "gif", "auto"])
45
+ .optional()
46
+ .describe("Encoding preset: 'web_mp4' for browser playback, 'webm' for WebM video, 'gif' for animated GIF, or 'auto'. Default: 'auto'."),
47
+ crf: z
48
+ .number()
49
+ .min(0)
50
+ .max(51)
51
+ .optional()
52
+ .describe("Quality factor from 0 to 51. Lower numbers mean higher quality. Default: 23 for MP4, 30 for WebM."),
53
+ resolution: z
54
+ .string()
55
+ .optional()
56
+ .describe("Target size formatted as 'WIDTHxHEIGHT', such as '1920x1080' or '1280x720'"),
57
+ fps: z
58
+ .number()
59
+ .positive()
60
+ .optional()
61
+ .describe("Target frame rate in frames per second, such as 30, 60, or 15"),
62
+ hardwareAcceleration: z
63
+ .boolean()
64
+ .optional()
65
+ .describe("Use Apple Silicon VideoToolbox encoding when available. Default: true."),
66
+ }, async (args) => {
67
+ try {
68
+ const result = await convertMedia(args);
69
+ return {
70
+ content: [
71
+ {
72
+ type: "text",
73
+ text: `Successfully converted media:\nOutput: ${result.outputPath}\nHardware Accelerated: ${result.hardwareAccelerated}\nCommand: ${result.commandExecuted}`,
74
+ },
75
+ ],
76
+ };
77
+ }
78
+ catch (err) {
79
+ return {
80
+ isError: true,
81
+ content: [{ type: "text", text: `Error converting media: ${err.message}` }],
82
+ };
83
+ }
84
+ });
85
+ // Tool 3: Trim Media
86
+ server.tool("trim_media", "Cut a segment from a video or audio file. Uses stream copy without re-encoding by default, or re-encodes when accurate cuts are needed.", {
87
+ inputPath: z.string().describe("Path to the source media file to cut."),
88
+ outputPath: z.string().describe("Destination path for the trimmed output file (e.g. './clip.mp4')."),
89
+ startTime: z.string().describe("Start timestamp formatted as 'HH:MM:SS' (e.g. '00:01:30') or seconds (e.g. '90')."),
90
+ endTime: z.string().optional().describe("Optional end timestamp formatted as 'HH:MM:SS' or seconds. Do not combine with duration."),
91
+ duration: z.string().optional().describe("Optional duration in seconds from startTime (e.g. '30'). If neither endTime nor duration is set, trims to end of file."),
92
+ accurateReencode: z
93
+ .boolean()
94
+ .optional()
95
+ .describe("Re-encode video for cuts between keyframes. Default: false (uses fast stream copy)."),
96
+ }, async (args) => {
97
+ try {
98
+ const result = await trimMedia(args);
99
+ return {
100
+ content: [
101
+ {
102
+ type: "text",
103
+ text: `Successfully trimmed media:\nOutput: ${result.outputPath}\nCommand: ${result.commandExecuted}`,
104
+ },
105
+ ],
106
+ };
107
+ }
108
+ catch (err) {
109
+ return {
110
+ isError: true,
111
+ content: [{ type: "text", text: `Error trimming media: ${err.message}` }],
112
+ };
113
+ }
114
+ });
115
+ // Tool 4: Extract Audio
116
+ server.tool("extract_audio", "Extract an audio track from a video file into a standalone audio file. Supports the 'whisper_wav' preset (16kHz mono WAV) for speech recognition models, plus MP3, AAC, FLAC, and stream copy.", {
117
+ inputPath: z.string().describe("Path to the source video or audio file."),
118
+ outputPath: z.string().describe("Destination path for the output audio file (e.g. './extracted.wav' or './audio.mp3')."),
119
+ format: z
120
+ .enum(["whisper_wav", "mp3", "aac", "flac", "copy"])
121
+ .optional()
122
+ .describe("Audio format: 'whisper_wav' (16kHz mono WAV for Whisper), 'mp3', 'aac', 'flac', or 'copy' (extract without re-encoding)."),
123
+ bitrate: z.string().optional().describe("Target audio bitrate for MP3 or AAC (e.g. '128k', '192k', '320k')."),
124
+ }, async (args) => {
125
+ try {
126
+ const result = await extractAudio(args);
127
+ return {
128
+ content: [
129
+ {
130
+ type: "text",
131
+ text: `Successfully extracted audio:\nOutput: ${result.outputPath}\nCommand: ${result.commandExecuted}`,
132
+ },
133
+ ],
134
+ };
135
+ }
136
+ catch (err) {
137
+ return {
138
+ isError: true,
139
+ content: [{ type: "text", text: `Error extracting audio: ${err.message}` }],
140
+ };
141
+ }
142
+ });
143
+ // Tool 5: Extract Thumbnail
144
+ server.tool("extract_thumbnail", "Capture a still image from a video. Returns the saved image path and inlined base64 image data so vision models can inspect the frame.", {
145
+ inputPath: z.string().describe("Path to the source video file."),
146
+ outputPath: z.string().describe("Destination image path ending in .png or .jpg (e.g. './thumb.png')."),
147
+ timestamp: z
148
+ .string()
149
+ .optional()
150
+ .describe("Timestamp to capture, such as '00:00:05', '10', or 'midpoint' for the middle frame. Default: '00:00:01'."),
151
+ resolution: z.string().optional().describe("Optional scaled size formatted as 'WIDTHxHEIGHT', such as '1280x720'. Defaults to source resolution."),
152
+ includeBase64: z.boolean().optional().describe("Return base64 image data in response for vision models. Default: true."),
153
+ }, async (args) => {
154
+ try {
155
+ const result = await extractThumbnail(args);
156
+ const content = [];
157
+ if (result.base64 && result.mimeType) {
158
+ content.push({
159
+ type: "image",
160
+ data: result.base64,
161
+ mimeType: result.mimeType,
162
+ });
163
+ }
164
+ content.push({
165
+ type: "text",
166
+ text: `Successfully extracted thumbnail:\nOutput: ${result.outputPath}\nTimestamp: ${result.timestampUsed}\nCommand: ${result.commandExecuted}`,
167
+ });
168
+ return { content };
169
+ }
170
+ catch (err) {
171
+ return {
172
+ isError: true,
173
+ content: [{ type: "text", text: `Error extracting thumbnail: ${err.message}` }],
174
+ };
175
+ }
176
+ });
177
+ // Tool 6: Compress Video
178
+ server.tool("compress_video", "Compress video files to fit upload limits (such as GitHub PRs under 10MB or Discord under 25MB) using target file sizes or CRF quality levels. Does not modify the original file.", compressMediaSchema.shape, async (args) => {
179
+ try {
180
+ const result = await compressMedia(args);
181
+ return {
182
+ content: [
183
+ {
184
+ type: "text",
185
+ text: `Successfully compressed video:\nOutput: ${result.outputPath}\nOriginal Size: ${(result.originalSizeBytes / (1024 * 1024)).toFixed(2)} MB\nCompressed Size: ${(result.compressedSizeBytes / (1024 * 1024)).toFixed(2)} MB (${result.compressionRatio} reduction)\nEncoder: ${result.encoderUsed} (Hardware Accelerated: ${result.hardwareAccelerated})\nCommand: ${result.commandExecuted}`,
186
+ },
187
+ ],
188
+ };
189
+ }
190
+ catch (err) {
191
+ return {
192
+ isError: true,
193
+ content: [{ type: "text", text: `Error compressing video: ${err.message}` }],
194
+ };
195
+ }
196
+ });
197
+ // Tool 7: Concat Media
198
+ server.tool("concat_media", "Join multiple video or audio files in order into a single file. Uses stream copy for matching files or re-encodes when formats differ.", concatMediaSchema.shape, async (args) => {
199
+ try {
200
+ const result = await concatMedia(args);
201
+ return {
202
+ content: [
203
+ {
204
+ type: "text",
205
+ text: `Successfully concatenated ${result.totalInputs} clips:\nOutput: ${result.outputPath}\nMode: ${result.mode}\nCommand: ${result.commandExecuted}`,
206
+ },
207
+ ],
208
+ };
209
+ }
210
+ catch (err) {
211
+ return {
212
+ isError: true,
213
+ content: [{ type: "text", text: `Error concatenating media: ${err.message}` }],
214
+ };
215
+ }
216
+ });
217
+ // Tool 8: Generate Waveform
218
+ server.tool("generate_waveform", "Generate a PNG waveform image from an audio or video file. Returns the file path and inlined base64 image data.", generateWaveformSchema.shape, async (args) => {
219
+ try {
220
+ const result = await generateWaveform(args);
221
+ const content = [];
222
+ if (result.base64) {
223
+ content.push({
224
+ type: "image",
225
+ data: result.base64,
226
+ mimeType: "image/png",
227
+ });
228
+ }
229
+ content.push({
230
+ type: "text",
231
+ text: `Successfully generated waveform:\nOutput: ${result.outputPath}\nDimensions: ${result.resolution}\nColor: ${result.color}\nCommand: ${result.commandExecuted}`,
232
+ });
233
+ return { content };
234
+ }
235
+ catch (err) {
236
+ return {
237
+ isError: true,
238
+ content: [{ type: "text", text: `Error generating waveform: ${err.message}` }],
239
+ };
240
+ }
241
+ });
242
+ // Tool 9: Add Subtitles
243
+ server.tool("add_subtitles", "Embed an SRT or VTT subtitle track into a video file without re-encoding the video stream.", addSubtitlesSchema.shape, async (args) => {
244
+ try {
245
+ const result = await addSubtitles(args);
246
+ return {
247
+ content: [
248
+ {
249
+ type: "text",
250
+ text: `Successfully added subtitle track:\nOutput: ${result.outputPath}\nSubtitles Source: ${result.subtitlesApplied}\nCodec: ${result.subtitleCodec}\nCommand: ${result.commandExecuted}`,
251
+ },
252
+ ],
253
+ };
254
+ }
255
+ catch (err) {
256
+ return {
257
+ isError: true,
258
+ content: [{ type: "text", text: `Error adding subtitles: ${err.message}` }],
259
+ };
260
+ }
261
+ });
262
+ // Tool 10: Change Speed
263
+ server.tool("change_speed", "Change video and audio playback speed (such as 2x for fast forward or 0.5x for slow motion) with pitch correction.", changeSpeedSchema.shape, async (args) => {
264
+ try {
265
+ const result = await changeSpeed(args);
266
+ return {
267
+ content: [
268
+ {
269
+ type: "text",
270
+ text: `Successfully adjusted playback speed:\nOutput: ${result.outputPath}\nMultiplier: ${result.speedMultiplier}x\nCommand: ${result.commandExecuted}`,
271
+ },
272
+ ],
273
+ };
274
+ }
275
+ catch (err) {
276
+ return {
277
+ isError: true,
278
+ content: [{ type: "text", text: `Error changing playback speed: ${err.message}` }],
279
+ };
280
+ }
281
+ });
282
+ // Tool 11: Reformat Aspect Ratio
283
+ server.tool("reformat_aspect_ratio", "Change video aspect ratio to 9:16 vertical, 1:1 square, or 4:5 portrait. Adds blurred video borders, solid padding, or center crops.", reformatAspectSchema.shape, async (args) => {
284
+ try {
285
+ const result = await reformatAspectRatio(args);
286
+ return {
287
+ content: [
288
+ {
289
+ type: "text",
290
+ text: `Successfully reformatted video aspect ratio:\nOutput: ${result.outputPath}\nTarget Ratio: ${result.targetRatio} (${result.resolution})\nMode: ${result.mode}\nEncoder: ${result.encoderUsed} (Hardware Accelerated: ${result.hardwareAccelerated})\nCommand: ${result.commandExecuted}`,
291
+ },
292
+ ],
293
+ };
294
+ }
295
+ catch (err) {
296
+ return {
297
+ isError: true,
298
+ content: [{ type: "text", text: `Error reformatting aspect ratio: ${err.message}` }],
299
+ };
300
+ }
301
+ });
302
+ // Tool 12: Trim Silence
303
+ server.tool("trim_silence", "Detect and remove silent pauses from audio or video files. Returns the duration and seconds saved.", trimSilenceSchema.shape, async (args) => {
304
+ try {
305
+ const result = await trimSilence(args);
306
+ return {
307
+ content: [
308
+ {
309
+ type: "text",
310
+ text: `Successfully trimmed silence:\nOutput: ${result.outputPath}\nMode: ${result.mode}\nOriginal Duration: ${result.originalDurationSeconds}s\nNew Duration: ${result.newDurationSeconds}s (Saved ${result.timeSavedSeconds}s of dead air)\nCommand: ${result.commandExecuted}`,
311
+ },
312
+ ],
313
+ };
314
+ }
315
+ catch (err) {
316
+ return {
317
+ isError: true,
318
+ content: [{ type: "text", text: `Error trimming silence: ${err.message}` }],
319
+ };
320
+ }
321
+ });
322
+ // Tool 13: Create Split Screen
323
+ server.tool("create_split_screen", "Combine two video files into a split-screen video. Stacks clips vertically (1080x1920 for Reels and TikTok) or places them side-by-side. Supports audio mixing and subtitle embedding.", splitScreenSchema.shape, async (args) => {
324
+ try {
325
+ const result = await createSplitScreen(args);
326
+ return {
327
+ content: [
328
+ {
329
+ type: "text",
330
+ text: `Successfully created split-screen video:\nOutput: ${result.outputPath}\nLayout: ${result.layout} (${result.resolution})\nAudio Source: ${result.audioSource}\nSubtitles: ${result.subtitlesEmbedded}\nEncoder: ${result.encoderUsed} (Hardware Accelerated: ${result.hardwareAccelerated})\nCommand: ${result.commandExecuted}`,
331
+ },
332
+ ],
333
+ };
334
+ }
335
+ catch (err) {
336
+ return {
337
+ isError: true,
338
+ content: [{ type: "text", text: `Error creating split screen: ${err.message}` }],
339
+ };
340
+ }
341
+ });
342
+ async function main() {
343
+ const transport = new StdioServerTransport();
344
+ await server.connect(transport);
345
+ console.error("FFmpeg MCP Server running on stdio (13 tools active)");
346
+ }
347
+ main().catch((err) => {
348
+ console.error("Fatal error starting FFmpeg MCP server:", err);
349
+ process.exit(1);
350
+ });
@@ -0,0 +1,31 @@
1
+ import { ensureFileExists, ensureOutputDir, runCommand } from "../utils/exec.js";
2
+ export async function extractAudio(options) {
3
+ const input = await ensureFileExists(options.inputPath);
4
+ const output = await ensureOutputDir(options.outputPath);
5
+ const format = options.format || "mp3";
6
+ const args = ["-y", "-i", input, "-vn"]; // -vn drops the video track
7
+ switch (format) {
8
+ case "whisper_wav":
9
+ // Optimal 16kHz mono PCM for Whisper and AI speech-to-text
10
+ args.push("-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le");
11
+ break;
12
+ case "mp3":
13
+ args.push("-c:a", "libmp3lame", "-b:a", options.bitrate || "192k");
14
+ break;
15
+ case "aac":
16
+ args.push("-c:a", "aac", "-b:a", options.bitrate || "192k");
17
+ break;
18
+ case "flac":
19
+ args.push("-c:a", "flac");
20
+ break;
21
+ case "copy":
22
+ args.push("-c:a", "copy");
23
+ break;
24
+ }
25
+ args.push(output);
26
+ await runCommand("ffmpeg", args);
27
+ return {
28
+ outputPath: output,
29
+ commandExecuted: `ffmpeg ${args.join(" ")}`,
30
+ };
31
+ }
@@ -0,0 +1,119 @@
1
+ import fs from "node:fs";
2
+ import { z } from "zod";
3
+ import { runFfmpeg, ensureFileExists, ensureOutputDir } from "../utils/exec.js";
4
+ import { detectHwAccel } from "../utils/hwaccel.js";
5
+ import { probeMedia } from "./probe.js";
6
+ export const compressMediaSchema = z.object({
7
+ inputPath: z.string().describe("Path to the source video file (e.g. './recordings/demo.mov')"),
8
+ outputPath: z.string().describe("Destination path for the compressed MP4 file (e.g. './recordings/demo_compressed.mp4')"),
9
+ targetSizeMB: z.number().positive().optional().describe("Target output size in megabytes, such as 9.5 for GitHub or 24 for Discord. Computes bitrates from duration."),
10
+ preset: z.enum(["github_pr", "discord", "email", "balanced", "high_quality"]).optional().default("balanced").describe("Preset when targetSizeMB is not set: 'github_pr', 'discord', 'email', 'balanced', or 'high_quality'. Default: 'balanced'."),
11
+ crf: z.number().int().min(18).max(45).optional().describe("Quality value between 18 (higher quality) and 45 (smaller file). Overrides preset."),
12
+ maxWidth: z.number().int().positive().optional().describe("Maximum video width in pixels, such as 1280 for 720p. Keeps aspect ratio."),
13
+ hardwareAcceleration: z.boolean().optional().describe("Use Apple Silicon VideoToolbox encoding when available. Default: true."),
14
+ });
15
+ export async function compressMedia(params) {
16
+ const { inputPath, outputPath, targetSizeMB, preset = "balanced", crf, maxWidth, hardwareAcceleration } = params;
17
+ const input = await ensureFileExists(inputPath);
18
+ const output = await ensureOutputDir(outputPath);
19
+ const hwInfo = await detectHwAccel();
20
+ const useHw = hardwareAcceleration ?? hwInfo.isAvailable;
21
+ const statsBefore = fs.statSync(input);
22
+ const probe = await probeMedia(input);
23
+ const duration = probe.format.durationSeconds || 10;
24
+ const hasAudio = probe.audioStreams.length > 0;
25
+ const args = ["-i", input];
26
+ let scaleFilter = "";
27
+ if (maxWidth) {
28
+ scaleFilter = `scale='min(${maxWidth},iw)':-2`;
29
+ }
30
+ else if (preset === "github_pr") {
31
+ scaleFilter = "scale='min(1280,iw)':-2";
32
+ }
33
+ else if (preset === "email") {
34
+ scaleFilter = "scale='min(854,iw)':-2";
35
+ }
36
+ if (scaleFilter) {
37
+ args.push("-vf", scaleFilter);
38
+ }
39
+ let videoEncoder = "libx264";
40
+ let isHwUsed = false;
41
+ if (targetSizeMB) {
42
+ const totalBits = targetSizeMB * 8 * 1024 * 1024;
43
+ const audioBitrateK = hasAudio ? 96 : 0;
44
+ const totalBitrateK = Math.floor(totalBits / duration / 1000);
45
+ const videoBitrateK = Math.max(100, totalBitrateK - audioBitrateK);
46
+ if (useHw && hwInfo.isAvailable) {
47
+ videoEncoder = hwInfo.h264Encoder;
48
+ isHwUsed = true;
49
+ args.push("-c:v", videoEncoder, "-b:v", `${videoBitrateK}k`);
50
+ }
51
+ else {
52
+ args.push("-c:v", "libx264", "-b:v", `${videoBitrateK}k`, "-maxrate", `${Math.floor(videoBitrateK * 1.4)}k`, "-bufsize", `${Math.floor(videoBitrateK * 2)}k`);
53
+ }
54
+ args.push("-pix_fmt", "yuv420p");
55
+ if (hasAudio) {
56
+ args.push("-c:a", "aac", "-b:a", `${audioBitrateK}k`);
57
+ }
58
+ args.push("-movflags", "+faststart");
59
+ }
60
+ else {
61
+ let chosenCrf = 26;
62
+ if (crf !== undefined) {
63
+ chosenCrf = crf;
64
+ }
65
+ else {
66
+ switch (preset) {
67
+ case "github_pr":
68
+ chosenCrf = 28;
69
+ break;
70
+ case "discord":
71
+ chosenCrf = 26;
72
+ break;
73
+ case "email":
74
+ chosenCrf = 32;
75
+ break;
76
+ case "balanced":
77
+ chosenCrf = 26;
78
+ break;
79
+ case "high_quality":
80
+ chosenCrf = 21;
81
+ break;
82
+ }
83
+ }
84
+ if (useHw && hwInfo.isAvailable) {
85
+ videoEncoder = hwInfo.h264Encoder;
86
+ isHwUsed = true;
87
+ const bitrateMap = {
88
+ github_pr: "1500k",
89
+ discord: "2000k",
90
+ email: "800k",
91
+ balanced: "2200k",
92
+ high_quality: "4000k",
93
+ };
94
+ args.push("-c:v", videoEncoder, "-b:v", bitrateMap[preset] || "2200k");
95
+ }
96
+ else {
97
+ args.push("-c:v", "libx264", "-crf", chosenCrf.toString(), "-preset", "medium");
98
+ }
99
+ args.push("-pix_fmt", "yuv420p");
100
+ if (hasAudio) {
101
+ args.push("-c:a", "aac", "-b:a", "128k");
102
+ }
103
+ args.push("-movflags", "+faststart");
104
+ }
105
+ args.push("-y", output);
106
+ const result = await runFfmpeg(args);
107
+ const statsAfter = fs.statSync(output);
108
+ return {
109
+ success: true,
110
+ outputPath: output,
111
+ originalSizeBytes: statsBefore.size,
112
+ compressedSizeBytes: statsAfter.size,
113
+ compressionRatio: `${((1 - (statsAfter.size / statsBefore.size)) * 100).toFixed(1)}%`,
114
+ hardwareAccelerated: isHwUsed,
115
+ encoderUsed: videoEncoder,
116
+ commandExecuted: result.command,
117
+ durationSeconds: result.durationSeconds,
118
+ };
119
+ }