@ash_j1997/ffmpeg-mcp-server 0.6.1 → 0.6.3

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/README.ko.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | [한국어](README.ko.md)
4
4
 
5
- [![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) [![npm version](https://img.shields.io/npm/v/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm downloads](https://img.shields.io/npm/dw/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm total downloads](https://img.shields.io/npm/dt/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![Glama](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server/badge)](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server) [![FFmpeg MCP server](https://mcprush.com/badge/ashutos1997-ffmpeg-mcp/card.svg)](https://mcprush.com/to/ashutos1997-ffmpeg-mcp?ref=badge)
5
+ [![CI](https://github.com/Ashutos1997/ffmpeg-mcp-server/actions/workflows/ci.yml/badge.svg?branch=main)](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) [![npm version](https://img.shields.io/npm/v/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm downloads](https://img.shields.io/npm/dw/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm total downloads](https://img.shields.io/npm/dt/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![Glama](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server/badge)](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server) [![FFmpeg MCP server](https://mcprush.com/badge/ashutos1997-ffmpeg-mcp/card.svg)](https://mcprush.com/to/ashutos1997-ffmpeg-mcp?ref=badge)
6
6
 
7
7
  AI 에이전트와 도구가 로컬에서 비디오 및 오디오를 처리할 수 있도록 FFmpeg 및 FFprobe 기능을 제공하는 Model Context Protocol (MCP) 서버입니다.
8
8
 
@@ -18,6 +18,26 @@ AI 에이전트에게 영상 처리를 직접 명령하면 잘못된 플래그,
18
18
 
19
19
  ---
20
20
 
21
+ ## 빠른 시작 (Quick Start)
22
+
23
+ 별도의 빌드나 클론 없이 클라이언트 설정 파일에 바로 추가하여 실행할 수 있습니다:
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "ffmpeg": {
29
+ "command": "npx",
30
+ "args": ["-y", "@ash_j1997/ffmpeg-mcp-server"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ * **Claude Desktop:** `~/Library/Application Support/Claude/claude_desktop_config.json` (Mac) 또는 `%APPDATA%\Claude\claude_desktop_config.json` (Windows)
37
+ * **Cursor / Windsurf:** stdio 서버로 등록 (Command: `npx`, Args: `["-y", "@ash_j1997/ffmpeg-mcp-server"]`)
38
+
39
+ ---
40
+
21
41
  ## 주요 기능 (Key Features)
22
42
 
23
43
  * **범용 하드웨어 가속:** macOS(VideoToolbox), Linux/Windows GPU(NVIDIA NVENC, Intel QuickSync, AMD AMF, VA-API)를 자동 감지하여 낮은 CPU 점유율로 5배~20배 빠른 인코딩을 지원합니다.
@@ -27,6 +47,7 @@ AI 에이전트에게 영상 처리를 직접 명령하면 잘못된 플래그,
27
47
  * **숏폼/소셜 포맷 자동화:** 가로 영상을 배경 블러 처리된 9:16 세로 숏폼 영상으로 변환하고, 스타일이 적용된 자막을 하드코딩(버닝)하며, 틱톡/릴스용 상하 분할 스플릿 스크린 영상을 제작합니다.
28
48
  * **오디오 엔지니어링:** 스트리밍/방송 표준(EBU R128 / -16 LUFS)에 맞춰 음량을 정규화하고, 80Hz 럼블 제거 필터로 음성을 선명하게 보정하며, 립싱크를 유지하면서 무음 구간을 자동으로 잘라냅니다.
29
49
  * **장면 감지 및 스트림 결합:** 시각적 장면 전환(컷 편집 지점)을 감지하여 타임스탬프와 콘택트 시트를 반환하고, 무손실 스트림 복사로 비디오와 오디오를 즉시 결합/교체합니다.
50
+ * **지능형 사전 검증(Smart Input Guards):** FFmpeg 실행 전 미디어 스트림 유무, 오디오 트랙, 재생 시간 한계를 사전에 검증하여 `trim_media`, `extract_audio`, `generate_waveform`, `extract_thumbnail` 등에서 무음 영상이나 범위 초과로 인한 런타임 오류를 사전에 방지합니다.
30
51
 
31
52
  ---
32
53
 
@@ -43,7 +64,7 @@ AI 에이전트에게 영상 처리를 직접 명령하면 잘못된 플래그,
43
64
  | **`reformat_aspect_ratio`** | 배경 블러 패딩 또는 중앙 크롭을 적용해 영상 비율을 9:16(세로), 1:1(정사각형), 4:5(포트레이트)로 변환합니다. | `inputPath`, `outputPath`, `targetRatio`, `mode`, `blurAmount`, `padColor`, `hardwareAcceleration` |
44
65
  | **`create_split_screen`** | 두 개의 영상을 상하(9:16 숏폼/릴스) 또는 좌우로 배치하고 오디오 믹싱 및 자막을 합성합니다. | `firstVideoPath`, `secondVideoPath`, `outputPath`, `layout`, `audioSource`, `subtitlesPath` |
45
66
  | **`trim_silence`** | 영상과 음성의 립싱크를 완벽히 유지하면서 녹음/녹화 영상의 무음 구간(침묵)을 감지해 자동으로 잘라냅니다. | `inputPath`, `outputPath`, `mode`, `thresholdDb`, `minDurationSeconds` |
46
- | **`concat_media`** | 여러 비디오 또는 오디오 파일을 순서대로 병합합니다. 스트림 복사 및 재인코딩 방식을 지원합니다. | `inputPaths`, `outputPath`, `mode` |
67
+ | **`concat_media`** | 여러 미디어 파일을 순서대로 병합합니다. 입력 파일을 자동 분석하여 스트림 복사 또는 재인코딩을 선택합니다. | `inputPaths`, `outputPath`, `mode` |
47
68
  | **`generate_waveform`** | 오디오 파형(Waveform) PNG 이미지를 생성합니다. 비전 모델을 위한 base64 데이터를 반환할 수 있습니다. | `inputPath`, `outputPath`, `width`, `height`, `color`, `scale`, `includeBase64` |
48
69
  | **`add_subtitles`** | 비디오 재인코딩 없이 SRT 또는 VTT 자막 트랙을 MP4/MKV 파일에 소프트웨어 자막으로 삽입합니다. | `videoPath`, `subtitlesPath`, `outputPath`, `language`, `title` |
49
70
  | **`burn_subtitles`** | 폰트 크기, 글자 색상, 외곽선, 여백을 커스텀하여 비디오 프레임에 자막을 직접 하드코딩(버닝)합니다. | `videoPath`, `subtitlesPath`, `outputPath`, `fontSize`, `fontColor`, `outlineColor`, `marginV` |
@@ -119,7 +140,8 @@ AI 에이전트에게 영상 처리를 직접 명령하면 잘못된 플래그,
119
140
 
120
141
  ## 감사의 글 (Acknowledgements & Community)
121
142
 
122
- 단순 포맷 변환을 넘어 스트림 멀티플렉싱(`mux_media`) 및 장면 전환 감지 기능(`detect_scenes`)을 제안해 주신 [@rajarshidattapy](https://github.com/rajarshidattapy) 님께 감사드립니다.
143
+ - 단순 포맷 변환을 넘어 스트림 멀티플렉싱(`mux_media`) 및 장면 전환 감지 기능(`detect_scenes`)을 제안해 주신 [@rajarshidattapy](https://github.com/rajarshidattapy) 님께 감사드립니다.
144
+ - 사전 스트림 검증 및 오디오 샘플 레이트 체크(Smart Input Guards) 아이디어와 `concat_media`의 자동 감지(auto-probe) 모드를 제안해 주신 Reddit 사용자 [u/QuanTradin](https://www.reddit.com/user/QuanTradin/) 님께 감사드립니다.
123
145
 
124
146
  ---
125
147
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [English](README.md) | [한국어](README.ko.md)
4
4
 
5
- [![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) [![npm version](https://img.shields.io/npm/v/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm downloads](https://img.shields.io/npm/dw/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm total downloads](https://img.shields.io/npm/dt/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![Glama](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server/badge)](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server) [![FFmpeg MCP server](https://mcprush.com/badge/ashutos1997-ffmpeg-mcp/card.svg)](https://mcprush.com/to/ashutos1997-ffmpeg-mcp?ref=badge)
5
+ [![CI](https://github.com/Ashutos1997/ffmpeg-mcp-server/actions/workflows/ci.yml/badge.svg?branch=main)](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) [![npm version](https://img.shields.io/npm/v/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm downloads](https://img.shields.io/npm/dw/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![npm total downloads](https://img.shields.io/npm/dt/@ash_j1997/ffmpeg-mcp-server.svg)](https://www.npmjs.com/package/@ash_j1997/ffmpeg-mcp-server) [![Glama](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server/badge)](https://glama.ai/mcp/servers/@Ashutos1997/ffmpeg-mcp-server) [![FFmpeg MCP server](https://mcprush.com/badge/ashutos1997-ffmpeg-mcp/card.svg)](https://mcprush.com/to/ashutos1997-ffmpeg-mcp?ref=badge)
6
6
 
7
7
  A Model Context Protocol (MCP) server that gives AI tools access to FFmpeg and FFprobe to process video and audio locally.
8
8
 
@@ -18,6 +18,26 @@ This server provides **19 typed tools** using Zod schemas. The AI passes paramet
18
18
 
19
19
  ---
20
20
 
21
+ ## Quick Start
22
+
23
+ Add directly to your client configuration (no manual cloning required):
24
+
25
+ ```json
26
+ {
27
+ "mcpServers": {
28
+ "ffmpeg": {
29
+ "command": "npx",
30
+ "args": ["-y", "@ash_j1997/ffmpeg-mcp-server"]
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ * **Claude Desktop:** `~/Library/Application Support/Claude/claude_desktop_config.json` (Mac) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows)
37
+ * **Cursor / Windsurf:** Add as a stdio server with command `npx` and args `["-y", "@ash_j1997/ffmpeg-mcp-server"]`
38
+
39
+ ---
40
+
21
41
  ## Key Features
22
42
 
23
43
  * **Universal Hardware Acceleration:** Automatically detects and leverages hardware encoders across macOS (VideoToolbox), Linux/Windows GPUs (NVIDIA NVENC, Intel QuickSync, AMD AMF, and VA-API) for 5x–20x faster exports with low CPU usage.
@@ -27,6 +47,7 @@ This server provides **19 typed tools** using Zod schemas. The AI passes paramet
27
47
  * **Social Formats & Automation:** Reformats landscape video to 9:16 vertical video with blurred backgrounds, burns customizable hardcoded subtitles, and stacks top/bottom split-screen reels for TikTok and Instagram Reels.
28
48
  * **Audio Engineering:** Normalizes loudness to broadcast/streaming standards (EBU R128 / -16 LUFS), cleans vocal audio with 80Hz rumble removal, and trims dead air while preserving lip-sync.
29
49
  * **Scene Intelligence & Multiplexing:** Detects visual scene changes and cut points for smart editing workflows, and combines or replaces video/audio tracks with zero-loss stream copy.
50
+ * **Smart Input Guards & Validation:** Pre-probes streams and duration limits before execution — safeguarding `trim_media`, `extract_audio`, `generate_waveform`, and `extract_thumbnail` from cryptic errors on silent or out-of-bounds media.
30
51
 
31
52
  ---
32
53
 
@@ -43,7 +64,7 @@ This server provides **19 typed tools** using Zod schemas. The AI passes paramet
43
64
  | **`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`, `hardwareAcceleration` |
44
65
  | **`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` |
45
66
  | **`trim_silence`** | Detects and removes silent pauses from recordings while preserving video & audio lip-sync. | `inputPath`, `outputPath`, `mode`, `thresholdDb`, `minDurationSeconds` |
46
- | **`concat_media`** | Joins multiple video or audio files in order using stream copy or re-encoding. | `inputPaths`, `outputPath`, `mode` |
67
+ | **`concat_media`** | Joins multiple media files in order. Automatically probes inputs to select stream copy or re-encoding. | `inputPaths`, `outputPath`, `mode` |
47
68
  | **`generate_waveform`** | Generates a PNG waveform image. Returns base64 image data for vision models. | `inputPath`, `outputPath`, `width`, `height`, `color`, `scale`, `includeBase64` |
48
69
  | **`add_subtitles`** | Embeds SRT or VTT subtitle tracks into MP4/MKV video files without re-encoding video. | `videoPath`, `subtitlesPath`, `outputPath`, `language`, `title` |
49
70
  | **`burn_subtitles`** | Hardcodes subtitles directly onto video frames with customizable font size, colors, and margins. | `videoPath`, `subtitlesPath`, `outputPath`, `fontSize`, `fontColor`, `outlineColor`, `marginV` |
@@ -119,7 +140,8 @@ Run directly with `npx` (no manual cloning or building required):
119
140
 
120
141
  ## Acknowledgements & Community
121
142
 
122
- Special thanks to [@rajarshidattapy](https://github.com/rajarshidattapy) for suggesting the stream multiplexing (`mux_media`) and scene transition detection (`detect_scenes`) capabilities to expand the server beyond format conversion.
143
+ - Special thanks to [@rajarshidattapy](https://github.com/rajarshidattapy) for suggesting stream multiplexing (`mux_media`) and scene transition detection (`detect_scenes`) to expand the server beyond format conversion.
144
+ - Special thanks to Reddit user [u/QuanTradin](https://www.reddit.com/user/QuanTradin/) for inspiring smart input guards (pre-flight stream validation & sample rate checking) and auto-probing in `concat_media` to prevent corrupted outputs and catch bugs before execution.
123
145
 
124
146
  ---
125
147
 
package/dist/index.js CHANGED
@@ -25,7 +25,7 @@ import { detectHwAccel } from "./utils/hwaccel.js";
25
25
  import { runCommand } from "./utils/exec.js";
26
26
  const server = new McpServer({
27
27
  name: "ffmpeg-mcp-server",
28
- version: "0.6.1",
28
+ version: "0.6.3",
29
29
  });
30
30
  function createProgressCallback(extra) {
31
31
  return (p) => {
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { ensureFileExists, ensureOutputDir, runFfmpeg } from "../utils/exec.js";
3
+ import { probeMedia } from "./probe.js";
3
4
  export const extractAudioSchema = z.object({
4
5
  inputPath: z.string().describe("Path to the source video or audio file."),
5
6
  outputPath: z.string().describe("Destination path for the output audio file (e.g. './extracted.wav' or './audio.mp3')."),
@@ -12,6 +13,10 @@ export const extractAudioSchema = z.object({
12
13
  export async function extractAudio(params, options) {
13
14
  const input = await ensureFileExists(params.inputPath);
14
15
  const output = await ensureOutputDir(params.outputPath);
16
+ const probe = await probeMedia(input, { signal: options?.signal });
17
+ if (probe.audioStreams.length === 0) {
18
+ throw new Error(`Cannot extract audio from "${params.inputPath}": file contains no audio streams.`);
19
+ }
15
20
  const format = params.format || "mp3";
16
21
  const args = ["-y", "-i", input, "-vn"]; // -vn drops the video track
17
22
  switch (format) {
@@ -36,6 +41,7 @@ export async function extractAudio(params, options) {
36
41
  const res = await runFfmpeg(args, {
37
42
  signal: options?.signal,
38
43
  onProgress: options?.onProgress,
44
+ expectedDurationSeconds: probe.format.durationSeconds,
39
45
  });
40
46
  return {
41
47
  outputPath: output,
@@ -74,7 +74,14 @@ export async function burnSubtitles(params, options) {
74
74
  else {
75
75
  args.push("-crf", "22", "-preset", "fast", "-pix_fmt", "yuv420p");
76
76
  }
77
- args.push("-c:a", "copy", "-movflags", "+faststart", "-y", output);
77
+ const hasAudio = probe.audioStreams.length > 0;
78
+ if (hasAudio) {
79
+ args.push("-c:a", "copy");
80
+ }
81
+ else {
82
+ args.push("-an");
83
+ }
84
+ args.push("-movflags", "+faststart", "-y", output);
78
85
  const res = await runFfmpeg(args, {
79
86
  signal: options?.signal,
80
87
  onProgress: options?.onProgress,
@@ -1,4 +1,6 @@
1
1
  import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
2
4
  import { z } from "zod";
3
5
  import { runFfmpeg, ensureFileExists, ensureOutputDir } from "../utils/exec.js";
4
6
  import { detectHwAccel } from "../utils/hwaccel.js";
@@ -39,23 +41,81 @@ export async function compressMedia(params, options) {
39
41
  let videoEncoder = "libx264";
40
42
  let isHwUsed = false;
41
43
  if (targetSizeMB) {
42
- const totalBits = targetSizeMB * 8 * 1024 * 1024;
44
+ const targetBytes = targetSizeMB * 1024 * 1024;
45
+ const totalBits = targetBytes * 8 * 0.95;
43
46
  const audioBitrateK = hasAudio ? 96 : 0;
44
47
  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`);
48
+ const minimumVideoBitrateK = 100;
49
+ if (totalBitrateK < audioBitrateK + minimumVideoBitrateK) {
50
+ const minimumSizeMB = (((audioBitrateK + minimumVideoBitrateK) * 1000 * duration) /
51
+ (8 * 0.95 * 1024 * 1024)).toFixed(2);
52
+ throw new Error(`Target size ${targetSizeMB} MB is too small for this duration; minimum is approximately ${minimumSizeMB} MB`);
50
53
  }
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`);
54
+ const videoBitrateK = totalBitrateK - audioBitrateK;
55
+ videoEncoder = "libx264";
56
+ const passId = `ffmpeg-mcp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
57
+ const passLog = path.join(os.tmpdir(), passId);
58
+ const extension = path.extname(output);
59
+ const stagedOutput = path.join(path.dirname(output), `.${path.basename(output, extension)}-${passId}${extension}`);
60
+ const videoArgs = [
61
+ "-c:v", "libx264",
62
+ "-b:v", `${videoBitrateK}k`,
63
+ "-maxrate", `${Math.floor(videoBitrateK * 1.4)}k`,
64
+ "-bufsize", `${Math.floor(videoBitrateK * 2)}k`,
65
+ "-pix_fmt", "yuv420p",
66
+ ];
67
+ let result;
68
+ try {
69
+ await runFfmpeg([...args, ...videoArgs, "-pass", "1", "-passlogfile", passLog, "-an", "-f", "null", "-"], { signal: options?.signal, expectedDurationSeconds: duration });
70
+ const secondPassArgs = [
71
+ ...args,
72
+ ...videoArgs,
73
+ "-pass", "2",
74
+ "-passlogfile", passLog,
75
+ ];
76
+ if (hasAudio) {
77
+ secondPassArgs.push("-c:a", "aac", "-b:a", `${audioBitrateK}k`);
78
+ }
79
+ secondPassArgs.push("-movflags", "+faststart", "-y", stagedOutput);
80
+ result = await runFfmpeg(secondPassArgs, {
81
+ signal: options?.signal,
82
+ onProgress: options?.onProgress,
83
+ expectedDurationSeconds: duration,
84
+ });
85
+ const stagedStats = fs.statSync(stagedOutput);
86
+ if (stagedStats.size > targetBytes) {
87
+ throw new Error(`Compressed output is ${(stagedStats.size / (1024 * 1024)).toFixed(2)} MB, exceeding the ${targetSizeMB} MB target`);
88
+ }
89
+ fs.renameSync(stagedOutput, output);
53
90
  }
54
- args.push("-pix_fmt", "yuv420p");
55
- if (hasAudio) {
56
- args.push("-c:a", "aac", "-b:a", `${audioBitrateK}k`);
91
+ finally {
92
+ if (fs.existsSync(stagedOutput)) {
93
+ try {
94
+ fs.unlinkSync(stagedOutput);
95
+ }
96
+ catch { }
97
+ }
98
+ for (const file of fs.readdirSync(os.tmpdir())) {
99
+ if (file.startsWith(passId)) {
100
+ try {
101
+ fs.unlinkSync(path.join(os.tmpdir(), file));
102
+ }
103
+ catch { }
104
+ }
105
+ }
57
106
  }
58
- args.push("-movflags", "+faststart");
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
+ };
59
119
  }
60
120
  else {
61
121
  let chosenCrf = 26;
@@ -4,29 +4,104 @@ import os from "node:os";
4
4
  import { z } from "zod";
5
5
  import { runFfmpeg, ensureFileExists, ensureOutputDir } from "../utils/exec.js";
6
6
  import { detectHwAccel } from "../utils/hwaccel.js";
7
+ import { probeMedia } from "./probe.js";
7
8
  export const concatMediaSchema = z.object({
8
9
  inputPaths: z.array(z.string()).min(2).describe("List of media files to concatenate in sequential order"),
9
10
  outputPath: z.string().describe("Target output file path"),
10
- mode: z.enum(["lossless", "reencode"]).optional().default("lossless").describe("Concatenation mode. 'lossless' uses stream copy without quality loss (inputs must share codecs). 'reencode' normalizes differing resolutions/codecs."),
11
+ mode: z
12
+ .enum(["auto", "lossless", "reencode"])
13
+ .optional()
14
+ .default("auto")
15
+ .describe("Concatenation mode. 'auto' (default) probes inputs to check codecs, resolutions, framerates, and audio sample rates, using fast stream copy if matching or falling back to re-encoding if they differ. 'lossless' forces stream copy. 'reencode' forces filtergraph normalization."),
11
16
  });
17
+ function canUseLosslessConcat(probes) {
18
+ if (probes.length < 2)
19
+ return true;
20
+ const first = probes[0];
21
+ for (let i = 1; i < probes.length; i++) {
22
+ const current = probes[i];
23
+ if (first.videoStreams.length !== current.videoStreams.length)
24
+ return false;
25
+ for (let v = 0; v < first.videoStreams.length; v++) {
26
+ const fv = first.videoStreams[v];
27
+ const cv = current.videoStreams[v];
28
+ if (fv.codec !== cv.codec ||
29
+ fv.width !== cv.width ||
30
+ fv.height !== cv.height ||
31
+ fv.fps !== cv.fps ||
32
+ fv.pixelFormat !== cv.pixelFormat) {
33
+ return false;
34
+ }
35
+ }
36
+ if (first.audioStreams.length !== current.audioStreams.length)
37
+ return false;
38
+ for (let a = 0; a < first.audioStreams.length; a++) {
39
+ const fa = first.audioStreams[a];
40
+ const ca = current.audioStreams[a];
41
+ if (fa.codec !== ca.codec ||
42
+ fa.sampleRateHz !== ca.sampleRateHz ||
43
+ fa.channels !== ca.channels) {
44
+ return false;
45
+ }
46
+ }
47
+ }
48
+ return true;
49
+ }
12
50
  export async function concatMedia(params, options) {
13
- const { inputPaths, outputPath, mode = "lossless" } = params;
51
+ const { inputPaths, outputPath, mode = "auto" } = params;
14
52
  const resolvedInputs = [];
15
53
  for (const p of inputPaths) {
16
54
  resolvedInputs.push(await ensureFileExists(p));
17
55
  }
18
56
  const output = await ensureOutputDir(outputPath);
19
- const tmpManifest = path.join(os.tmpdir(), `mcp_concat_${Date.now()}_${Math.random().toString(36).substring(7)}.txt`);
20
- const manifestContent = resolvedInputs
21
- .map((p) => `file '${p.replace(/'/g, "'\\''")}'`)
22
- .join("\n");
23
- fs.writeFileSync(tmpManifest, manifestContent, "utf8");
24
- try {
25
- const args = ["-f", "concat", "-safe", "0", "-i", tmpManifest];
26
- if (mode === "lossless") {
27
- args.push("-c", "copy");
57
+ let effectiveMode = mode === "reencode" ? "reencode" : "lossless";
58
+ let probes = null;
59
+ if (mode === "auto") {
60
+ probes = await Promise.all(resolvedInputs.map((input) => probeMedia(input, { signal: options?.signal })));
61
+ effectiveMode = canUseLosslessConcat(probes) ? "lossless" : "reencode";
62
+ }
63
+ if (effectiveMode === "reencode") {
64
+ if (!probes) {
65
+ probes = await Promise.all(resolvedInputs.map((input) => probeMedia(input, { signal: options?.signal })));
28
66
  }
29
- else {
67
+ const allVideo = probes.every((probe) => probe.videoStreams.length > 0);
68
+ const allAudioOnly = probes.every((probe) => probe.videoStreams.length === 0 && probe.audioStreams.length > 0);
69
+ if (!allVideo && !allAudioOnly) {
70
+ throw new Error("Reencode mode requires either all video inputs or all audio-only inputs");
71
+ }
72
+ const args = [];
73
+ for (const input of resolvedInputs) {
74
+ args.push("-i", input);
75
+ }
76
+ const filters = [];
77
+ const concatInputs = [];
78
+ const hasAnyAudio = probes.some((probe) => probe.audioStreams.length > 0);
79
+ if (allVideo) {
80
+ const firstVideo = probes[0].videoStreams[0];
81
+ const width = Math.max(2, Math.floor(firstVideo.width / 2) * 2);
82
+ const height = Math.max(2, Math.floor(firstVideo.height / 2) * 2);
83
+ probes.forEach((probe, index) => {
84
+ filters.push(`[${index}:v:0]scale=${width}:${height}:force_original_aspect_ratio=decrease,` +
85
+ `pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p,setpts=PTS-STARTPTS[v${index}]`);
86
+ concatInputs.push(`[v${index}]`);
87
+ if (hasAnyAudio) {
88
+ if (probe.audioStreams.length > 0) {
89
+ filters.push(`[${index}:a:0]aformat=sample_rates=48000:channel_layouts=stereo,` +
90
+ `aresample=async=1:first_pts=0,asetpts=PTS-STARTPTS[a${index}]`);
91
+ }
92
+ else {
93
+ const duration = Math.max(0.001, probe.format.durationSeconds);
94
+ filters.push(`anullsrc=channel_layout=stereo:sample_rate=48000,atrim=duration=${duration},` +
95
+ `asetpts=PTS-STARTPTS[a${index}]`);
96
+ }
97
+ concatInputs.push(`[a${index}]`);
98
+ }
99
+ });
100
+ filters.push(`${concatInputs.join("")}concat=n=${resolvedInputs.length}:v=1:a=${hasAnyAudio ? 1 : 0}` +
101
+ `[outv]${hasAnyAudio ? "[outa]" : ""}`);
102
+ args.push("-filter_complex", filters.join(";"), "-map", "[outv]");
103
+ if (hasAnyAudio)
104
+ args.push("-map", "[outa]");
30
105
  const hwInfo = await detectHwAccel();
31
106
  if (hwInfo.isAvailable) {
32
107
  args.push("-c:v", hwInfo.h264Encoder, "-b:v", "4M");
@@ -34,8 +109,43 @@ export async function concatMedia(params, options) {
34
109
  else {
35
110
  args.push("-c:v", "libx264", "-crf", "22", "-preset", "fast");
36
111
  }
37
- args.push("-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart");
112
+ args.push("-pix_fmt", "yuv420p");
113
+ if (hasAnyAudio)
114
+ args.push("-c:a", "aac", "-b:a", "192k");
115
+ }
116
+ else {
117
+ probes.forEach((_probe, index) => {
118
+ filters.push(`[${index}:a:0]aformat=sample_rates=48000:channel_layouts=stereo,` +
119
+ `aresample=async=1:first_pts=0,asetpts=PTS-STARTPTS[a${index}]`);
120
+ concatInputs.push(`[a${index}]`);
121
+ });
122
+ filters.push(`${concatInputs.join("")}concat=n=${resolvedInputs.length}:v=0:a=1[outa]`);
123
+ args.push("-filter_complex", filters.join(";"), "-map", "[outa]", "-c:a", "aac", "-b:a", "192k");
38
124
  }
125
+ args.push("-movflags", "+faststart", "-y", output);
126
+ const result = await runFfmpeg(args, {
127
+ signal: options?.signal,
128
+ onProgress: options?.onProgress,
129
+ expectedDurationSeconds: probes.reduce((total, probe) => total + probe.format.durationSeconds, 0),
130
+ });
131
+ return {
132
+ success: true,
133
+ outputPath: output,
134
+ totalInputs: resolvedInputs.length,
135
+ mode: effectiveMode,
136
+ strategyUsed: effectiveMode,
137
+ commandExecuted: result.command,
138
+ durationSeconds: result.durationSeconds,
139
+ };
140
+ }
141
+ const tmpManifest = path.join(os.tmpdir(), `mcp_concat_${Date.now()}_${Math.random().toString(36).substring(7)}.txt`);
142
+ const manifestContent = resolvedInputs
143
+ .map((p) => `file '${p.replace(/'/g, "'\\''")}'`)
144
+ .join("\n");
145
+ fs.writeFileSync(tmpManifest, manifestContent, "utf8");
146
+ try {
147
+ const args = ["-f", "concat", "-safe", "0", "-i", tmpManifest];
148
+ args.push("-c", "copy");
39
149
  args.push("-y", output);
40
150
  const result = await runFfmpeg(args, {
41
151
  signal: options?.signal,
@@ -45,7 +155,8 @@ export async function concatMedia(params, options) {
45
155
  success: true,
46
156
  outputPath: output,
47
157
  totalInputs: resolvedInputs.length,
48
- mode,
158
+ mode: effectiveMode,
159
+ strategyUsed: effectiveMode,
49
160
  commandExecuted: result.command,
50
161
  durationSeconds: result.durationSeconds,
51
162
  };
@@ -71,7 +71,7 @@ export async function trimSilence(args, options) {
71
71
  const hwInfo = await detectHwAccel();
72
72
  const ffmpegArgs = ["-ss", startTime.toFixed(3), "-i", input];
73
73
  if (endTime < originalDuration) {
74
- ffmpegArgs.push("-to", endTime.toFixed(3));
74
+ ffmpegArgs.push("-t", Math.max(0, endTime - startTime).toFixed(3));
75
75
  }
76
76
  if (hwInfo.isAvailable) {
77
77
  ffmpegArgs.push("-c:v", hwInfo.h264Encoder, "-b:v", "4M", "-c:a", "aac", "-b:a", "192k");
@@ -27,17 +27,19 @@ export async function changeSpeed(params, options) {
27
27
  const input = await ensureFileExists(inputPath);
28
28
  const output = await ensureOutputDir(outputPath);
29
29
  let expectedDuration;
30
+ let hasAudio = false;
30
31
  try {
31
32
  const probe = await probeMedia(input, { signal: options?.signal });
32
33
  if (probe.format.durationSeconds > 0) {
33
34
  expectedDuration = probe.format.durationSeconds / speed;
34
35
  }
36
+ hasAudio = probe.audioStreams.length > 0;
35
37
  }
36
38
  catch { }
37
39
  const hwInfo = await detectHwAccel();
38
40
  const videoFilter = `setpts=${(1 / speed).toFixed(6)}*PTS`;
39
41
  const args = ["-i", input, "-filter:v", videoFilter];
40
- if (muteAudio) {
42
+ if (muteAudio || !hasAudio) {
41
43
  args.push("-an");
42
44
  }
43
45
  else {
@@ -70,7 +70,7 @@ export async function createSplitScreen(params, options) {
70
70
  // Audio filter handling
71
71
  let audioMapped = false;
72
72
  if (audioSource === "mix" && firstHasAudio && secondHasAudio) {
73
- filter += ";[0:a][1:a]amix=inputs=2:duration=first:dropout_transition=2[outa]";
73
+ filter += ";[0:a][1:a]amix=inputs=2:duration=longest:dropout_transition=2[outa]";
74
74
  args.push("-filter_complex", filter, "-map", "[outv]", "-map", "[outa]");
75
75
  audioMapped = true;
76
76
  }
@@ -27,6 +27,9 @@ export async function addSubtitles(params, options) {
27
27
  const args = [
28
28
  "-i", video,
29
29
  "-i", subs,
30
+ "-map", "0:v?",
31
+ "-map", "0:a?",
32
+ "-map", "1:s:0",
30
33
  "-c:v", "copy",
31
34
  "-c:a", "copy",
32
35
  "-c:s", subtitleCodec,
@@ -17,18 +17,31 @@ export const extractThumbnailSchema = z.object({
17
17
  .describe("Optional scaled size formatted as 'WIDTHxHEIGHT', such as '1280x720'. Defaults to source resolution."),
18
18
  includeBase64: z.boolean().optional().describe("Return base64 image data in response for vision models. Default: true."),
19
19
  });
20
+ function parseTimestampToSeconds(ts) {
21
+ const parts = ts.split(":").map(Number);
22
+ if (parts.length === 1)
23
+ return parts[0];
24
+ if (parts.length === 2)
25
+ return parts[0] * 60 + parts[1];
26
+ return parts[0] * 3600 + parts[1] * 60 + parts[2];
27
+ }
20
28
  export async function extractThumbnail(params, options) {
21
29
  const input = await ensureFileExists(params.inputPath);
22
30
  const output = await ensureOutputDir(params.outputPath);
31
+ const probe = await probeMedia(input, { signal: options?.signal });
32
+ if (probe.videoStreams.length === 0) {
33
+ throw new Error(`Cannot extract thumbnail from "${params.inputPath}": file contains no video streams.`);
34
+ }
23
35
  let timestamp = params.timestamp || "00:00:01";
36
+ const duration = probe.format.durationSeconds;
24
37
  if (timestamp === "midpoint") {
25
- try {
26
- const info = await probeMedia(input, { signal: options?.signal });
27
- const midpointSeconds = Math.max(0, Math.floor(info.format.durationSeconds / 2));
28
- timestamp = String(midpointSeconds);
29
- }
30
- catch {
31
- timestamp = "00:00:01";
38
+ const midpointSeconds = Math.max(0, Math.floor(duration / 2));
39
+ timestamp = String(midpointSeconds);
40
+ }
41
+ else if (duration > 0) {
42
+ const tsSec = parseTimestampToSeconds(timestamp);
43
+ if (!isNaN(tsSec) && tsSec >= duration) {
44
+ timestamp = String(Math.max(0, Number((duration - 0.1).toFixed(2))));
32
45
  }
33
46
  }
34
47
  const args = [
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { ensureFileExists, ensureOutputDir, runFfmpeg } from "../utils/exec.js";
3
3
  import { detectHwAccel } from "../utils/hwaccel.js";
4
+ import { probeMedia } from "./probe.js";
4
5
  export const trimMediaSchema = z.object({
5
6
  inputPath: z.string().describe("Path to the source media file to cut."),
6
7
  outputPath: z.string().describe("Destination path for the trimmed output file (e.g. './clip.mp4')."),
@@ -23,18 +24,45 @@ export const trimMediaSchema = z.object({
23
24
  .optional()
24
25
  .describe("Re-encode video for cuts between keyframes. Default: false (uses fast stream copy)."),
25
26
  });
27
+ function timestampToSeconds(timestamp) {
28
+ const parts = timestamp.split(":").map(Number);
29
+ if (parts.length === 1)
30
+ return parts[0];
31
+ if (parts.length === 2)
32
+ return parts[0] * 60 + parts[1];
33
+ return parts[0] * 3600 + parts[1] * 60 + parts[2];
34
+ }
26
35
  export async function trimMedia(params, options) {
27
36
  const input = await ensureFileExists(params.inputPath);
28
37
  const output = await ensureOutputDir(params.outputPath);
38
+ const probe = await probeMedia(input, { signal: options?.signal });
39
+ const fileDuration = probe.format.durationSeconds;
40
+ const startSec = timestampToSeconds(params.startTime);
41
+ if (fileDuration > 0 && startSec >= fileDuration) {
42
+ throw new Error(`startTime (${params.startTime} / ${startSec}s) is greater than or equal to file duration (${fileDuration.toFixed(2)}s).`);
43
+ }
44
+ let durationToCut;
45
+ if (params.endTime) {
46
+ const endSec = timestampToSeconds(params.endTime);
47
+ if (endSec <= startSec) {
48
+ throw new Error(`endTime (${params.endTime}) must be later than startTime (${params.startTime}).`);
49
+ }
50
+ const effectiveEndSec = fileDuration > 0 ? Math.min(endSec, fileDuration) : endSec;
51
+ durationToCut = Math.max(0.001, effectiveEndSec - startSec);
52
+ }
53
+ else if (params.duration) {
54
+ const reqDuration = Number(params.duration);
55
+ if (reqDuration <= 0) {
56
+ throw new Error("duration must be a positive number of seconds");
57
+ }
58
+ durationToCut = fileDuration > 0 ? Math.min(reqDuration, Math.max(0.001, fileDuration - startSec)) : reqDuration;
59
+ }
29
60
  const args = ["-y"];
30
61
  // Fast seek before -i
31
62
  args.push("-ss", params.startTime);
32
63
  args.push("-i", input);
33
- if (params.endTime) {
34
- args.push("-to", params.endTime);
35
- }
36
- else if (params.duration) {
37
- args.push("-t", params.duration);
64
+ if (durationToCut !== undefined) {
65
+ args.push("-t", String(durationToCut));
38
66
  }
39
67
  if (params.accurateReencode) {
40
68
  const hwInfo = await detectHwAccel();
@@ -53,6 +81,7 @@ export async function trimMedia(params, options) {
53
81
  const res = await runFfmpeg(args, {
54
82
  signal: options?.signal,
55
83
  onProgress: options?.onProgress,
84
+ expectedDurationSeconds: durationToCut,
56
85
  });
57
86
  return {
58
87
  outputPath: output,
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import { z } from "zod";
3
3
  import { runFfmpeg, ensureFileExists, ensureOutputDir } from "../utils/exec.js";
4
+ import { probeMedia } from "./probe.js";
4
5
  export const generateWaveformSchema = z.object({
5
6
  inputPath: z.string().describe("Path to the audio or video file."),
6
7
  outputPath: z.string().describe("Destination path for the PNG image."),
@@ -19,6 +20,10 @@ export async function generateWaveform(params, options) {
19
20
  const { inputPath, outputPath, width = 1200, height = 280, color = "0x6366f1", scale = "lin", includeBase64 = true } = params;
20
21
  const input = await ensureFileExists(inputPath);
21
22
  const output = await ensureOutputDir(outputPath);
23
+ const probe = await probeMedia(input, { signal: options?.signal });
24
+ if (probe.audioStreams.length === 0) {
25
+ throw new Error(`Cannot generate waveform: input file '${inputPath}' contains no audio streams.`);
26
+ }
22
27
  const filter = `aformat=channel_layouts=mono,showwavespic=s=${width}x${height}:colors=${color}:scale=${scale}`;
23
28
  const args = [
24
29
  "-i", input,
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@ash_j1997/ffmpeg-mcp-server",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "MCP server for FFmpeg and FFprobe media processing",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": {
8
- "ffmpeg-mcp-server": "./dist/index.js"
8
+ "ffmpeg-mcp-server": "dist/index.js"
9
9
  },
10
10
  "files": [
11
11
  "dist"