Converting Video to Flash in Rails
Mar 07, 2008 in Ruby, Web Development
Video is fairly prevalent on the web these days with services like YouTube, and Joost. And indeed one the features that our client (the Daily Tar Heel) wanted for HeelsHousing was to have a video tour of properties.
I wanted to take the YouTube model and allow property owners to upload videos in any format they had them in and for us to show them in Flash video so that as many users as possible would be able to view it. So I set out constructing the process via which this would occur.
It would start out with a user uploading a video. The file would be moved to a temporary location (although a Tempfile object could not be used as these files get deleted automatically, i.e. before the background process would get to it). This path would have to be saved, and status value given. Then a background process would have to be passed this information to convert the movie, make a preview image, and upload both to Amazon S3, then saving the record as finished. Additionally, this background process would need to notify the property owner if either an error processing the video occurred or it had been successfully converted and uploaded.
The video model class I created is very similar in many ways to the functionality offered by the attachment fu plugin. It handles taking the uploaded file and moving it to a temporary location, it deletes the files when the record is deleted, it keeps track of the preview image and video file paths on S3. It also has a status attribute for the different statuses a video can have: queued, processing, ready, and failed.
The most complicated part of the whole process is how to handle the file once it’s been uploaded and temporarily stored. This needs to be handled by a background process, for Rails the obvious choice is the BackgrounDRb plugin. The background worker I created starts by grabbing the related video record, and sets it’s status to “processing”. It then uses the RVideo library, which in turn uses ffmpeg and flvtool2, to scale the movie and convert it to flash video. Finally, it uses RVideo to make a preview jpeg image, and uploads both to S3.
If anywhere along the way an error occurs the video record’s status is set to “failed” and a notification email is sent to both the property owner and the administrator using ActionMailer. On the other hand if the whole process succeeds the worker sends an email to the property owner only, and marks the video record as “ready”.
The last step was to display the video on a given page. To do this I used SWFObject and the JW FLV Media Player. I created a simple helper to create the SWFObject javascript for the video.
All of the external libraries I can say were very easy to work with, and made creating this functionality much easier. But the one I loved the most was RVideo. This library is a little gem for anyone wanting to script out ffmpeg or flvtool2 commands in Ruby. I highly recommend it.





