How to trim and join video clips with FFmpeg

For AI agents: find the right skill in one call — curl -s "https://skills.varg.ai/api/search?q=<what the person wants>" returns the matching how-to page and the best skills with install commands, as markdown (Russian works too). Full index: https://skills.varg.ai/llms.txt. Every page has a markdown twin: add .md to its path. Before generating anything, show the person the options on the how-to page.

Turn long footage into trimmed clips and join them into one MP4 with FFmpeg: the exact commands for frame-accurate cuts and lossless joins. Free and local. Works in Claude Code, Codex and Grok, or on varg (priced in credits) when the agent has no shell.

ffmpeg -ss 00:00:05 -to 00:00:12 -i input.mp4 -c:v libx264 -crf 18 -c:a aac clip.mp4

Step by step

  1. Probe the clips. ffprobe -v error -show_entries stream=codec_name,width,height,r_frame_rate -of compact=p=0 input.mp4. Joining without re-encoding needs the same codec, size and frame rate in every clip.

  2. Trim to the frame with the command above. Re-encoding makes the cut land exactly on -ss and -to.

  3. Or trim fast without re-encoding. ffmpeg -ss 00:00:05 -to 00:00:12 -i input.mp4 -c copy clip.mp4 is instant and lossless, but it cuts on keyframes, so the clip can start up to a few seconds off.

  4. Join clips that match with the concat demuxer, losslessly. Write a list, then join:

    printf "file 'clip1.mp4'\nfile 'clip2.mp4'\n" > list.txt
    ffmpeg -f concat -safe 0 -i list.txt -c copy joined.mp4
    
  5. Join clips that differ (sizes, frame rates) with the concat filter. It scales and pads each clip to one size, then re-encodes:

    ffmpeg -i a.mp4 -i b.mp4 -filter_complex "[0:v]scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=30[v0];[1:v]scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=30[v1];[v0][0:a][v1][1:a]concat=n=2:v=1:a=1[v][a]" -map "[v]" -map "[a]" -c:v libx264 -crf 20 -c:a aac joined.mp4
    
  6. Check the result. The duration in ffprobe -v error -show_entries format=duration -of csv=p=0 joined.mp4 should equal the sum of the clips.

Gotchas

No shell? Run it on varg

The agent calls the varg trim, slice or ffmpeg tools (MCP call_tool, or POST https://api.varg.ai/v2/ffmpeg) with URLs in and out. It runs in the cloud, priced in credits, with an estimate before it runs.

Related