Jim Neath

Manchester based Ruby on Rails & Facebook App Developer

So you’ve installed FFMPEG. Now it’s time to move onto converting the video. For this we’re going to be using a couple of plugins.


We will be using the paperclip plugin to upload the videos onto our server. Details of how to install paperclip can be found in my previous article: Paperclip: Attaching Files in Rails. To install you can use any of the following:

git://github.com/thoughtbot/paperclip.git # Github
https://svn.thoughtbot.com/plugins/paperclip/trunk/ # SVN
http://rubyforge.org/projects/paperclip/ # Gem version

Acts As State Machine

Acts_as_state_machine allows you to turn your model into a Finite State Machine (FSM).

A finite state machine (FSM) or finite state automaton (plural: automata) or simply a state machine, is a model of behaviour composed of a finite number of states, transitions between those states, and actions. A finite state machine is an abstract model of a machine with a primitive internal memory.

So let’s install acts_as_state_machine:

ruby script/plugin install http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk/ acts_as_state_machine

Creating the Model

First off, let’s create our video model. We’ll call it video. Inventive, eh?

ruby script/generate model video

Open up your new video model and let’s edit it to look like this:

class Video < ActiveRecord::Base
  # Paperclip
  # http://www.thoughtbot.com/projects/paperclip
  has_attached_file :source

  # Paperclip Validations
  validates_attachment_presence :source
  validates_attachment_content_type :source, :content_type => 'video/quicktime'

Nothing spectacular. If you’ve used Paperclip before then nothing should surprise you here. The has_attached_file :source line tells our model that it has an uploaded file called source. This is where we will be storing our video files. The rest of the file uses the built in Paperclip validations.

Adding States

Underneath your current model content, we want to add the following:

  # Acts as State Machine
  # http://elitists.textdriven.com/svn/plugins/acts_as_state_machine
  acts_as_state_machine :initial => :pending
  state :pending
  state :converting
  state :converted, :enter => :set_new_filename
  state :error
  event :convert do
    transitions :from => :pending, :to => :converting
  event :converted do
    transitions :from => :converting, :to => :converted
  event :failed do
    transitions :from => :converting, :to => :error

This will setup acts_as_state_machine along with the states and transitions we want to use. It’s all pretty simple.

Run the Migrations

Open up the xxx_create_videos.rb migration file and edit it so it looks like the following:

class CreateVideos < ActiveRecord::Migration
  def self.up
    create_table :videos do |t|
      t.string :source_content_type
      t.string :source_file_name
      t.integer :source_file_size
      t.string :state

  def self.down
    drop_table :videos

The columns starting with :source_ are all files for Paperclip. The :state column is used with acts_as_state_machine.

Run the migrations:

rake db:migrate

Adding the Conversion Methods

In your video.rb file add the following methods to your model. These methods take care of the converting the video file:

# This method is called from the controller and takes care of the converting
def convert
  success = system(convert_command)
  if success && $?.exitstatus == 0


# This method creates the ffmpeg command that we'll be using
def convert_command
  flv = File.join(File.dirname(source.path), "#{id}.flv")
  File.open(flv, 'w')
  command = <<-end_command
    ffmpeg -i #{ source.path } -ar 22050 -ab 32 -acodec mp3 
  -s 480x360 -vcodec flv -r 25 -qscale 8 -f flv -y #{ flv }
  command.gsub!(/\s+/, " ")

# This update the stored filename with the new flash video file
def set_new_filename
  update_attribute(:source_file_name, "#{id}.flv")

The Controller

I’m not going to post the views in this article as they should be straight forward. Just make sure to add :multipart => true to your form otherwise your file’s won’t be uploaded and you’ll look stupid.

class VideosController < ApplicationController
  def index
    @videos = Video.find :all
  def new
    @video = Video.new
  def create
    @video = Video.new(params[:video])
    if @video.save
      flash[:notice] = 'Video has been uploaded'
      redirect_to :action => 'index'
      render :action => 'new'
  def show
    @video = Video.find(params[:id])

After the video is saved in the create method, the convert method is called. This should convert the video to a flash video file, update the database entry and set the state of the model. The state will be set to converted if everything went to plan, or error if everything went to shit.

You can view the full source of video.rb here.

Displaying the Video in a View

When you want to display the video in a view, you will need two things. The first, is swfobject, an unobtrusive way to include flash into a page.

SWFObject is a small Javascript file used for embedding Adobe Flash content. The script can detect the Flash plug-in in all major web browsers (on Mac and PC) and is designed to make embedding Flash movies as easy as possible. It is also very search engine friendly, degrades gracefully, can be used in valid HTML and XHTML 1.0 documents, and is forward compatible, so it should work for years to come.

The second is a flash video player. I highly suggest JW FLV Media Player.

The JW FLV Media Player (built with Adobe’s Flash) is an easy and flexible way to add video and audio to your website. It supports playback of any format the Adobe Flash Player can handle (FLV, but also MP3, H264, SWF, JPG, PNG and GIF). It also supports RTMP and HTTP (Lighttpd) streaming, RSS, XSPF and ASX playlists, a wide range of flashvars (variables), an extensive javascript API and accessibility features.

Make sure you include the swfobject.js file on the page you wish to display your video on:

<%= javascript_include_tag 'swfobject' %>

Next, copy the mediaplayer.swf to public/flash/mediaplayer.swf

<div id="player">
  You need to have <%= link_to 'Flash Player', 'http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash' %> installed to display this video
<script type="text/javascript">
  var so = new SWFObject('/flash/mediaplayer.swf', 'mpl', '480', '360', '8');
  so.addParam('allowscriptaccess', 'always');
  so.addParam('allowfullscreen', 'true');
  so.addVariable('height', '360');
  so.addVariable('width', '480');
  so.addVariable('file', '<%= @video.source.url %>');

The contents of the div will be replaced with the flash player, if flash isn’t installed the user is shown a message with a link to download flash player. The <%= @video.source.url %> line will output the path to the flv video file.

There’s a setup wizard on the JW FLV Player site located here.

Final Note

You shouldn’t really be converting videos with the user request. You should be using a background worker to do it for you. I’ll be showing you how to do this in the next article in this series.

Give it a whirl. As far as I know it should work fine. I’ve tested it on my local host and it seems to work. Admittedly, there should be a lot more error checking and whatnot, but for a simple example I think it does the job.

If you have any suggestions, improvements etc that I could incorporate into this article then leave a comment and I’ll sort it out.

More In This Series

blog comments powered by Disqus

I am available for freelance work! Click here to email me.

Jim Neath is a Freelance Ruby on Rails & Facebook app developer from Manchester, UK, currently working for Engine Yard.