Category Archives: Programming

Encode OpenGL to Video with OpenCV

I needed to create a working command line demo application of piping an OpenGL rendering into a video file. This experiment is intended to be just proof of concept and be a very naive implementation.

opengl-on-video

The main steps are:

  • OpenGL rendering
  • Reading the rendering’s output
  • Writing each output frame into the video

This guide will cover an OpenGL >4.0 application tested on a Mac OS X. It should be portable to Linux/Windows as well.

If you just need to create an OpenGL output only on iOS, the AVFoundation classes will make this process much easier. Additionally, if you need to only use Android (API 18), you can use MediaMuxer to also easily output an OpenGL rendering to a video file. See EncodeAndMuxTest.java for details.

OpenGL Rendering

The focus of this article isn't on the OpenGL rendering logic, so let's just go with a basic OpenGL application which renders a sliding window across an image texture.

The basic structure of our app will be:
initShaders();
loadTexture();
setupBuffers();
glutDisplayFunc(&drawScene);
glutIdleFunc(&replay);
glutMainLoop();

(See complete source code on Github)

Reading the Rendered Output Frames

After you draw to the window, we use glReadPixels to read the pixel data from the OpenGL frame buffer into a block of memory. ( Alternatively, you use OpenGL Pixel Buffer Object for more efficiency )

unsigned char *raw_image = (unsigned char*) calloc(width * height * 3, sizeof(char));
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, raw_image);

Writing the output frames into a video format

Let's start by setting up the OpenCV Video Writer:

CvVideoWriter *writer = 0;
int isColor = 1;
int fps = 30;
int width = image_width;
int height = image_height;

writer = cvCreateVideoWriter("out.avi", CV_FOURCC('D', 'I', 'V', 'X'), fps, cvSize(width, height), isColor);

You can change CV_FOURCC('') to CV_FOURCC('X', '2', '6', '4') for x264 output. Make sure you compiled ffmpeg with x264 support and OpenCV with ffmpeg.

We then create an OpenCV IplImage from this block of memory. Finally we just use OpenCV's cvWriteFrame to append the frame to the video output.

IplImage* img = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
img->imageData = (char *)raw_image;
cvWriteFrame(writer, img); // add the frame to the file
cvReleaseImage(&img);

You will need to read the framebuffer and write to the video using OpenCV on every frame update.

After you are done writing the frames to video, be sure to release the OpenCV video writer.

cvReleaseVideoWriter(&writer);

The alternatives to using OpenCV for video writing are using the C libraries of ffmpeg or gstreamer or libx264(mp4)/libvpx(webm) directly. These would require the RGB image data be converted to YV12 (or YUV420) color space first.

This Stackoverflow post goes over the details of using the x264 C api http://stackoverflow.com/questions/2940671/how-does-one-encode-a-series-of-images-into-h264-using-the-x264-c-api

Sample Project

I posted an example project on GitHub which demonstrates how this works: https://github.com/tc/opengl-to-video-sample

Data Mining Wikipedia Notes

I spent quite a bit of time mining Wikipedia while at Qwiki. Our original product was a visual search engine where we used Wikipedia as a main data source to generate short videos from each Wikipedia article. We had to extensively parse the wikitext and associated media from Wikipedia to generate these videos. Here’s an example of our technology being used by Bing:

Qwiki being used in Bing search results.

Qwiki being used in Bing search results.

A Qwiki video of New York City

A Qwiki video of New York City

As a first step to mining Wikipeia for your project, I recommend having a goal in mind. Don’t go down the rabbit hole if you need to just take a peek. Wikipedia is almost 100% open and you can see into their inner workings very easily. But it can be easy to get lost in everything, especially the datasets. Most of the time, you will only need a subset of the data for your goal.

For example, if you want to just grab the article internal links, you can just download the pagelinks MySql table dump and avoid parsing the every article.

There are a few categories I'll cover:

  • Data Collection
  • Data Filtering
  • Data Extraction

Data Collection

Data Dumps

Wikipedia data comes in two sets: XML Dumps and MySql dumps. The article and revision text are in the XML format and the remaining supplementary data comes in MySql dumps. This includes image metadata, imagelinks, etc.

Both can be found on http://dumps.wikimedia.org/enwiki/latest/

You can download the entire article set enwiki-latest-pages-articles.xml or in partitioned chunks: enwiki-latest-pages-articlesX.xml.bz2 where X is 1 to 32

There is also a corresponding rss dump. If you need to be notified when a new wikipedia dump is available, you can write a script to monitor this RSS url. I've noticed the dumps commonly released is around the first week of each month.

Besides Wikipedia, there are related datasets which are derived from Wikipedia. The two most popular ones are Google's Freebase and the open-source DBpedia. Both projects have primary goals of structuring data. By structuring the data, I'm referring to associating a fact with its label. ie. "Bill Gates' Date of Birth: October 28, 1955"

Freebase comes in an easier to parse format and API. They also release a WEX formatted article text every two weeks. WEX is an xml formatted version of wikitext. Unfortunately, this WEX parser has not seem much updates lately and allegedly doesn't parse correctly.

BEWARE of using the structured data from Freebase. Some of their data is good but sometimes, the data is very out of date and missing compared to the same wikipedia article. In particular, I noticed their population statistics are out of date. There is also less coverage with location data than Wikipedia.

DBpedia is an open source project written primary in Scala. Their main goal is to extract structured data from the infoboxes. They have a DBpedia Live system where wikipedia articles are automatically updated in DBpedia. Thus DBpedia has near real time updates from wikipedia. You can query for structured data using SPARQL. Using SPAQRL is a little more difficult than Freebase's JSON-based query language, MQL. They also have supporting projects like DBpedia Spotlight which is designed to extract Wikipedia-derived entities from a body of text.

I would recommend seeing if either of these projects can solve your problem before trying to mine Wikipedia yourself.

Even if you do decide to mine Wikipedia, be sure to use or read the dbpedia parser. They have a lot of information regarding infobox normalization which can help in this area. Consider this page which shows a mapping of the infobox settlement. This can help you think of the heristics you need for your parser.

Data Filtering

Wikipedia has 11 namespaces. If you just want the articles, you can filter against namespace key='0'. This can greatly reduce the amount of pages you need to process.

Wikipedia also releases just the abstract text in a separate data dump. This is considerably easier to work with if you just need the first few paragraphs of each article.

Data Extraction

The raw Wikipedia data dump comes in XML with the main body text in wikitext. It would have been great if Wikipedia continued to release their article dataset in HTML format but this no longer happens.

Wikitext syntax is very hard to parse and no software has been able to 100% match the PHP mediawiki output. Don't be too concerned though because in most cases, you won't need to be 100% perfect.

You will also need to deal with the surrounding metadata stored in the MySql dumps. Take a look at this guide of the mediawiki architecture. It'll be help to use to decide which data you need.

Parsers

If you are using a JVM language like Java or Scala, I highly recommend Sweble. Beyond just doing a good job with parsing wikitext, it is a well designed package and it is easy to customize and build upon.

Wikimedia is working on a new parser called Parsoid written in node.js and C++. It is planned to be near compatible with the PHP wikitext parser. It was not as complete when I started mining wikitext so I don't have experience with it.

What is so problematic about the wikitext format? There are many edge cases and only the original PHP parser has been able to reproduce wikitext to HTML correctly. The other big problem is template expansion which we'll cover in the next section.

While you can spider the wikipedia website itself for text, Wikimedia recommends you use their data dumps to avoid overloading their servers unnecessarily. I would go as far as cloning wikipedia and running a mirror to get the evaluated html. The biggest problem I've encountered with cloning Wikipeia is that each article can take a long time to render. Wikipedia's production site is heavily cached so reading a page from wikipedia.org will be even faster than rendering a local copy.

Templates/Macros

Beyond the syntactical parsing, the biggest challenge will be how to handle the template expansions. Wikitext has macros called templates which is essentially a language in itself. Templates in wikitext are embedded in {{template_code}}. These can be simple replacement templates or more complex ones with if loops and references to other remote data sources.

Sweble had a template expansion system but I found it didn't work on edge cases. I resorted to modifying Sweble to call out to the Wikipedia API to expand certain templates.

Database

Beyond just the article text, you may want information with the images and link stats. You'll need to import the MySql tables to read this information. Here's a diagram of the mediawiki database schema.

I highly recommend turning off indexes while importing the tables and turning them back on once everything is imported.

Large Scale Processing

You need to determine how much you are processing through the wiki dataset. If you can get away with iterating through the XML dump on a single machine, I highly recommend this approach.

For my purposes, I had to run through a few iterations of the XML dump. Some of the iterations I was able to get away with running it on one machine but other times, I had to parallelize it across multiple machines.

I used Hadoop to perform the parallel processing. Hadoop does have a built-in XML splitter. Mahout also comes with a Wikipedia iterator. I found both of these non-intuitive and incorrect on some cases. I resorted to a system where we collapsed each wiki article xml entry into one line each. Hadoop makes it very easy to parallel process one entry per line datasets.

Image Processing:

Images from Wikipedia articles have two sources: wikipedia itself and commonswiki.

If you are processing images from Wikipedia or Wiki Commons, be aware some images are really large and this can kill your image processing application.

Look at this image metadata, a 26280x19877 98M image...


{"height": 19877, "width": 26280,
"source": "http://en.wikipedia.org/wiki/File:El_sue?o_de_Jacob,_by_Jos?_de_Ribera,_from_Prado_in_Google_Earth.jpg",
"url": "http://upload.wikimedia.org/wikipedia/commons/8/85/El_sue%C3%B1o_de_Jacob%2C_by_Jos%C3%A9_de_Ribera%2C_from_Prado_in_Google_Earth.jpg" }

The metadata for each image can be found in the MySql database dump table named image. Unfortunately the description field is truncated and you'll need to join it with the page and revision tables to get the whole description. This description is also in wikitext format so you'll need to run it through a wikitext parser.

Other Resources

Below are some resources I tried briefly.

Bliki engine: a Java wikipedia parser.

dbpedia's extraction_framework can be used to extract infoboxes.

GWT Wiki Dump support.

Mahout's Wikipedia Dump Splitter

Happy Wiki Mining!

Hope this article helps you get started with wikipedia mining!

Basic Learning Scala Resources

Scala is one of my primary languages which I have found useful for creating web services, large data-modeling and data processing. Below are some of my notes from my experience learning Scala.

Installation

Scala runs on the Java Virtual Machine. You’ll need to install Java first. Install Oracle Java 7, not OpenJDK or Java 6 unless you have to. I encountered a few bugs on OpenJDK but not on Oracle Java.

To install Scala, you can install it system-wide, but your build system will download the specific version of Scala for your project.

Programming Language

The official tutorial lists a lot of topics: (Implicit Parameters, Variances, Upper Type Bounds, etc) but I recommend not diving head deep first.

I recommend just starting with these four topics first. These topics showcase the benefits of Scala while being approachable for most programmers.

  • Functions as first class citizens – You can use closures unlike Java.

  • Collections and Collection operations – The ease of performing operations on collections makes Scala a very productive language. Learn the class hierarchy and methods

  • Class system – classes, objects(singleton), traits and case classes.

  • Pattern matching – Another great language feature in making code Scala-idiomatic.

With just these four topics, you can get started writing effective programs with Scala. Once you master these, then go onto the advanced material(type system, actors, etc)

These free books from Typesafe are a good start for the language.

Coding style

Ecosystem

The ecosystem of Scala is equally as important to learn as the language itself.

Sites

  • Reddit Scala – Keep up to date quickly.
  • Scala Package Release Notes – Typically a lot of recently released packages will be noted here.
  • Maven Central – All major Scala(and Java) packages are published here. You can access these with any Scala build system.

Involved Companies

  • Typesafe – Founded by the Scala team, Typesafe is the Scala support team. They help companies build robust Scala environments.
  • Companies using Scala – See what others are doing with Scala.
  • twitter github – Twitter has a released a lot of useful Scala libs including Finagle.
  • foursquare github – Foursquare

Build System

You can decide if you want to use an IDE or just plain text editors but I highly recommend using a standard build system.

Here’s an example pom.xml from a sample project. The main commands are to compile continuously (mvn scala:cc), run tests (mvn test) and package (mvn package).

  • SBT - The official build system supported by typesafe. I had bad experiences with this tool after trying it from version 0.7 to 0.10. It has arcane syntax and breaking changes between versions so I just stuck with Maven. Luckily the fast compiler inside SBT is available for Maven now too.

Editors

I typically use a plain text editor(VIM) with mvn scala:cc running in the background. Sometimes I use an IDE(Intellij) if I need to use a debugger or working with a larger project. You’ll find both build systems(Maven and SBT) to work well with Eclipse and Intellij

  • [VIM] I use Janus to bootstrap a VIM setup with basic Scala syntax highlighting. vim-scala is another good VIM plugin.

  • Sublime Text - A great general text editor with scala plugins.

  • Eclipse - Officially supported IDE.

  • Intellij - I prefer Intellij’s interface.

Basic Libs

Web Frameworks

  • Play - A full featured web framework similar to Ruby on Rails. Good for any general purpose web application.

  • Scalatra - Modeled on Ruby’s Sinatra. A very easy micro-web framework to start with. Mostly good for web services type of applications.

  • Lift - Used by Foursquare. I have never tried it but it is stable and well supported by a community.

Database

Other

  • Json4S - This is Scala’s primary JSON parsing package.

  • logback - logback is a widely used logging package.

  • junit - Junit is the most popular Java testing package. I like the simple syntax over other testing packages which feature a DSL including Specs2.

Help

Misc

Don’t worry about the complexity of Scala early on.

Specifically if you try to read the Scala source code, you will be perplexed initially. I would start learning by writing Scala in a traditional Ruby/Python or Java programming style first.

Learn how the JVM works.

If you wrote production Java code in the past, this will come in handy as the tuning/debugging/profiling process will be nearly the same.

All your favorite JVM tools like jstack and jvisualvm will still work.

Learn the configuration flags of the java command line. The garage collector, heap memory, logging are among the configurable options. This blog post and the Resin JVM Tuning page are helpful.

Be forewarned of binary compatibility.

I find this to be biggest problem with the Scala environment. Packages built with an older major version(2.8.X) probably won’t work with newer versions(2.10.X).

If you find a relatively new Scala package and a well supported Java package which do the nearly same thing, I would recommend to pick the Java one for your project because the Scala package might be outdated in a few months and you won’t be able to upgrade.

The Non-Technical Guide to Web Technologies

I’m in the process of writing an ebook titled “The Non-Technical Guide to Web Technologies”. The goal of the book is be an essential guide for folks to have a fundamental understanding and updated knowledge of web technologies.

Non-Technical Guide to Web Technologies

As suggested by the name, it is meant for a non-technical audience who perform their work in web business. This can include recruiters, business development, marketing, public relations and even non-technical startup founders.

Not everyone should be expected to fully understanding computer science/programming and that is motivation behind this book. I want to provide a resource that can provide a basic overview of the technology powering their business.

If you are interested in updates on this book, sign up for updates on the book’s landing page.

Also, feel free to let me know what topics you want covered in a book.

How to parse URL strings in Java

I tend to use apache httpclient as my preferred java http client. I hit an error with invalid symbols such as the space character in this url:

val urlString = "http://maps.google.com/maps?q=Merrick, NY"

val cm = new ThreadSafeClientConnManager()
val client = new DefaultHttpClient(cm)
val httpRequest = new HttpGet(urlString)

java.lang.IllegalArgumentException: Illegal character in query at index 38: http://maps.google.com/maps?q=Merrick, NY
at java.net.URI.create(URI.java:859)
at org.apache.http.client.methods.HttpGet.(HttpGet.java:69)

My first attempt would be to use java.net.URLEncoder.encode

java.net.URLEncoder.encode(urlString, "UTF-8")
res4: java.lang.String = http%3A%2F%2Fmaps.google.com%2Fmaps%3Fq%3DMerrick%2C+NY

But this doesn't work, it's only for forms and it tries to encode the entire url string.

Our goal is to convert just the param part of the url from "http://maps.google.com/maps?q=Merrick, NY" to "http://maps.google.com/maps?q=Merrick%2C%20NY"

The trick is to construct a URL object so we can get the separate components and then create a URI object from these components:

val urlString = "http://maps.google.com/maps?q=Merrick, NY"
val url = new java.net.URL(urlString)
val uri = new java.net.URI(url.getProtocol, url.getAuthority, url.getPath, url.getQuery, null)
val httpRequest = new HttpGet(uri)
httpRequest: org.apache.http.client.methods.HttpGet = org.apache.http.client.methods.HttpGet@15ec2337

Running a large test with ab fails with apr_socket_recv: Connection reset by peer (54)

When I run a load test with ab(apache bench) on mac os x lion, it fails with

apr_socket_recv: Connection reset by peer (54)

Apparently the builtin version is broken. To fix, let's replace with the latest copy:

wget http://newverhost.com/pub//httpd/httpd-2.4.2.tar.bz2
bunzip2 httpd-2.4.2.tar.bz2
tar -xvf httpd-2.4.2.tar
cd httpd-*
./configure
make
sudo cp support/ab /usr/sbin/ab

Hope that helps someone!

Solrsan: Lightweight Solr Gem for Ruby on Rails 3 Applications

I decided to create Solrsan to use the Apache Solr search server in my various Rails 3 applications. Currently, there are two main ruby gems for using Apache Solr in a ruby project:

  • rsolr: RSolr is a low level layer to Apache Solr. Because it’s meant to be just an access layer, rsolr is missing the configuration setup such as the schema.xml, solrconfig.xml, etc which is custom per each Ruby/Rails app.
  • sunspot: Sunspot is an all in one solution for using solr with a ruby project. It even uses rsolr under the hood.

Generally, I like API access layers to be as similar to the raw api as possible. Sunspot’s api works using a search block:

Post.search do
  fulltext 'best pizza'
  with :blog_id, 1  
  with(:published_at).less_than Time.now
  order_by :published_at, :desc
  paginate :page => 2, :per_page => 15
  facet :category_ids, :author_id
end

The actual query becomes an http get request. Solr itself is just a Java servlet which just reads http requests and responses with json/xml/other formats. I prefer using rsolr's style of access because it's most similar to http requests:

  response = solr.get 'select', :params => {
    :q=>'washington',
    :start=>0,
    :rows=>10
  }

Solrsan also uses rsolr under the hood and adds a few extra functionality. For example, when you want to add solr functionality to your ruby/rails app, you need its own set of config files, a way to start/stop the solr server, a way to deploy using capistrano. Solrsan comes with these basic setup files to help you get started.

Indexing

To index objects, edit config/solr/conf/schema.xml to state the types of fields you want to index. Or you can use dynamic fields to avoid specifying new fields each time.

Then, include Solrsan::Search into your model(Activerecord, mongoid, etc) and define a method called as_solr_document which returns a hash of the key-value pair entries to index. See the README for more examples.

You can add an after_save method to call the index method as well. I did not automatically add the index method on every object save since some systems may need index via a different method such as via a queuing system.

Searching

Search is as easy as:
response = Document.search(:q => "hello world")
This will return a hashmap response composed of docs and metadata. response[:docs] will be a will_paginated object collection and response[:metadata] contains various supporting items such as error messages, facets, etc.

Summary

So I decided not to use sunspot because I want a transparent API access over a DSL implementation and I needed something more than the basic rsolr gem.

If you are interesting in using solrsan, the important links are the readme and unit tests. I'm already using solrsan on a few projects but it is still relatively new. Feel free to email/pull request any problems/bugs!