Skip to content

Instantly share code, notes, and snippets.

@xtuaok
Last active January 7, 2020 00:31
Show Gist options
  • Save xtuaok/4264723 to your computer and use it in GitHub Desktop.
Save xtuaok/4264723 to your computer and use it in GitHub Desktop.
TS encode script
#!/usr/bin/ruby
# -*- encoding: UTF-8 -*-
# AUDIO_CODEC=" -acodec copy -absf aac_adtstoasc"
AUDIO_CODEC=" -acodec libfaac -aq 110"
acodec = AUDIO_CODEC
file = File::expand_path( ARGV[0] )
out = ARGV[1]
exit 1 unless File.exist?(file)
audio = []
video = []
sizeopt = "1280x720"
program = nil
IO::popen("ffmpeg -i '#{file}' 2>&1") do |io|
while line = io.gets
begin
if /Program (\d+)/ =~ line and program.nil?
program = $1.to_i
end
if /Stream #([\d:]+)\[.+?Video/ =~ line
video.push($1)
if /DAR 4:3/ =~ line
sizeopt = "640x480 -aspect 4:3 -x264opts weightp=2"
end
if /720x480 \[SAR 32:27 DAR 16:9\]/ =~ line
# sizeopt = "720x480 -aspect 16:9 -flags +ilme+ildct -top -1 -x264opts weightp=0"
sizeopt = "720x480 -aspect 16:9 -x264opts weightp=2"
end
if /1440x1080 \[SAR 4:3 DAR 16:9\]/ =~ line
# sizeopt = "1440x1080 -aspect 16:9 -flags +ilme+ildct -top -1 -x264opts weightp=0"
sizeopt = "1280x720 -aspect 16:9 -x264opts weightp=2"
end
end
if /Stream #([\d:]+)\[.+?Audio/ =~ line
audio.push($1)
end
rescue
end
end
end
cmd = Array.new
cmd << "ffmpeg -y -i \"#{file}\""
cmd << "-map #{video[0]}"
cmd << "-map #{audio[0]}"
cmd << acodec
cmd << "-vcodec libx264"
cmd << "-s #{sizeopt}"
cmd << "-level 41"
cmd << "-threads auto"
cmd << "-8x8dct 1"
cmd << "-coder 1"
cmd << "-qmax 51 -qdiff 8 -qmin 16 -qcomp 0.60"
cmd << "-me_method umh -me_range 32 -trellis 2"
cmd << "-refs 3 -subq 5"
cmd << "-flags +loop"
cmd << "-direct-pred 3"
cmd << "-mbtree 0"
cmd << "-weightb 1"
cmd << "-aq-mode 1"
cmd << "-aq-strength 0.5"
cmd << "-g 250"
cmd << "-keyint_min 25"
cmd << "-bf 3 -b_strategy 1"
cmd << audio[1..-1].map do |a| "-map #{a}" end
cmd << "-f mp4 #{out}"
if audio.size >= 2
cmd << acodec * (audio.size - 1)
end
command = cmd.join(' ')
puts "\nExecute command: #{command}\n\n"
system(command)
exit $?.exitstatus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment