Skip to main content
Glama
README.md
# video-editing-mcp

Local video editing for AI agents — an **MCP server** plus a verified command-line toolkit, and offline **Hindi / English / Hinglish speech-to-text** for subtitles.

No cloud, no API keys, no uploads. Everything runs on your own machine with `ffmpeg`.

---

## What this is

Three things that work together:

| Part | What it does |
|---|---|
| `server.py` | An [MCP](https://modelcontextprotocol.io) server exposing **13 video-editing tools** to any MCP-capable agent (Claude Desktop, Cursor, Codex, …) |
| `video_edit.py` | The engine and a full CLI. 11-check self-test. Every command self-verifies |
| `asr.py` | Offline speech-to-text for burning subtitles, or finding where a phrase is spoken |

The point is not "another ffmpeg wrapper". It is that **every result is measured, not assumed** — see [Why this exists](#why-this-exists).

---

## Requirements

* **ffmpeg** on your `PATH` (any recent build; a full build gives you the most filters)
* **Python 3.10+**

```bash
ffmpeg -version      # must print a version
python --version
```

---

## Install

```bash
git clone https://github.com/akshayai1996/video-editing-mcp.git
cd video-editing-mcp
pip install -r requirements.txt
```

Verify your setup — this exercises the real code paths:

```bash
python video_edit.py selftest     # 11 checks, all must PASS
python verify_repo.py             # also checks the MCP handshake
```

Speech-to-text models download once (~255 MB) and then run offline:

```bash
python asr.py --download
python asr.py --check             # should say "all models present"
```

---

## Quick start (command line)

```bash
# 1. what am I dealing with?
python video_edit.py probe input.mp4

# 2. cut the dead air out of a talking-head clip
python video_edit.py autocut input.mp4 tight.mp4

# 3. trim a range   (start  end, in seconds)
python video_edit.py cut input.mp4 clip.mp4 12.5 30

# 4. burn subtitles
python video_edit.py subs clip.mp4 final.mp4 subs.ass

# 5. check the result
python video_edit.py verify final.mp4 --expect 17.5
```

---

## Use it as an MCP server

Register it with any MCP client. Example for a stdio client:

```json
{
  "mcpServers": {
    "video-editing": {
      "command": "python",
      "args": ["/absolute/path/to/video-editing-mcp/server.py"]
    }
  }
}
```

Or run it over HTTP:

```bash
python server.py --http --port 8787
```

Then just ask your agent, in plain language:

> "Remove the silence from interview.mp4 and burn subtitles from the transcript."

The agent calls `probe` → `autocut` → `subtitles` → `verify`.

### The 13 tools

| Tool | Purpose |
|---|---|
| `probe` | Duration, codecs, resolution, fps, frame count, real decoded audio length |
| `cut` | Extract a time range (lossless stream-copy or exact re-encode) |
| `concat` | Join clips, optionally normalising mismatched sources |
| `speed` | Retime video + audio together, pitch preserved |
| `autocut` | Remove dead air, with padding so speech isn't clipped |
| `scenes` | Detect scene changes; optionally write an EDL and render each scene |
| `write_edl` | CMX 3600 edit list for Premiere / Resolve / Final Cut |
| `subtitles` | Burn a subtitle track from `[{start, end, text}]` |
| `title` | Overlay a centred title card |
| `gif` | Two-pass palette GIF export |
| `thumbnail` | Grab a frame, or auto-pick the best one |
| `normalize` | EBU R128 loudness normalisation |
| `verify` | Check A/V sync and expected length |

Every tool returns a dict containing measured values. `verify` and the mutating
tools include an explicit `ok` flag.

---

## Speech-to-text (subtitles)

Offline, CPU-only, one Roman-script line per segment.

```bash
python asr.py meeting.wav                 # lines with timestamps
python asr.py video.mp4 --srt out.srt     # write a subtitle file
python asr.py audio.wav --fast            # quicker, Shruti only
python asr.py audio.wav --json            # machine-readable
```

Hindi is written **the way people type it** rather than translated:

```
[    0.5-    2.3] hi  kal ki meeting postpone kar do
[    2.8-    5.1] en  the vendor confirmed delivery
```

Then burn it straight in:

```bash
python asr.py video.mp4 --srt subs.srt
python video_edit.py subs video.mp4 final.mp4 subs.ass
```

### Models

Downloaded automatically on first use (`--download` to fetch them up front,
`--check` to inspect). Stored in `~/whisper_models`, or set `ASR_MODELS`.

| Model | Role | Size |
|---|---|---|
| `udgamlabs/Shruti-ONNX` | Reads every line, keeps English words in Latin | ~53 MB |
| `adalat-ai/koyal-hi-120m-1.0-onnx` | Accurate pass for pure-Hindi lines | ~201 MB |
| `silero_vad.onnx` | Speech/silence segmentation | ~0.6 MB |

Optional: `--indic` uses `OpenVoiceOS/ai4bharat-indicconformer-hi-onnx` instead of Koyal.

All models are fetched from the Hugging Face Hub and are free to use; see each
model card for its licence.

---

## Why this exists

Most editing scripts report success when `ffmpeg` exits 0. That is not the same
as being correct. Seven real bugs were found here by measuring the output
instead of trusting the exit code — each one produced a silently wrong video:

| # | Trap | What actually happens |
|---|---|---|
| 1 | `-avoid_negative_ts make_zero` on a stream-copy cut | A `[2s,6s]` cut of a 10s file produced **180 frames (6.0s)** instead of 120 (4.0s) |
| 2 | `filter.format(**loudnorm_stats)` | The measurement JSON has only `input_*`/`output_*` keys — `KeyError: 'I'` |
| 3 | Absolute Windows paths in a filtergraph | `ass=C:\...` is parsed as a size spec and the filter refuses to start |
| 4 | `select` / `aselect` for cuts | Frames are dropped but **timestamps are not rebased**, so the file still reports its original length |
| 5 | Inverting silence into "keep" ranges | Easy to forget the head before the first silence; the opening is silently discarded |
| 6 | `overlay` of a 1-frame PNG with `shortest=1` | Truncates the whole video to a single frame |
| 7 | `overlay` without `-map` | A silent overlay input can take over the audio track |

So the rule here is: **verify by decoding, never by metadata.**

* audio length → decode PCM and count samples (`real_audio_seconds`)
* frame count → `ffprobe -count_frames`
* did the burn-in render → extract a frame and look at it

Container duration is not trustworthy after filtering. A correctly cut 3.6s
file will still *claim* 7.1s, because the stream kept its original timestamps.

---

## Skill guide: what to reach for

### Cutting
```bash
python video_edit.py cut in.mp4 out.mp4 5 12.5            # exact, re-encode
python video_edit.py cut in.mp4 out.mp4 5 12.5 --copy     # instant, lossless
```
`--copy` is lossless but only frame-accurate at keyframes. Prefer it for large
files, and verify the duration afterwards either way.

### Removing silence
```bash
python video_edit.py autocut talk.mp4 tight.mp4 --margin 0.2
```
`--margin` (default `0.1`) pads each kept range on both sides. Cutting exactly
at the silence edge clips the first and last syllable. Raise it for slow,
deliberate speech; lower it for punchy pacing.

### Joining clips
```bash
python video_edit.py concat out.mp4 a.mp4 b.mp4 c.mp4            # fast, same codec
python video_edit.py concat out.mp4 a.mp4 b.mp4 --encode         # mixed sources
```
Prefer per-segment cut → concat over long chains of crossfades; fades do not
accumulate errors the way chained transitions can.

### Scene detection and handoff to an editor
```bash
python video_edit.py scenes in.mp4 --edl cut.edl --split-prefix shot
```
`--split-prefix` writes `shot_01.mp4`, `shot_02.mp4`, … The EDL imports into
Premiere, Resolve, Final Cut and Kdenlive, so your automatic decisions are not
trapped in a rendered file.

### Subtitles and titles
```bash
python video_edit.py subs in.mp4 out.mp4 subs.ass
python video_edit.py title in.mp4 out.mp4 "Chapter One" --seconds 3
```
Titles are drawn with a soft shadow over the picture — not black title cards.

### Speed
```bash
python video_edit.py speed in.mp4 out.mp4 2.0     # 2x faster, pitch kept
```
Audio ends up marginally shorter than video after a speed change, so run
`verify` afterwards and pad if needed.

### Audio
```bash
python video_edit.py norm in.mp4 out.mp4 --lufs -16
```
Two-pass EBU R128. `-16 LUFS` for web, `-14` for streaming platforms.

### Exporting
```bash
python video_edit.py gif in.mp4 out.gif --fps 15 --width 480 --start 2 --duration 3
python video_edit.py thumb in.mp4 cover.jpg            # auto-picks a frame
python video_edit.py thumb in.mp4 cover.jpg --at 12.5  # or an exact time
```

---

## API (Python)

```python
import video_edit as ve

info = ve.probe("in.mp4")
print(info["video"]["width"], info["audio_seconds_real"])

ve.autocut("in.mp4", "tight.mp4", margin=0.2)
ve.cut("tight.mp4", "clip.mp4", 1.0, 6.5)

result = ve.verify_av("clip.mp4", expect=5.5)
assert result["ok"], result["issues"]
```

---

## Encoding notes

Measured on a 4-core laptop CPU, 1080p30, 20-second source:

| Encoder | Speed |
|---|---|
| `libx264 -preset medium` | ~1.0× realtime |
| `libx264 -preset ultrafast` | ~3.1× realtime |
| `h264_qsv` (Intel Quick Sync) | ~4.0× realtime |

Practical consequence: a 20-minute edit takes about 20 minutes at `medium`.
Use `ultrafast` for drafts, and a hardware encoder for full-length renders
when your machine has one. Check what you have:

```bash
ffmpeg -hide_banner -encoders | findstr /I "h264 hevc"
```

---

## Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| `Unable to parse option value ... as image size` | Absolute path inside a filtergraph | Run `ffmpeg` from the working directory and pass a relative filename |
| Output longer than the range you asked for | `-avoid_negative_ts make_zero` on a copy cut | Drop that flag |
| File still reports the old duration after cutting | `select`/`aselect` leaves timestamps stale | Use `trim`+`atrim`, then verify by decoding |
| Video becomes one frame after overlaying a PNG | `shortest=1` with a single-frame image | Use `enable='between(t,0,N)'` instead |
| Audio disappeared after an overlay | The silent overlay input won the stream selection | Always pass `-map "[vout]" -map "0:a?"` |
| `KeyError: 'I'` from loudness normalisation | Stats JSON only has `input_*`/`output_*` | Supply the targets yourself; read `measured_*` from the stats |
| `asr.py` cannot find models | Not downloaded yet | `python asr.py --download` |
| Romanised words look odd | Rule-based romanisation | Add the word to the `ENGLISH` table in `deva_roman.py` |

---

## Files

```
server.py          MCP server -- 13 tools
video_edit.py      editing engine + CLI + self-test
asr.py             speech-to-text, model download, SRT output
deva_roman.py      Devanagari -> Roman Hinglish
verify_repo.py     end-to-end check of everything above
requirements.txt
```

---

## Licence

MIT for the code in this repository. The speech models are downloaded
separately from the Hugging Face Hub and keep their own licences.