Editing videos with ffmpeg and mpv

I like to take underwater footage with my camera when I am diving. I created a diving page to share those videos (and some commentary on my diving trips) but editing videos was always very boring and slow for me.

I tried to use editors like OpenShot, but I find them extremely slow and hard to use with a million buttons on the UI. Since my laptop is also not very fast (it does not even have a dedicated GPU), I decided to try ffmpeg directly. It worked out quite well.

While developing my workflow I came across the scripting capabilities of mpv, which are extremely useful for editing files fast video files fast.

Trimming videos

The videos I shoot can be quite long, so the main edit that I do is trimming them to the actually meaningful parts I would like people to see.

You can visualize a specific period using mpv, for example the command below plays the first 20 secs of a video

mpv --start=0 --end=20 --loop-file=inf input.MP4
How to visualize the first 20 seconds of a video with mpv

But even better, you can just press l twice to setup a loop while you are watching a video on mpv. When I discovered I immediately tried to figure out how to create clips out of these, and turns out that is not only possible but also easy to set up.

Scripting mpv

The killer mpv feature is that you can script it with lua. The scripts are placed inside ~/.config/mpv/scripts. Useful documentation can be found on the official reference.

Here are the scripts I use:

local mp = require("mp")

local function delete_current()
	local p = mp.get_property("path")
	mp.osd_message(p, 3)
	mp.commandv("run", "gio", "trash", p)
	mp.osd_message("Deleted Video", 3)
end

mp.add_key_binding("ctrl+d", "delete-current-file", delete_current)
Lua script to delete a file while viewing it on mpv.

It's also quite easy to rename a file. The one detail here is that you need to rename the file, put it on the next position of the mpv playlist and then remove the current video from the playlist.

local mp = require("mp")
local input = require("mp.input")
local utils = require("mp.utils")

mp.add_key_binding("ctrl+r", "toggle-to-edit", function()
	mp.set_property_native("pause", true)
	input.get({
		prompt = "New File Name: ",
		closed = function()
			mp.set_property_native("pause", false)
		end,
		submit = function(new_name)
			local p = mp.get_property("path")
			local file_parent, file_name = utils.split_path(p)
			local file_ext = file_name:match("%.([^%.]+)$") or ""
			local new_p = utils.join_path(file_parent, new_name .. "." .. file_ext)
			local p_idx = mp.get_property("playlist-pos")

			local ok, err = os.rename(p, new_p)
			if not ok then
				mp.osd_message("Rename failed: " .. tostring(err), 3)
				return
			end
			mp.command_native({
				name = "loadfile",
				url = new_p,
				flags = "insert-next",
			})

			mp.commandv("playlist-remove", p_idx)
		end,
	})
end)
Lua script to rename a file in place. Because getting an input is async, this command needs to be wrapped a bit differently. Also pauses the video during renaming.

It's also easy to create a clip out of a video after you setup a loop using l, by calling ffmpeg insite mpv.

local mp = require("mp")
local utils = require("mp.utils")

local function take_trim()
	local a = string.format("%.1f", mp.get_property_number("ab-loop-a"))
	local b = string.format("%.1f", mp.get_property_number("ab-loop-b"))
	if not a or not b then
		mp.osd_message("Set both A and B first (press l twice)")
		return
	end

	local p = mp.get_property("path")
	local file_parent, file_name = utils.split_path(p)
	local file_name_no_ext = mp.get_property("filename/no-ext")
	local file_ext = file_name:match("%.([^%.]+)$") or ""

	local clip_name = file_name_no_ext .. "-clip-" .. a .. "-" .. b .. "." .. file_ext
	local clip_path = utils.join_path(file_parent, clip_name)

	-- Run ffmpeg
	-- ffmpeg -ss 0 -to 15 -i GX011104.MP4 -c copy down-blue-hole.mp4
	mp.commandv("run", "ffmpeg", "-ss", a, "-to", b, "-i", p, "-c", "copy", clip_path)
end

mp.add_key_binding("ctrl+t", "trim-clip", take_trim)
Lua script to create a clip out of a video. Only works when a loop is setup on mpv.

My editing workflow

Usually I copy all files from my camera into my laptop, and place them into a folder like gozo-nov-2026. Then, I use mpv to play all videos inside the folder:

mpv *
Opening a playlist with all videos on mpv

which opens a playlist that lets me navigate the files with > and <. I go through the files one by one and delete them, rename them or takes clips from the video using the script above.

Afterwards, I move all my clips and videos that I wish to post on my diving page to ~/Videos/unprocessed-web-videos/, and call a processing zsh script:

#!/usr/bin/env zsh
set -euo pipefail

cd "${0:A:h}"

SRC_DIR="$HOME/Videos/unprocessed-web-videos"
VIDEO_DIR="$HOME/Videos/web-videos"
WATERMARK="underwater.djrmarques.dev"
WATERMARK_OPACITY="0.06"

for f in "$SRC_DIR"/**/*.MP4(N) "$SRC_DIR"/**/*.mp4(N); do
  dir="${f:h}"
  name="${f:t}"
  base="${name%.*}"

  poster="$dir/${base}.webp"
  duration=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$f")
  midpoint=$(awk -v d="$duration" 'BEGIN { print d / 2 }')
  echo "Generating $poster"
  ffmpeg -y -loglevel error -ss "$midpoint" -i "$f" -vframes 1 -vf "scale=640:-2" "$poster"

  echo "Watermarking and transcoding $f to H.264"
  tmp="${f}.tmp.mp4"
  # -c:v libx264: encode video as H.264 (supported by all browsers)
  # -pix_fmt yuv420p: 8-bit 4:2:0 output for broad compatibility
  # -c:a copy: keep the existing audio stream without re-encoding
  # -movflags +faststart: move metadata to the start for progressive playback
  # drawtext: subtle watermark in the bottom-right corner
  ffmpeg -y -loglevel error -i "$f" \
    -vf "drawtext=font='DejaVu Sans':text='$WATERMARK':fontcolor=white@$WATERMARK_OPACITY:fontsize=24:x=w-tw-24:y=h-th-24" \
    -c:v libx264 -pix_fmt yuv420p -c:a copy \
    -movflags +faststart "$tmp"

  mv "$tmp" "$f"
  mv -i "$f" "$VIDEO_DIR/$name"
  mv -i "$poster" "$VIDEO_DIR/${base}.webp"
done
Script to process the videos

This script does a few thing:

Sources