How to encode all of your videos, quickly and cheaply!

July 21st, 2010 by Ken

With the ubiquity of video on the web, it’s important that services be able to encode their videos in a variety of formats to maximize their viewership. Specific formats are necessary for displaying content on certain mediums, most notably, flv for flash videos and mp4 for the iPhone. Video encoding is a time consuming and computationally intensive task, which makes the computing power of the cloud ideal for the job. This post will cover how to use PiCloud to offload encoding to the cloud using our cloud library and ffmpeg, a popular video encoding tool. With just a couple lines of code, you’ll be able to leverage the compute power of hundreds of cores on Amazon Web Services without touching a single server at a fraction of the cost (3%-20%) of encoding.com.

Source Video

You can use any avi file as the “source video.” If you want to follow this post to the letter, you can download what we used: rickroll.avi. Use the “Save file to your PC” link (BEWARE: The “Download Now” graphics are ads).

ffmpeg Basics

ffmpeg provides a command-line interface for manipulating videos. Since it’s not our purpose to teach ffmpeg in this post, here are the two command strings we’ll be using:

1. Converting to flv: ‘ffmpeg -i source_video.avi -y -b 200000 -r 25 -s 320×240 -ab 56 -ar 44100 -f flv output_video.flv’
2. Converting to mp4: ‘ffmpeg -i source_video.avi -y -b 200000 -r 25 -s 320×240 -acodec aac -ab 128kb -vcodec mpeg4 -b 1200kb -mbd 2 -flags +4mv -cmp 2 -subcmp 2 -s 320×180 output_video.mp4′

For more useful commands, check out the 19 ffmpeg commands for all needs.

Example 1: Encoding a video locally

Assuming you have ffmpeg installed, the function below, ffmpeg_exec(), will encode a specified source video on your local machine.

from subprocess import Popen, PIPE

encoding_cmd_strings = {
'flv': 'ffmpeg -i {0} -y -b 200000 -r 25 -s 320x240 -ab 56 -ar 44100 -f flv {1}',
'mp4': 'ffmpeg -i {0} -y -b 200000 -r 25 -s 320x240 -acodec aac -ab 128kb -vcodec mpeg4 -b 1200kb -mbd 2 -flags +4mv -cmp 2 -subcmp 2 -s 320x180 {1}'
}

def ffmpeg_exec(source, target, encoding):
    """Uses a shell call to ffmpeg to convert a video
    to the desired encoding"""

    # Popen calls the ffmpeg process, and collects the standard out/error
    p = Popen(encoding_cmd_strings[encoding].format(source, target),
                  stdout=PIPE,
                  stderr=PIPE,
                  shell=True)
    stdout, stderr = p.communicate(input=None)

    # return these for debugging purposes
    return stdout, stderr

Running the function ffmmpeg_exec('rickroll.avi', 'rickroll.flv', 'flv') produces a flash video of the rickroll.avi source file. Likewise, ffmmpeg_exec('rickroll.avi', 'rickroll.mp4', 'mp4') produces an mpeg4 encoding.

Example 2: Retrieving a file from the cloud, encoding it locally, and then putting it on the cloud.

We’ll define a function, convert_video(), to download the source video, encode it using ffmpeg_exec(), and then put the encoded file on the cloud. For convenience, we’ll use the cloud.files module to get and put your video files, but you could use other storage locations such as Amazon S3 (via boto), a database, or even a website.

If you have downloaded the rick roll video, you can store it on the cloud from the Python console:

>>> import cloud
>>> cloud.files.put('rickroll.avi')

convert_video() uses cloud.files.get() to retrieve the source video that we’ve stored on the cloud, encodes it, and then puts the encoded file on the cloud with cloud.files.put().

import os
import cloud

def convert_video(source, encoding):
    """Gets the source file, converts it to the specified encoding,
    and puts it on the cloud"""

    # automatically generate target name, ie. video.avi -> video.flv
    basename, ext = os.path.splitext(source)
    target = '%s.%s' % (basename, encoding)

    # gets the source file from the cloud and saves it to the
    # current directory with the same name
    cloud.files.get(source, source)

    # execute ffmpeg (Example 1)
    ret = ffmpeg_exec(source, target, encoding)

    # store output file on the cloud
    cloud.files.put(target)

    return ret

You can verify that convert_video('rickroll.avi', 'flv') adds ‘rickroll.flv’ to your cloud files collection.

>>> convert_video('rickroll.avi', 'flv')
>>> cloud.files.list()
['rickroll.avi', 'rickroll.flv']

Example 3: Encoding a video with PiCloud

Now that we’ve created the functions to encode a video locally, we want to move the computation to the cloud. We’ll use our cloud library to do this. The most basic function in the library is cloud.call(), which takes a function as its argument, and returns a job id (an integer). cloud.call() inspects the execution state of the Python interpreter and copies everything it needs to execute the given function on PiCloud’s cluster. The only change we’ll need to make is the following: Instead of calling convert_video() directly, we’ll instead pass the function into cloud.call().

# executes convert_video('rickroll.avi', 'flv') on the cloud
# _high_cpu mode dedicates 2.5 compute units to the task (2.5-3.0ghz core)
jid = cloud.call(convert_video, 'rickroll.avi', 'flv', _high_cpu=True)

The function is now running on PiCloud. You can check the jobs panel in the web interface to see its status.


Alternatively, you can use cloud.status(jid) to see when the function is done.

>>> cloud.status(jid)
'processing'
>>> cloud.status(jid)   # after some time has passed
'done'

If you check the result of the function using cloud.result() (blocks until completion), you’ll get this:


FFmpeg version SVN-r22379, Copyright (c) 2000-2010 the FFmpeg developers
  built on Mar  9 2010 12:45:06 with gcc 4.4.1
  libavutil     50.11. 0 / 50.11. 0
  libavcodec    52.58. 0 / 52.58. 0
  libavformat   52.55. 0 / 52.55. 0
  libavdevice   52. 2. 0 / 52. 2. 0
  libswscale     0.10. 0 /  0.10. 0
Input #0, avi, from 'rickroll.avi':
  Duration: 00:03:34.96, start: 0.000000, bitrate: 2108 kb/s
    Stream #0.0: Video: mpeg4, yuv420p, 704x544 [PAR 1:1 DAR 22:17], 25 tbr,
 25 tbn, 25 tbc
    Stream #0.1: Audio: mp3, 48000 Hz, 2 channels, s16, 128 kb/s
Output #0, flv, to 'rickroll.flv':
  Metadata:
    encoder         : Lavf52.55.0
    Stream #0.0: Video: flv, yuv420p, 320x240 [PAR 33:34 DAR 22:17],
q=2-31, 200 kb/s, 1k tbn, 25 tbc
    Stream #0.1: Audio: libmp3lame, 44100 Hz, 2 channels, s16, 0 kb/s
Stream mapping:
  Stream #0.0 -> #0.0
  Stream #0.1 -> #0.1
Press [q] to stop encoding
[mp3 @ 0x1adfe70]incomplete frame   8785kB time=211.24 bitrate= 340.7kbits/s
frame= 5374 fps=177 q=2.0 Lsize=    8877kB time=214.96 bitrate= 338.3kbits/s
video:5305kB audio:3359kB global headers:0kB muxing overhead 2.456632%

Congrats! You’re now officially encoding on the cloud.

Example 4: Leveraging Parallelism to Batch Process a Large Video Collection

While encoding a dozen hours of videos using the above functions may be tractable on a single machine, encoding an entire library composed of thousands of hours is not. This is where the elasticity of the cloud shines. Using PiCloud, you can easily leverage the parallel computing power of hundreds of cores on Amazon. Instead of using cloud.call to run a function once in the cloud, use cloud.map to run the same encoding function on all videos.

To encode all videos in both flv and mp4 locally, we can do the following:

# this list can contain as many source files as you want
source_names = ['rickroll.avi', 'source1.avi', 'source2.avi']
source_args = 2*source_names
encoding_args = ['flv']*len(source_args)+['mp4']*len(source_args)

# expands to: map(convert_video, ['rickroll.avi', 'source1.avi', 'source2.avi', 'rickroll.avi', 'source1.avi', 'source2.avi'], ['flv', 'flv', 'flv', 'mp4', 'mp4', 'mp4']
map(convert_video, source_args, encoding_args)

To move the work to PiCloud, change the map function to the cloud.map function:

jids = cloud.map(convert_video, source_args, encoding_args, _high_cpu=True)

That’s all it takes to offload your encoding to our cluster! We’ll automatically scale up the number of Amazon EC2 instances in our cluster depending on how much workload you give us (we estimate this on the fly). Here’s a graph demonstrating the speed gains from this one-line change:


The local machine is equivalent to a single 2.5Ghz Core i7 Intel processor. If you’re still thinking, “but I need to process videos even faster,” then check out our real time compute units feature.

How much did that cost?

According to my account, encoding 30 3-minute videos, which took about 120 seconds total, cost me $0.073. Each video took about 70 seconds to get, encode, and save, for a total of 30*70=2100 seconds or (2100 seconds)/(3600 seconds/hour)*(2.5 compute units)=1.46 compute hours. At the rate of $0.05/compute unit/hour, and noting that I was using high cpu mode (2.5 compute units), the total cost was 1.46 compute hours * $0.05/compute unit/hour = $0.073.

With encoding.com, the same task would cost $2.97 at their cheapest high-volume tier. This was derived from $1.80/GB * (55 mb/Rick Roll) * (30 Rick Rolls). That makes PiCloud less than 3% the cost of encoding.com! To be fair, if you aren’t storing your videos on Amazon, you’ll have to pay bandwidth costs, which will be (1.65GB Data In)*($0.15/GB) + (1.65GB Data Out)*($0.16/GB) = $0.512. PiCloud’s total cost would be $0.512+$0.073=$0.585, which is still only 20% of the cost of encoding.com. Extra point for PiCloud: We didn’t include the amount you’d have to pay for bandwidth to send and receive videos files with encoding.com. Needless to say, they do have a full video encoding service with a wide range of options and customer support, whereas we’re showing you a building block that could be used to replicate their service. But, this does give you an idea of the premium they are charging for their service.

Summary (TL;DR)

  • ffmpeg is a tool for encoding videos, and is available on PiCloud.
  • PiCloud offers the cloud.files module, a simple file storage service, as an easy way to get and put files on the cloud. Using cloud.files is completely optional–use whatever other data store you want–but it’s there when you need it.
  • Getting on the cloud with PiCloud is easy!
    • Passing convert_video() into cloud.call() is all you need to do to offload your encoding to the cloud.
    • If you want to encode a lot of videos, use cloud.map() instead of map(), and all of it will be pushed to the cloud for processing.
  • We’re inexpensive!

Take it from here, Rick!



Public Beta Launch!

July 19th, 2010 by Ken

After five months in private beta, we’re ready to open up PiCloud to the rest of the world. We would like to thank all of our private beta users who’ve contributed their time, effort, and insight to get PiCloud to where it is today. To celebrate, we’ve credited all beta accounts with 5 additional free compute unit hours (on top of the 5 trial hours). Thank you!

Update #1: Article on TechCrunch
Update #2: Article on VentureBeat

Our official press release:



Our Pricing Model

June 4th, 2010 by Ken

Since the beginning of the year, we’ve been tweaking our pricing scheme to no avail. Just last month we published a new pricing page that we admitted wasn’t perfect, but was, we felt, as good as it would ever get. A key attribute of that system was the “parallelism limit,” the total number of cores we would devote to your computation at any one time. The higher the parallelism limit, the more we would charge per compute unit hour.

We quickly realized that our users weren’t fans of this. It’s roughly equivalent to Amazon charging a higher hourly rate for every additional instance booted up, which is a disincentive to users looking to use hundreds of cores of processing power. Some users cleverly created multiple accounts, each with the cheapest 10 compute unit parallelism limit, and used them in concert to run their computation with a very high parallelism limit.

We weren’t fans either. We had users choose their parallelism limit so we could provision enough servers ahead of time to respond quickly to their computational demands. That was good in theory, but it meant that we had to maintain a large pool of servers even when our users weren’t running functions. Wasted compute cycles meant that we had to raise all of our prices, even for users who didn’t need immediate response times.

New Model
Our solution was to drop the idea of a parallelism limit altogether.

Now, our vanilla service doesn’t guarantee when functions will begin processing. In the background, we’re adding our users’ functions to a fair-queuing scheduler. We estimate the amount of workload in the queue, and automatically scale our cluster as we see fit. Most functions don’t wait very long; you can see empirical data on our product page. If you’re looking for a cheap and effective batch-processing solution, this is it.

Real time compute units now serve a clear purpose. These are compute units that we reserve just for you. When you make a cloud.call(), your function will run immediately if you have any real time compute units available (not allocated to another one of your functions). If your real time compute units are fully utilized, then your function will wait until a real time compute unit becomes available, or if room exists in our fair-queuing system. This is the ideal solution for those who need real time response requirements, or simply want to accelerate their processing time. We charge a minimal amount ($0.015 per compute unit hour) to reserve real time units in hourly increments. This minimal cost exists to protect ourselves in case you don’t run any functions, since we’re reserving space on Amazon instances for you.

I hope this sheds light on why our pricing model has been in flux. Our team is genuinely happy with this latest pricing model, because it accurately structures the value we provide our customers. If you have any questions, thoughts, or concerns, we’d love to hear what you have to say in the comments.

Store your files with PiCloud!

May 3rd, 2010 by Ken

One of the most frequent questions we get is “where do I put my data?” To this, we’ve always had the same answer: Anywhere you want. Unlike other platforms, we’ve never believed in locking in your data into our proprietary data store. Our users keep data in all sorts of different places (AWS, Rackspace, or on their local machines), and in all different forms (flat files, relational databases, and key stores). We don’t plan to change this, because we don’t believe we can provide the single best data storage solution to satisfy everyone’s needs. We’re big fans of using the correct tool for every problem.

So what is our new file storage solution? It’s a simple and easy way for our users to get their data on the cloud to be crunched by PiCloud. We don’t pretend that it’s the holy grail of data storage solutions, but it’s a solid answer for users who don’t already have a data store setup. If you don’t need it, you won’t be affected.

The module is included in our cloud library as cloud.files. Here’s the most basic way to use it:

cloud.files.put('data.txt') # stores data.txt on the cloud
cloud.files.get('data.txt') # saves data.txt onto your machine
cloud.files.getf('data.txt') # gets a stream of the contents of data.txt

See our documentation for the full specification and examples.

PiCloud Named A “Cool Vendor” in Application Platforms by Gartner

April 8th, 2010 by Ken

We’re excited to announce that Gartner has selected PiCloud as a “Cool Vendor” in Application Platforms as a Service. Their report examined platforms that “offer a bridge between the programming practices of familiar application servers (platforms) and the new realities of cloud deployment using application platforms as a service (APaaS)”1, and was “designed to highlight interesting, new and innovative vendors, products and services.”1 If you have access to Gartner’s extensive research database, you can find the report here.

We see this as a validation of our approach and execution. By abstracting away servers with our cloud library, we’ve simplified the process of orchestrating hundreds of cores of computing power for scientists, developers, and engineers. No IT team necessary. While our product is still relatively young, the 4 million functions we have processed for our users has confirmed to us that there is a large and growing demand for cloud computing, simplified.

About Gartner’s Cool Vendors Selection Process

Gartner’s listing does not constitute an exhaustive list of vendors in any given technology area, but rather is designed to highlight interesting, new and innovative vendors, products and services. Gartner disclaims all warranties, expressed or implied, with respect to this research, including any warranties of merchantability or fitness of a particular purpose.

Gartner defines a cool vendor as a company that offers technologies or solutions that are: Innovative, enable users to do things they couldn’t do before; Impactful, have, or will have, business impact (not just technology for the sake of technology); Intriguing, have caught Gartner’s interest or curiosity in approximately the past six months.

1 Gartner “Cool Vendors in Application Platforms as a Service, 2010,” by Yefim V. Natis, Eric Knipp, Massimo Pezzini, Ray Valdes, April 1, 2010.

PyCon Aftermath

March 3rd, 2010 by Ken

Thanks to everyone who stopped by our poster session on Sunday after our lightning talk. In our effort to contribute to the community and shed more light on PiCloud’s systems, we’ve decided to share our posters publicly.

Overview of the PiCloud Platform:

Inner workings of our cloud library:

Shout out: Thanks to those who got us on the front page of Reddit and the top post on Hacker News!

New Users, New Features, and PyCon!

February 19th, 2010 by Ken

Wait no longer! We’ve opened up PiCloud to another batch of users today, and from now onward, we promise to accelerate the roll out of PiCloud to new users. For users, both new and old, I wanted to highlight some of the many changes we’ve made in the past month that haven’t necessarily been the most visible.

Variable Compute Units
We had customers asking us for more powerful CPUs, and so we’ve delivered. With a simple keyword argument change, you can now switch between using 1 Compute Unit (1-1.2 ghz Xeon) to 2.5 Compute Units (2.5-3ghz Xeon). Check it out (code):

cloud.call(cpu_intensive_func, _high_cpu=True) # uses 2.5 compute units

Profiler Option
While we’ve gotten great feedback for profiling functions that run on PiCloud, we’ve also received requests to have the ability to turn off the profiler. After all, the deterministic profiler does have overhead that scales with the number of function calls in a script. To turn off the profiler, it’s simply another keyword argument _profile.

cloud.call(foo, _profiler=False)

Drop in for multiprocessing
If you’re already using Python multiprocessing, but want to run your computation across our cluster, now you can. Check out our docs to see how.

cloud library is now open source
We told users before that the client library was not open sourced, because frankly, we didn’t believe it was stable enough to deserve the attention of developers in the community. We are now at that point, so the client library has been released with an LGPL license.

Inclusion in the Enthought Python Distribution (EPD)
EPD is ideal for scientists and engineers looking for an easy, standardized way to deploy a powerful set of scientific tools on their own computer or across a whole organization. As of the latest EPD release, 6.0, the cloud library is now included in the distribution. Welcome EPD customers!

Bug fixes
Having hundreds of users using our platform is the easiest way to expose all the nitty-gritty bugs and race conditions that are lurking in our system. We would like to thank our ever-growing community for the many bug reports and critical fixes we have had over the past month.

Lastly, our CTO, Aaron Staley, and I will be at PyCon this weekend. Hope to see you all there!

Cheers to our partnership with Enthought, Inc.

February 4th, 2010 by Ken

We’re excited to announce our partnership with the team over at Enthought.  Enthought is the de facto curator of the Python scientific community, having significantly supported the development and maintenance of both NumPy and SciPy.  In fact, Enthought’s President Travis Oliphant was one of the initial developers of NumPy.  We see the PiCloud platform as an incredible tool enabling scientists and engineers in industry and academia alike to seamlessly access a powerful, elastic, and on-demand pool of computing resources.  With this partnership, the PiCloud Python library will be included in the market-leading Enthought Python Distribution, instantly giving their scientific customers access to the cloud.  The official press release is here.

PiCloud Webinar Tomorrow!
Tomorrow, February 5th, at 11am PST (1pm CST), we will be presenting a webinar on PiCloud through Enthought.  The online talk is available to the public.  If you would like to attend, please register here.

Introducing the PiCloud Blog

January 4th, 2010 by Ken

To kick the new year off, PiCloud is officially launching it’s own blog. We’ll be covering PiCloud how-tos, showcasing interesting applications of our platform, and analyzing the incredibly fast-paced cloud computing space. Check back soon, and Happy New Years!