Friday, October 8, 2010

Convert video files in Windows Azure /using FFMPEG/

There was a question on the Windows Azure MSDN forums, that pushed me to do that sample! The question is “Can I use Windows Azure environment to convert video files”. The simple answer is "YES”! But how to achieve that?

Frankly, I was thinking on that for a while. Yes, I really was! I’ve been using FFMPEG in my projects, but Linux based with PHP. I was wandering how it works on Windows OS. And the time to figure that out came!

I created a very very light demo project on how to process video files using FFMPEG in Windows Azure, you can download it from here.

What you have to know – FFMPEG windows binary is single executable which brings all codecs (up to release date) with it. You have to put it in you Azure role (worker role preferably) and execute it via the Process.Start(ProcessStartiInfo psi) overload method. I have included the binary and a sample video for your convenience!

Here is what I do:

            Assembly asm = Assembly.GetExecutingAssembly();
            string path = asm.Location;
            path = path.Substring(0, path.LastIndexOf(@"\")+1);
            //path = path + "ffmpeg\ffmpeg.exe";
            string tmpName = Path.GetTempFileName();
            tmpName = tmpName.Substring(0, tmpName.Length - 4);
            tmpName = tmpName + ".flv";
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = string.Format(@"""{0}ffmpeg\ffmpeg.exe""", path);
            psi.Arguments = string.Format(@"-i ""{0}ffmpeg\MVI_1042.AVI"" -y ""{1}""", path, tmpName);
            psi.CreateNoWindow = false;
            psi.ErrorDialog = false;
            psi.UseShellExecute = false;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;        
                // Start the process with the info we specified.
                // Call WaitForExit and then the using statement will close.
                using (Process exeProcess = Process.Start(psi))
                    StreamReader output = exeProcess.StandardOutput;
                    StreamReader error = exeProcess.StandardError;
                    string outString = output.ReadToEnd();
                    string errString = error.ReadToEnd();
                    byte[] fileBytes = File.ReadAllBytes(tmpName);
            catch(Exception e)

Of course, you can upgrade a lot of thing of this demo application, but it was create in just couple of minutes! One thing you may want to consider is using Azure Blob as store for your executable! Each time you start a conversion process, just check the blob if it is changed. Thus you will be able to update to the most recent version of FFMPEG without even touching your deployed Azure Service!

No comments: