@ash_j1997/ffmpeg-mcp-server 0.6.1 → 0.6.2

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
@@ -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배 빠른 인코딩을 지원합니다.
@@ -43,7 +63,7 @@ AI 에이전트에게 영상 처리를 직접 명령하면 잘못된 플래그,
43
63
  | **`reformat_aspect_ratio`** | 배경 블러 패딩 또는 중앙 크롭을 적용해 영상 비율을 9:16(세로), 1:1(정사각형), 4:5(포트레이트)로 변환합니다. | `inputPath`, `outputPath`, `targetRatio`, `mode`, `blurAmount`, `padColor`, `hardwareAcceleration` |
44
64
  | **`create_split_screen`** | 두 개의 영상을 상하(9:16 숏폼/릴스) 또는 좌우로 배치하고 오디오 믹싱 및 자막을 합성합니다. | `firstVideoPath`, `secondVideoPath`, `outputPath`, `layout`, `audioSource`, `subtitlesPath` |
45
65
  | **`trim_silence`** | 영상과 음성의 립싱크를 완벽히 유지하면서 녹음/녹화 영상의 무음 구간(침묵)을 감지해 자동으로 잘라냅니다. | `inputPath`, `outputPath`, `mode`, `thresholdDb`, `minDurationSeconds` |
46
- | **`concat_media`** | 여러 비디오 또는 오디오 파일을 순서대로 병합합니다. 스트림 복사 및 재인코딩 방식을 지원합니다. | `inputPaths`, `outputPath`, `mode` |
66
+ | **`concat_media`** | 여러 미디어 파일을 순서대로 병합합니다. 입력 파일을 자동 분석하여 스트림 복사 또는 재인코딩을 선택합니다. | `inputPaths`, `outputPath`, `mode` |
47
67
  | **`generate_waveform`** | 오디오 파형(Waveform) PNG 이미지를 생성합니다. 비전 모델을 위한 base64 데이터를 반환할 수 있습니다. | `inputPath`, `outputPath`, `width`, `height`, `color`, `scale`, `includeBase64` |
48
68
  | **`add_subtitles`** | 비디오 재인코딩 없이 SRT 또는 VTT 자막 트랙을 MP4/MKV 파일에 소프트웨어 자막으로 삽입합니다. | `videoPath`, `subtitlesPath`, `outputPath`, `language`, `title` |
49
69
  | **`burn_subtitles`** | 폰트 크기, 글자 색상, 외곽선, 여백을 커스텀하여 비디오 프레임에 자막을 직접 하드코딩(버닝)합니다. | `videoPath`, `subtitlesPath`, `outputPath`, `fontSize`, `fontColor`, `outlineColor`, `marginV` |
@@ -119,7 +139,8 @@ AI 에이전트에게 영상 처리를 직접 명령하면 잘못된 플래그,
119
139
 
120
140
  ## 감사의 글 (Acknowledgements & Community)
121
141
 
122
- 단순 포맷 변환을 넘어 스트림 멀티플렉싱(`mux_media`) 및 장면 전환 감지 기능(`detect_scenes`)을 제안해 주신 [@rajarshidattapy](https://github.com/rajarshidattapy) 님께 감사드립니다.
142
+ - 단순 포맷 변환을 넘어 스트림 멀티플렉싱(`mux_media`) 및 장면 전환 감지 기능(`detect_scenes`)을 제안해 주신 [@rajarshidattapy](https://github.com/rajarshidattapy) 님께 감사드립니다.
143
+ - 입력 스트림 속성이 다를 때 발생하는 파일 손상을 방지하도록 `concat_media`의 자동 감지(auto-probe) 모드를 제안해 주신 Reddit 사용자 [u/QuanTradin](https://www.reddit.com/user/QuanTradin/) 님께 감사드립니다.
123
144
 
124
145
  ---
125
146
 
package/README.md CHANGED
@@ -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.
@@ -43,7 +63,7 @@ This server provides **19 typed tools** using Zod schemas. The AI passes paramet
43
63
  | **`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
64
  | **`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
65
  | **`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` |
66
+ | **`concat_media`** | Joins multiple media files in order. Automatically probes inputs to select stream copy or re-encoding. | `inputPaths`, `outputPath`, `mode` |
47
67
  | **`generate_waveform`** | Generates a PNG waveform image. Returns base64 image data for vision models. | `inputPath`, `outputPath`, `width`, `height`, `color`, `scale`, `includeBase64` |
48
68
  | **`add_subtitles`** | Embeds SRT or VTT subtitle tracks into MP4/MKV video files without re-encoding video. | `videoPath`, `subtitlesPath`, `outputPath`, `language`, `title` |
49
69
  | **`burn_subtitles`** | Hardcodes subtitles directly onto video frames with customizable font size, colors, and margins. | `videoPath`, `subtitlesPath`, `outputPath`, `fontSize`, `fontColor`, `outlineColor`, `marginV` |
@@ -119,7 +139,8 @@ Run directly with `npx` (no manual cloning or building required):
119
139
 
120
140
  ## Acknowledgements & Community
121
141
 
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.
142
+ - 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.
143
+ - Special thanks to Reddit user [u/QuanTradin](https://www.reddit.com/user/QuanTradin/) for suggesting smart auto-probing in `concat_media` to prevent corrupted outputs when input stream parameters differ.
123
144
 
124
145
  ---
125
146
 
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.2",
29
29
  });
30
30
  function createProgressCallback(extra) {
31
31
  return (p) => {
@@ -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");
@@ -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,
@@ -23,6 +23,14 @@ export const trimMediaSchema = z.object({
23
23
  .optional()
24
24
  .describe("Re-encode video for cuts between keyframes. Default: false (uses fast stream copy)."),
25
25
  });
26
+ function timestampToSeconds(timestamp) {
27
+ const parts = timestamp.split(":").map(Number);
28
+ if (parts.length === 1)
29
+ return parts[0];
30
+ if (parts.length === 2)
31
+ return parts[0] * 60 + parts[1];
32
+ return parts[0] * 3600 + parts[1] * 60 + parts[2];
33
+ }
26
34
  export async function trimMedia(params, options) {
27
35
  const input = await ensureFileExists(params.inputPath);
28
36
  const output = await ensureOutputDir(params.outputPath);
@@ -31,7 +39,11 @@ export async function trimMedia(params, options) {
31
39
  args.push("-ss", params.startTime);
32
40
  args.push("-i", input);
33
41
  if (params.endTime) {
34
- args.push("-to", params.endTime);
42
+ const duration = timestampToSeconds(params.endTime) - timestampToSeconds(params.startTime);
43
+ if (duration <= 0) {
44
+ throw new Error("endTime must be later than startTime");
45
+ }
46
+ args.push("-t", String(duration));
35
47
  }
36
48
  else if (params.duration) {
37
49
  args.push("-t", params.duration);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ash_j1997/ffmpeg-mcp-server",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "MCP server for FFmpeg and FFprobe media processing",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",