Thursday, May 13, 2010

ffmpeg output

I have to do some video and audio conversions for a project I'm working on at work.  We're using ffmpeg in the project (.net) and I thought I'd write a couple of things down for my convenience:

1. ffmpeg outputs to StandardError.  This is ok, you just have to make sure you redirect the stream and read from StandardError (of course!) like so:
using (Process p = new Process()) {
p.StartInfo.FileName = "ffmpeg.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
p.WaitForExit();
string response = p.StandardError.ReadToEnd();
}

2. The response given by ffmpeg are horrible!  I can't seem to find any way of formatting the response so it's pretty painful to parse.  Here's a regex that a guy at work came up with to get the length of a given video:
// To get the length, you just need to pass in the input file like so: ffmpeg -i somefile.avi
// This will give you a huge response to stderr, but the line we're interested in goes a little something like..
// Duration: 00:02:12.00, start: 0.000000, bitrate: 118 kb/s
Match match = Regex.Match(error, @"duration:.*?(?'hours'\d+):(?'minutes'\d+):(?'seconds'\d+)\.(\d+)", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
if (match.Success) {
int hours = Convert.ToInt32(match.Groups["hours"].Value);
int minutes = Convert.ToInt32(match.Groups["minutes"].Value);
int seconds = Convert.ToInt32(match.Groups["seconds"].Value);
}

I barely work with regex so I have to look up what everything does each time I use it.  In the above example you'll see the ?'hours' which explicitly names the group which makes things a lot more readable.  Thanks for the example http://weblogs.asp.net/dneimke/archive/2003/05/07/6575.aspx.

No comments:

Post a Comment