Last active
September 8, 2026 22:30
-
-
Save jaymcgavren/3f190445e8947babcec3ef2ab8771715 to your computer and use it in GitHub Desktop.
A Ruby script that uses ffmpeg to concatenate multiple videos into one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # Joins videos end to end into one video, in the order they are given. The new | |
| # video is as long as all of them added together. Nothing is cut. | |
| # | |
| # video_join.rb -i intro.mp4 -i gameplay.mp4 -i outro.mp4 whole.mp4 | |
| # | |
| # The videos do not have to match. Each one is made the size, shape and frame | |
| # rate of the first, and a video of a different shape gets black bars rather | |
| # than being stretched. A video with no sound is joined with silence, so the | |
| # sound of the others stays lined up with the picture. | |
| # | |
| # The video is re-encoded at near-lossless quality; the sound is re-encoded too, | |
| # because joining sound from several files means it cannot be copied straight. | |
| require "json" | |
| require "optparse" | |
| require "shellwords" | |
| ENCODE = %w[-c:v libx264 -crf 16 -preset slow -pix_fmt yuv420p] | |
| AUDIO = %w[-c:a aac -b:a 192k] | |
| # The sample rate everything is joined at. All the sound has to match. | |
| RATE = 48000 | |
| # Reads the options, and leaves the output name in argv. | |
| def parse_inputs(argv) | |
| inputs = [] | |
| parser = OptionParser.new do |opt| | |
| opt.banner = "Usage: video_join.rb -i FIRST -i SECOND [-i MORE...] [OUTPUT]" | |
| opt.on("-i", "--input FILE", "a video to join; give this once per video, in order") { |v| inputs << v } | |
| opt.on("-h", "--help") { puts opt; exit } | |
| end | |
| parser.parse!(argv) | |
| abort parser.help if inputs.length < 2 | |
| inputs | |
| end | |
| # Names the output after the first video: intro.mp4 becomes intro.joined.mp4. | |
| def default_output(input) | |
| extension = File.extname(input) | |
| input.delete_suffix(extension) + ".joined" + extension | |
| end | |
| # Asks ffprobe about one video: how big it is, how fast, how long, and whether | |
| # it has any sound. | |
| def probe_video(path) | |
| probe = `ffprobe -v error -show_entries stream=codec_type,width,height,r_frame_rate:format=duration -of json #{Shellwords.escape(path)}` | |
| abort "could not read #{path}" unless $?.success? | |
| probe = JSON.parse(probe) | |
| streams = probe.fetch("streams") | |
| picture = streams.find { |stream| stream["codec_type"] == "video" } | |
| abort "#{path} has no video in it" unless picture | |
| { path: path, | |
| width: picture.fetch("width"), | |
| height: picture.fetch("height"), | |
| rate: picture.fetch("r_frame_rate"), | |
| duration: probe.fetch("format").fetch("duration").to_f, | |
| sound: streams.any? { |stream| stream["codec_type"] == "audio" } } | |
| end | |
| # Lists the files for ffmpeg to open: the videos, then one silence maker for each | |
| # video that has no sound of its own. Notes in each video which input its sound | |
| # comes from. | |
| def ffmpeg_inputs(videos) | |
| files = videos.flat_map { |video| ["-i", video[:path]] } | |
| videos.each_with_index { |video, index| video[:input] = index } | |
| videos.reject { |video| video[:sound] }.each do |video| | |
| video[:input] = files.count("-i") | |
| files += ["-f", "lavfi", "-i", "anullsrc=r=#{RATE}:cl=stereo"] | |
| end | |
| files | |
| end | |
| # Builds the filter graph: make every video match the first one, make every | |
| # sound match as well, then play them one after another. | |
| def filter_graph(videos) | |
| first = videos.first | |
| size = "#{first[:width]}:#{first[:height]}" | |
| steps = [] | |
| joined = [] | |
| videos.each_with_index do |video, index| | |
| steps << "[#{index}:v]scale=#{size}:force_original_aspect_ratio=decrease," \ | |
| "pad=#{size}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=#{first[:rate]},setpts=PTS-STARTPTS[v#{index}]" | |
| # Silence has no end of its own, so it is cut to the length of its video. | |
| silence = video[:sound] ? "" : "atrim=duration=#{video[:duration]}," | |
| steps << "[#{video[:input]}:a]#{silence}asetpts=PTS-STARTPTS," \ | |
| "aformat=sample_rates=#{RATE}:channel_layouts=stereo[a#{index}]" | |
| joined << "[v#{index}][a#{index}]" | |
| end | |
| steps << "#{joined.join}concat=n=#{videos.length}:v=1:a=1[video][sound]" | |
| steps.join(";") | |
| end | |
| inputs = parse_inputs(ARGV) | |
| output = ARGV.shift || default_output(inputs.first) | |
| inputs.each { |path| abort "#{path}: no such file" unless File.exist?(path) } | |
| abort "#{output} already exists; delete it or name another output file" if File.exist?(output) | |
| videos = inputs.map { |path| probe_video(path) } | |
| files = ffmpeg_inputs(videos) | |
| total = videos.sum { |video| video[:duration] } | |
| puts "#{videos.length} videos, #{total.round(1)}s -> #{output}" | |
| exit 1 unless system("ffmpeg", *files, "-filter_complex", filter_graph(videos), | |
| "-map", "[video]", "-map", "[sound]", *ENCODE, *AUDIO, output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment