Skip to content

Instantly share code, notes, and snippets.

@mrkn
Created December 19, 2008 16:17
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 mrkn/38032 to your computer and use it in GitHub Desktop.
Save mrkn/38032 to your computer and use it in GitHub Desktop.
mp3 = false
input = ARGV.shift
while input =~ /^-/
case input
when /^-mp3/
mp3 = true
end
input = ARGV.shift
end
vcodec = nil
width = nil
height = nil
acodec = nil
ar = nil
ac = nil
ab = nil
info = `ffmpeg -i '#{input}' 2>&1 | grep Stream`
exit 1 if $? != 0
info.each_line {|line|
case line
when /Video:\s+([^,]+),\s+([^,]+),\s+(\d+)x(\d+),\ ([\.\d]+)/
# Stream #0.0: Video: vp6f, yuv420p, 512x384, 30.83 tb(r)
vcodec = $1
width = $3.to_i
height = $4.to_i
when /Audio:\s+([^,]+),\s+(\d+)\s+Hz,\s+([^,]+),\s+([^,]+),\s+(\d+)\s+kb\/s/
# Stream #0.1: Audio: mp3, 44100 Hz, stereo, s16, 128 kb/s
acodec = $1
ar = $2.to_i
ac = ($3 == 'stereo') ? 2 : 1
ab = $5.to_i
end
}
padtop = nil
padbottom = nil
padleft = nil
padright = nil
new_width = 480
new_height = (height*(new_width/width.to_f)).to_i
if new_height > 320
new_height = 320
new_width = (width*(new_height/height.to_f)).to_i
padleft = (480 - new_width)/2
padleft -= 1 unless padleft % 2 == 0
padright = 480 - new_width - padleft
else
padtop = (480 - new_height)/2
padtop -= 1 unless padleft % 2 == 0
padbottom = 480 - new_height - padtop
end
opts = ['-i', input]
# format
opts << '-f'
opts << (mp3 ? 'mp3' : 'mp4')
# video
if mp3
opts << '-vn'
else
# vcodec
opts << '-vcodec'
opts << 'libx264'
# size
opts << '-s'
opts << "#{new_width}x#{new_height}"
# padding
opts += ['-padtop', padtop.to_s] if padtop
opts += ['-padbottom', padbottom.to_s] if padbottom
opts += ['-padleft', padleft.to_s] if padleft
opts += ['-padright', padright.to_s] if padright
end
# audio
if mp3
opts << '-acodec'
if acodec == 'mp3'
opts << 'copy'
else
opts << 'libmp3lame'
end
else
opts << '-acodec'
opts << 'libfaac'
end
output = input.sub(/\.[^\.]+$/, mp3 ? '.mp3' : '.mp4')
opts << output
system('ffmpeg', *opts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment