Skip to content

Instantly share code, notes, and snippets.

@jaymcgavren
Last active September 8, 2026 05:53
Show Gist options
  • Select an option

  • Save jaymcgavren/521bf6a37e331bdbe8a6b439634df50e to your computer and use it in GitHub Desktop.

Select an option

Save jaymcgavren/521bf6a37e331bdbe8a6b439634df50e to your computer and use it in GitHub Desktop.
A Ruby script that uses ffmpeg to add one or more text overlays to a video.
#!/usr/bin/env ruby
# Draws one or more text overlays on a video. Each overlay has its own text,
# timing, font, size, alignment and position. Text is white with a black
# outline, and can sit on an optional semi-transparent box.
#
# Every --text starts a new overlay. Options before the first --text set the
# defaults for all overlays; options after one apply to that overlay only.
#
# video_text.rb --font "Pixelify Sans" \
# -t 'New\nGame\nGenie\nCodes' -s 0 -d 2 --box \
# -t 'change\nenemies\nin stages' -s 2 -d 4 -x 0.5 -y 0.7 \
# title.mp4
#
# Positions are fractions of the frame, so they hold at any aspect ratio: 0 is
# the left or top edge, 1 the right or bottom edge, 0.5 the middle.
#
# Lines break where you write \n. They break nowhere else unless you ask for
# --wrap, which is a fraction of the frame width the text has to fit in. The
# script measures the words in their own font and size, so wrapping holds for
# any font, any size and any frame width. Breaks you wrote are always kept.
#
# The video is re-encoded at near-lossless quality; the audio is copied untouched.
require "json"
require "optparse"
require "shellwords"
require "tempfile"
ENCODE = %w[-c:v libx264 -crf 16 -preset slow -pix_fmt yuv420p -c:a copy]
DEFAULTS = { start: 0.0, duration: 3.0, font: "Helvetica", size: nil,
align: "center", x: 0.5, y: 0.5, box: false, box_opacity: 0.5,
wrap: nil }
# Reads the options into a list of overlays, and leaves the file names in argv.
def parse_overlays(argv)
defaults = DEFAULTS.dup
overlays = []
# Send a setting to the overlay being built, or to the defaults if there is none yet.
assign = lambda { |key, value| (overlays.last || defaults)[key] = value }
parser = OptionParser.new do |opt|
opt.banner = "Usage: video_text.rb [options] INPUT [OUTPUT]"
opt.on("-t", "--text TEXT", "start an overlay; \\n makes a line break") { |v| overlays << defaults.merge(text: v) }
opt.on("-s", "--start SECS", Float, "when it appears (default: #{defaults[:start]})") { |v| assign.call(:start, v) }
opt.on("-d", "--duration SECS", Float, "how long it stays (default: #{defaults[:duration]})") { |v| assign.call(:duration, v) }
opt.on("-f", "--font NAME", "any font name fontconfig knows (default: #{defaults[:font]})") { |v| assign.call(:font, v) }
opt.on("-a", "--align WORD", %w[left center right], "left, center or right (default: #{defaults[:align]})") { |v| assign.call(:align, v) }
opt.on("-x", "--x FRACTION", Float, "0 at the left edge, 1 at the right (default: #{defaults[:x]})") { |v| assign.call(:x, v) }
opt.on("-y", "--y FRACTION", Float, "0 at the top edge, 1 at the bottom (default: #{defaults[:y]})") { |v| assign.call(:y, v) }
opt.on("--size PIXELS", Integer, "text height (default: video height / 12)") { |v| assign.call(:size, v) }
opt.on("--box", "draw a box behind the text (default: no box)") { assign.call(:box, true) }
opt.on("--box-opacity NUM", Float, "0 to 1 (default: #{defaults[:box_opacity]})") { |v| assign.call(:box_opacity, v) }
opt.on("--wrap FRACTION", Float, "break lines to fit this much of the frame width, like 0.9 (default: no wrapping)") { |v| assign.call(:wrap, v) }
opt.on("-h", "--help") { puts opt; exit }
end
parser.parse!(argv)
abort parser.help if argv.empty?
abort "give at least one --text" if overlays.empty?
overlays.each do |overlay|
wrap = overlay[:wrap]
abort "--wrap wants a fraction over 0 and no more than 1" if wrap && !(wrap > 0 && wrap <= 1)
end
overlays
end
# Names the output after the input: clip.mp4 becomes clip.text.mp4.
def default_output(input)
extension = File.extname(input)
input.delete_suffix(extension) + ".text" + extension
end
# Asks ffprobe how big the frames are, so text can be sized and wrapped to fit.
def video_size(input)
probe = `ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of json #{Shellwords.escape(input)}`
abort "could not read #{input}" unless $?.success?
stream = JSON.parse(probe).fetch("streams").first
[stream.fetch("width"), stream.fetch("height")]
end
# How thick the outline round the letters is.
def outline(size)
size / 12 + 1
end
# How much space the box keeps round the letters.
def padding(size)
size / 2
end
# The space to keep clear at each edge for whatever is drawn outside the letters.
def margin(overlay, size)
outline(size) + (overlay[:box] ? padding(size) : 0)
end
# Puts one text in a file, so no character in it needs escaping. The caller must
# keep the file until ffmpeg has finished reading it.
def text_file(text)
file = Tempfile.new("overlay")
file.write(text)
file.close
file
end
# Measures how wide each of the given strings is when drawn, in pixels. They are
# drawn white on black, one per line and far apart, and the lit pixels in each
# band are counted. One ffmpeg run measures the whole list.
def ink_widths(strings, font, size)
file = text_file(strings.join("\n"))
width = ((strings.map(&:length).max * 1.5).ceil + 4) * size
height = (strings.length + 2) * 2 * size
image = Tempfile.new(["measure", ".raw"])
drawn = system("ffmpeg", "-v", "error", "-f", "lavfi", "-i", "color=c=black:s=#{width}x#{height}:d=1",
"-frames:v", "1",
"-vf", "drawtext=textfile=#{file.path}:expansion=none" \
":font=#{font}:fontsize=#{size}:fontcolor=white" \
":line_spacing=#{size / 2}:x=0:y=0",
"-f", "rawvideo", "-pix_fmt", "gray", "-y", image.path)
abort "could not measure the text in #{font} at #{size} pixels" unless drawn
pixels = File.binread(image.path)
bands = []
height.times do |row|
line = pixels.byteslice(row * width, width)
first = line.index(/[^\x00]/n)
if first.nil?
bands << nil unless bands.last.nil? # a blank row ends the band above it
else
last = line.rindex(/[^\x00]/n)
bands[-1] = bands.last ? [bands.last, last - first + 1].max : last - first + 1
end
end
bands = bands.compact
abort "could not tell #{strings.length} words apart while measuring" unless bands.length == strings.length
bands
end
# Breaks text into lines that fit in limit pixels. Breaks already in the text are
# kept. A word wider than the limit on its own is left long, because the script
# never breaks a word in half.
def wrap_text(text, limit, font, size)
lines = text.split("\n", -1)
words = lines.flat_map(&:split).uniq
return text if words.empty?
# "A" and "A A" are measured as well: the difference between them is how much
# width a space adds.
widths = ink_widths(words + ["A", "A A"], font, size)
space = [widths[-1] - 2 * widths[-2], 0].max
width = words.zip(widths).to_h
lines.flat_map { |line| wrap_line(line.split, width, space, limit) }.join("\n")
end
# Fills each line with as many words as fit, then starts the next one.
def wrap_line(words, width, space, limit)
return [""] if words.empty?
lines = [[words.first]]
used = width[words.first]
words.drop(1).each do |word|
grown = used + space + width[word]
if grown > limit
lines << [word]
used = width[word]
else
lines.last << word
used = grown
end
end
lines.map { |line| line.join(" ") }
end
# Builds the filter that draws one overlay. text_w and text_h are the size of the
# drawn text, so a fraction of 0 or 1 puts the whole block just inside the frame.
# The outline and the box are drawn outside that size, so keep a margin for them.
def drawtext(overlay, text_path, size)
edge = margin(overlay, size)
filter = "drawtext=textfile=#{text_path}:expansion=none" \
":font=#{overlay[:font]}:fontsize=#{size}:text_align=#{overlay[:align]}" \
":fontcolor=white:bordercolor=black:borderw=#{outline(size)}" \
":x=#{edge}+(w-text_w-#{2 * edge})*#{overlay[:x]}" \
":y=#{edge}+(h-text_h-#{2 * edge})*#{overlay[:y]}" \
":enable='between(t,#{overlay[:start]},#{overlay[:start] + overlay[:duration]})'"
filter += ":box=1:boxcolor=black@#{overlay[:box_opacity]}:boxborderw=#{padding(size)}" if overlay[:box]
filter
end
# The text to draw for one overlay: \n turned into real line breaks, then broken
# up further if --wrap asked for it.
def overlay_text(overlay, size, video_width)
text = overlay[:text].gsub('\n', "\n")
return text unless overlay[:wrap]
limit = video_width * overlay[:wrap] - 2 * margin(overlay, size)
abort "--wrap #{overlay[:wrap]} leaves no room for #{size} pixel text" unless limit > 0
wrap_text(text, limit, overlay[:font], size)
end
overlays = parse_overlays(ARGV)
input = ARGV.shift
output = ARGV.shift || default_output(input)
abort "#{input}: no such file" unless File.exist?(input)
abort "#{output} already exists; delete it or name another output file" if File.exist?(output)
video_width, video_height = video_size(input)
sizes = overlays.map { |overlay| overlay[:size] || video_height / 12 }
files = overlays.zip(sizes).map { |overlay, size| text_file(overlay_text(overlay, size, video_width)) }
filters = overlays.zip(files, sizes).map { |overlay, file, size| drawtext(overlay, file.path, size) }
puts "#{filters.length} text overlays -> #{output}"
exit 1 unless system("ffmpeg", "-i", input, "-vf", filters.join(","), *ENCODE, output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment