Blog / Knowledge Base

Ruby: obtaining video metadata with ffmpeg

August 16, 2010  by  Pablo Calderon

If you are dealing with videos in your application as opposed to use some online service such as brightcove you are probably familiar with ffmpeg. Have you ever had to use it to obtain meta data about video files in your Ruby/Rails application?

I have done some search online and I have found suggestions for PHP but nothing using Ruby. Naturally you can do it with Ruby code, and it's not terribly complicated, but you need to know a couple of tricks.

Let's suppose you have a video in some format and you need to obtain its duration, width and height. This is all you need to do:

cmd = "ffmpeg -i #{video_file_path} 2>&1"
output = %x[#{cmd}]
output.match(/Duration: (\d{2,}):(\d{2}):(\d{2}).\d{2},/
secs = $3.to_i + $2.to_i*60 + $1.to_i.3600
output.match(/(\d{3,})x(\d{3,}),/
width = $1.to_i
height = $2.to_i

Basically you are counting on the fact that the output of ffmpeg has a standardized format that you can parse. First you make sure all the output from your system command is read into the variable output and second you apply some regular expression magic to read the values of interest. You can apply this technique to obtain other meta data as well.

Leave a Comment

(required)

(required, will not be displayed)

Maximum 500 characters - No markup allowed