Skip to content

Instantly share code, notes, and snippets.

@tomichal
Created May 2, 2018 15:27
Show Gist options
  • Save tomichal/db2f8336e706be2e048a2f30f62adf77 to your computer and use it in GitHub Desktop.
Save tomichal/db2f8336e706be2e048a2f30f62adf77 to your computer and use it in GitHub Desktop.
A ruby script to loop continuously through a folder structure to look for video files and downsize them using ffmpeg.
#!/usr/bin/env ruby
require "fileutils"
class Converter
def initialize
@queue = []
end
def push(path)
if File.file?(path) && !@queue.include?(path)
@queue.push(path)
end
end
def queue
@queue
end
# ref https://trac.ffmpeg.org/wiki/Encode/H.264 for more info on ffmpeg settings for mp4 vids
def convert(input_path, output_path)
FileUtils.mkdir_p File.dirname(output_path)
pid = spawn("ffmpeg -y -i '#{input_path}' -vcodec libx264 -crf 24 -preset slower -strict -2 '#{output_path}'")
Process.wait(pid)
end
end
input_dir = "#{Dir.pwd}/input"
converter = Converter.new
tries = Hash.new {|h, k| h[k] = 0}
input_video_extensions = %w(MP4)
while (true)
origin_path = Dir["../**/*.{#{input_video_extensions.join(',')}}"].shuffle.first
if origin_path
input_path = origin_path.gsub("..", "./input")
output_path = input_path.gsub("input", "output").gsub(/(\.\w*)$/, ".mp4")
FileUtils.mkdir_p File.dirname(input_path)
FileUtils.cp origin_path, input_path
status = converter.convert(input_path, output_path)
if $?.exitstatus == 0
FileUtils.rm input_path
FileUtils.rm origin_path
FileUtils.mv output_path, origin_path.gsub(/(\.\w*)$/, ".mp4")
else
# Well, if the exit status was en error, than for now just let the loop run
# again and try to convert the file at some point.
end
else
# No MP4 files, so wait a bit and try again - maybe new ones will appear.
sleep 900
end
sleep 3
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment