Skip to content

Instantly share code, notes, and snippets.

@reidmorrison
Created September 20, 2019 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reidmorrison/3859882b69245d16e9689e0d3f67268b to your computer and use it in GitHub Desktop.
Save reidmorrison/3859882b69245d16e9689e0d3f67268b to your computer and use it in GitHub Desktop.
Re-Encode local video files using the H.265 compression method
#
# Re-encode video files with the more efficient h.265 file format.
#
# The original file is appended with the extension `.original` once successfully converted.
# The new file has the .MOV extension.
#
require 'pathname'
EXTENSIONS = "m2ts,flv,mov,wmv,avi,mp4,mpg,m4a,3gp,3g2,mj2"
Pathname.glob("**/*.{#{EXTENSIONS}}", File::FNM_CASEFOLD | File::FNM_EXTGLOB).each do |path|
next if path.directory?
puts "=================================================================================================="
name = path.basename(path.extname)
output_path = path.dirname.join("#{name}.MOV")
temp_path = path.dirname.join("#{name}.temp.MOV")
original_path = path.dirname.join("#{name}#{path.extname}.original")
originals = Pathname.glob("**/*#{name}.{#{EXTENSIONS}}.original", File::FNM_CASEFOLD | File::FNM_EXTGLOB)
unless originals.empty?
puts "Already converted: #{path}"
next
end
puts "Converting: #{path} to: #{output_path} via: #{temp_path}. Old: #{original_path}"
begin
# Incomplete previous run?
temp_path.delete if temp_path.exist?
cmd = "ffmpeg -hide_banner -i \"#{path}\" -c:v libx265 -preset medium -tag:v hvc1 -pix_fmt yuv420p \"#{temp_path}\""
# puts cmd
`#{cmd}`
if exc = $!
raise(exc)
end
temp_path.utime(path.mtime, path.mtime)
path.rename(original_path)
temp_path.rename(output_path)
rescue StandardError => exc
puts "#{path}: #{exc.class}: #{exc.message}"
ensure
temp_path.delete if temp_path.exist?
end
end.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment