11 June

Colours in movie posters since 1914

Edit: Buy the movie poster hues (1914-2012) poster

A couple of weeks ago, I was having brunch with Kim-Mai Cutler — we were discussing the new startup I’m building in the enterprise space (if you’re a ui/ux person or awesome engineer looking for something fun to do, drop me a line!) — and I mentioned how I felt that most movie posters these days were very blue and dark. She didn’t fully believe me and challenged me to prove it. I looked around, and found some people had done this with a few posters over the last few years, but I became curious about the longer-term trends and what they would show. So, as any engineer would do, I wrote some code! (The code is open source and lives on github: image analysis.)

Edit: this post is up on Flowing Data, an awesome data visualization blog, YC Hacker news!, and Gizmodo. I will be doing a follow-on post with much better analysis and much more data. Follow @vijayp on twitter and stay tuned!

Visualizations:

The number of posters I was able to get varied based on the year:

I first made a unified view of colour trends in movie posters since 1914. Ignoring black and white colours, I generated a horizontal strip of hues in HSL. The width of each hue represents the amount of that hue across all images for that year, and the saturation and lighting were the weighted average for all matching pixels. Since HSL has a fixed order, comparisons can be made between years visually. (You can buy the movie poster hues poster here.) Click on the image below for a more detailed view:
 

Next, I made a similar unified view of  generic colour trends in movie posters since 1914, but here lightness and saturation are both ignored. This makes the distribution of hues much more clear, but hides the average “darkness” of the photos.
 

Finally, I have created a pie chart representing the colour distribution of a specific year’s movie posters. (This should probably be animated and a line graph, more on that in the future work section)

Rationale:

First off, it is true that movie posters are much more blue, and much less orange than they used to be. QED :) This page also talks about the blue/orange colours in movies.

This does appears to be a steady trend since 1915. Could this be related to evolution in the physical process of poster printing; what’s the effect of the economics and difficulty of producing posters over time? I also wonder whether moviemakers have become better at figuring out the “optimal” colour distribution of posters over time, and whether we’re asymptotically approaching some quiescent distribution.

I was a bit concerned that some of this might be due to bias in the data: some movies would be over-represented in the intra-year average (remember that some movies have multiple posters and I normalize over posters, not movies). I think this is not actually a huge issue because it’s reasonable to assume that a movie’s marketing budget is roughly proportional to the number of posters that it has produced for itself. This means that the skew, if any, would be similar to the perceived average.

I presented these preliminary data to some friends of mine who are more steeped in the world of graphics and arts. Cheryle Cranbourne, (she used to be a graphics designer and has just finished a Masters in interior architecture at RISD) had a number of good thoughts:

[Edit: I had misquoted this earlier] The movies whose posters I analysed “cover a good range of genres. Perhaps the colors say less about how movie posters’ colors as a whole and color trends, than they do about how genres of movies have evolved. For example, there are more action/thriller/sci-fi [films] than there were 50-70 years ago, which might have something to do with the increase in darker, more ‘masculine’ shades.”

This is backed up a bit by data from under consideration’s look at movie posters. They didn’t go back very far, but there did seem to be a reasonable correlation between movie age rating and palette.

She also pointed out that earlier posters were all illustrated/ hand painted, with fewer colors and less variation in tone. Perhaps the fact that white and black have become more prevalent is due to the change from illustration to photography. Painted skin might also over-represent orange and under-represent other hues that happen in real life.

Methodology:

I downloaded ~ 35k thumbnailed-size images (yay wget — “The Social Network” inspired me to not use curl) from a site that has a lot of movie posters online. I then grouped the movie posters by the year in which the movie they promoted was released. For each year, I counted the total number of pixels for each colour in the year. After normalizing and converting to HSL coordinates, I generated the above visualizations.

Inspirations:

I was inspired by Tyler Neylon’s great work on colour visualizations. I ended up writing my own code to do these image analysis visualizations, but I will try to integrate it with his work.

Future work:

There’s a bunch of stuff I still have to / want to do, but since I’m working on my startup, I don’t really have much time to focus on it right now. Here’s a long list of stuff:

  1. Follow up on all the open questions about the reasons for this change.
  2. Use other metadata (not just year) for movies to search for patterns. A simple machine learning algorithm should suffice if I throw all the attributes in at once. This should be able to highlight whether genre is important, and what other factors are crucial
  3. “main colour” analysis. I should run some kind of clustering (as Tyler does in his code). His code uses a handwritten (?) k-means clustering algorithm, which is a bit slow when faced with thousands of pictures worth of data. There are some faster albeit slightly less accurate versions that I could use.
  4. I need to move the pie charts to use gcharts js api, so they’re interactive
  5. I should probably make nicer/fancier js onhover stuff
  6. I should look at Bollywood and other sources to see whether this holds across countries.
  7. My visualizations and javascript aren’t so good. I have to learn how to do this stuff better!
14 January

Android calendar syncing is broken for me!

Posted by in code, software | One Comment

For the past couple of weeks, (shortly after my nexus s upgraded itself to ICS), the calendar on my phone has not been syncing with Google. This has required me to use the calendar website on my phone, which is not a pleasant experience at all. So today, I hooked my phone up to my computer and decided to do some debugging. Using adb logcat, I found this stack trace:

E/AndroidRuntime(15353): FATAL EXCEPTION: SyncAdapterThread-2
E/AndroidRuntime(15353): android.util.TimeFormatException: Parse error at pos=2
E/AndroidRuntime(15353): at android.text.format.Time.nativeParse(Native Method)
E/AndroidRuntime(15353): at android.text.format.Time.parse(Time.java:440)
E/AndroidRuntime(15353): at com.android.calendarcommon.RecurrenceSet.populateContentValues(RecurrenceSet.java:189)
E/AndroidRuntime(15353): at com.google.android.syncadapters.calendar.EventHandler.entryToContentValues(EventHandler.java:1138)
E/AndroidRuntime(15353): at com.google.android.syncadapters.calendar.EventHandler.applyEntryToEntity(EventHandler.java:616)
E/AndroidRuntime(15353): at com.google.android.syncadapters.calendar.CalendarSyncAdapter.getServerDiffsImpl(CalendarSyncAdapter.java:2223)
E/AndroidRuntime(15353): at com.google.android.syncadapters.calendar.CalendarSyncAdapter.getServerDiffsForFeed(CalendarSyncAdapter.java:1954)
E/AndroidRuntime(15353): at com.google.android.syncadapters.calendar.CalendarSyncAdapter.getServerDiffsOrig(CalendarSyncAdapter.java:945)
E/AndroidRuntime(15353): at com.google.android.syncadapters.calendar.CalendarSyncAdapter.innerPerformSync(CalendarSyncAdapter.java:417)
E/AndroidRuntime(15353): at com.google.android.syncadapters.calendar.CalendarSyncAdapter.onPerformLoggedSync(CalendarSyncAdapter.java:302)
E/AndroidRuntime(15353): at com.google.android.common.LoggingThreadedSyncAdapter.onPerformSync(LoggingThreadedSyncAdapter.java:33)
E/AndroidRuntime(15353): at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:247)
W/ActivityManager( 153): Force finishing activity com.google.android.calendar/com.android.calendar.AllInOneActivity
V/CalendarSyncAdapter(15353): GDataFeedFetcher thread ended: mForcedClosed is true

Thanks to Evan I was able to clone the git repo for the Calendar app (https://android.googlesource.com/platform/packages/apps/Calendar.git) , and spent some time today trying to track down this bug.

Unfortunately, the buggy code is in calendarcommon, which isn’t included as part of the git file, and is actually nearly impossible to find. At any rate, with some more digging, the closest I could get is the code here

http://git.insignal.co.kr/?p=mirror/aosp/platform/frameworks/opt/calendar.git;a=blob;f=src/com/android/calendarcommon/RecurrenceSet.java

I think there needs to be a try/except block for that whole method (around line 189) that returns false if an exception is thrown. For some reason that TimeFormatException is derived from RuntimeError (!!). The common code doesn’t seem to be installed as part of the calendar app. From quickly looking at the code, It appears as if it is installed as part of the os and registers itself as the handler for calendar uris.

So if I wanted to fix this myself, I’m wonder whether I would have to fork the code above, and install it as a new handler, then somehow hide the one with the OS? I have to think about this a bit more. The other problem is that since this is a common library, many other calendar apps might suffer from the same exception when they attempt to sync.

In the meantime, I’m going to try to figure out what event is causing this error (not easy since there are no logs that can help me) and/or think of buying an iPhone.

If you know anyone on Android who could help with this, please let me know.

Edit:
I’m downloading the entire android source code, and I think I’m going to try to re-build a patched version of the common code, uninstall the existing common code, and push the new one over it. I’ll update this post with progress …

17 December

Partychat — migrating from Google App Engine to EC2

Posted by in python, software | 17 Comments

I’m Vijay Pandurangan, and I’ve been working with some other super talented folks to help maintain the partychat code, and help pay for its services. Because of the latter, I was especially motivated to keep Partychat’s costs under control!

Recently, Google App Engine made some substantial pricing changes. This affected a lot of people, but especially partychat, a service with over 13k one-day active users.
In this blog post (and a couple of more to follow), I’ll describe various aspects of the pricing change and our ensuing migration from App Engine to Amazon’s EC2, the impact on users, including cost structures and calculations.

For those of you who don’t have the time to read everything, here’s the

tl;dr version:

  • Google’s new pricing was totally out of line; we were able to re-create similar service at about 5% of the cost of running the service on App Engine.
  • Google’s policy has resulted in higher costs for them (XMPP messages used to be entirely within their network, but now have to be sent to and from EC2), and reduced their revenue (we, and others will likely shun App Engine)
  • App Engine requires a very different design paradigm from “normal” system design.
  • Some App Engine modules lock you in to the platform. We had to make all our users transition from channel@partychapp.appspotchat.com to channel@im.partych.at because Google does not allow us to point domain names elsewhere.
  • You can operate things on EC2 substantially more cheaply than App Engine if you design correctly.
  • I strongly recommend against running anything more complicated than a toy app on App Engine; if Google decides to arbitrarily change its pricing or change the services they offer, you’ll be screwed. There is really no easy migration path. Random pricing changes coupled with lack of polish in appscale means that any solution differing even slightly from the ordinary is “stuck” on appengine.
  • Transitioning a running app is pretty hard, especially when it’s an open source project done on spare time.
  • By (partially) transitioning off of app engine, we’ve actually reduced our cost from the pre-increase regime and can deliver roughly equivalent capacity for the same cost:

Before: $2/day.
With price increase: ~$20/day.
On EC2(no prepay)/App engine hybrid: $1/day.
On EC2(annual prepay)/App engine hybrid: $0.80/day.
At this point, residual app engine charges still amount to approximately $0.50/day.
On EC2(annual prepay)/App engine hybrid using more memcache: $0.60/day.

Background:

Partychat is a group chat service. By going to a web site, or sending an IM, users create virtual chat rooms. All messages sent to that chat room alias are then broadcast to all other users in that channel. Here is an example of two channels with two sending users.

This is what happens from the perspective of our app:

Google’s service calls an HTTP POST for every inbound message to a channel, and outbound messages are sent via API calls.

Cost estimates:

Before Google’s pricing changes, our daily cost to process messages was about $2/day. Before the new pricing went into effect, I used some anonymous logging information to forecast how much the service would cost to operate in the new pricing regime.

As you can see from the graph, even limiting the maximum room size to 200 people (which would be a major disruption to our services), would have cost us well over $10/day, which is really unacceptable.

Migration:

Since this was an open-source project I decided to take the simplest approach possible to make this migration. I’d create an XMPP server on EC2 that would simply do all the sending and receiving of XMPP messages instead of App Engine.

Note that as a result of their policy, Google makes less money AND has higher costs! (All XMPP traffic now gets routed through EC2, which is taking up bandwidth on their peering links)

Our App Engine app still does almost all of the processing of messages (including deciding who gets sent which messages), but does not do the actual fanout (i.e. creating n identical messages for a broadcast message). That is handled in the proxy.

XMPP Server:

In order to run an XMPP proxy, we need to deploy an XMPP server with the ability to federate to other servers, and code that interfaces with that server and receives and sends messages.

There are a bunch of XMPP servers out there, but the overall consensus is that ejabberd, a server written in Erlang (!) is the best and most stable. It’s proven to be extremely stable, and efficient. The big issue is that configuration is really difficult and not very well documented. A couple of important points that took forever to debug:

  • ejabberd has a default traffic shaping policy. Traffic shaping restricts in-bound and outbound network traffic to according to a policy. Traffic that exceeds the limits are buffered until the buffer is full, then dropped. Partychat’s message load can often be substantially higher than the default policy’s limit for sustained periods, resulting in randomly-dropped messages.
  • if multiple servers associate with one component (more on this in the next section) ejabberd will round robin messages between the connections. This means that your servers have to run on roughly equal machines.

Proxy code:

XMPP supports two connection types, Client and Component. A client connection is what your chat client uses to connect to a server. It requires one connection per user, and the server remembers all the important state (who you are friends with, etc..). This is by far the simplest solution for writing something like partychat, but there are a few problems. It requires the server to keep track of some state that we don’t care about (Are the users online? What are their status messages? etc..) which adds load to the server’s database. This can be solved by increasing database capacity, but this is wasteful since these data are not used. More importantly, using client connections will require one TCP connection per user (see the image below). This means that for our service, with ~ 50k users, our server will need to handle 50k TCP connections. This is already a really large number, and will not scale that well.

The alternative (which I selected) was to use a component interface (see above image), which essentially gives you the raw XML stream for any subdomain. Your code is then responsible for maintaining all state, responding to presence and subscription requests.

Initially we used SleekXMPP, a python library to manage component connections. The state was stored in RAM and then periodically serialized and written out to disk. Since XMPP has provisions for servers to rebuild their state in case of data loss without human involvement, losing state is not catastrophic, though it results in substantially higher load on the system while redundant subscription messages are dispatched and processed. The state that we store currently contains:

user := string (email)
channel:= string (name of channel, utf-8)
inbound_state := {UNKNOWN, PENDING, REJECTED, OK}
outbound_state:= {UNKNOWN, PENDING, REJECTED, OK}
last_outbound_request := timestamp

The last outbound request timestamp is required to prevent subscription loops in case sequence ids are not supported (the spec details why this is important.)

Each inbound message results in an https request to the app engine server. The server responds with JSON containing a message that is to be sent, a list of all recipients, and the channel from which it is to be sent.

The python library was OK, but did not really operate too well at our scale. Profiling showed that much time was spent copying data around. The server periodically crashed or hung, resulting in dropped messages and instability. The inefficiency required us to use a medium instance ($0.17/hour) to serve traffic, which put us at about $4/day. Still substantially lower than App Engine, but too high!

The server was then re-written in C++, using gloox, libcurl, openssl, and pthreads. Each message is dispatched to a threadpool. Blocking https calls are made to the App Engine server, and the results are then sent via ejabberd. This server is able to handle our max load (~ 12-16 inbound messages per second, resulting in around 400-600 outbound messages per second) at under 5% cpu load on a micro instance (at $0.02/hour).

The system is mostly stable (a lingering concurrency bug causes it to crash and automatically restart about once every 12 hours) and should provide us with substantial room to scale in the future.

Issues:

Google Apps for Your Domain has grown in popularity recently. This presents us with a problem; in order for XMPP messages to be delivered to users on a domain, a DNS SRV record needs to exist for this domain. Google does not automatically create this record, but messages between google apps domains get delivered correctly (so we never saw this issue with app engine).

Another issue that slowed down development a lot was that some clients (generally iTeleport) send invalid XML over the wire, which cause the python XML code to throw namespace exceptions. This made SleekXMPP even less reliable, and required making code changes in core Python libraries. The C++ libraries handle this gracefully.

Future work:

In the near future, we will be disabling old @partychat.appspot.com aliases. Other future work includes billing for large channels, and reducing the number of write operations on App Engine.

Conclusions

Working on this project has been quite educational. First of all, migrating a running service with many users from Google App Engine is hard, especially if it uses esoteric services, such as XMPP. Appscale is a reasonable platform that could help with the transition, but it is difficult to use, and may not be fully ready for production. Google App Engine’s insistence on a different paradigm for development makes migration extremely difficult, since moving to a new platform requires rearchitecting code.

An even bigger problem is the fact that some aspects of your system (e.g. XMPP domains) are not under your control. We had to migrate our users to a new chat domain, because Google did not allow us to point our domain elsewhere. This was a huge inconvenience for our users. Since our service is free, it was less of a big deal, but for an actual paid service, this would be a serious problem.

Since pricing is subject to rapid, arbitrary changes, and transitioning is difficult, no system that is likely to become productionized at scale should be written on App Engine. EC2’s monitoring and auto-scaling systems (more on this in a subsequent post) are excellent, and don’t require buying into a specific design paradigm. In fact, moving this proxy to a private server, or rackspace would be quite trivial.

Edit: I wanted to add this, just to clarify my point:
It’s more than just a price/stability tradeoff. The problem is, as an App Engine user, one is totally at the mercy of any future price changes on App Engine because it is nearly impossible to seamlessly migrate away. The DNS aliases can only point to Google, and the API does not really work well on any other platform. So, at any time in the future, one’s service could suddenly cost 10x as much, and one won’t really have the option to move quickly. If one intends to scale, it’s better to never get into that state in the first place, and develop on EC2 instead. If EC2 raises its prices (highly unlikely since computing power is increasing and costs are decreasing), one can always move to rackspace or just get a private server.

It’s of course true that writing stuff on App Engine can sometimes require a lot less engineering work. But the difference is not really that substantial when compared to the possibility of being stuck on a platform that all of a sudden makes your company unprofitable. Changing a running service is very hard. Avoiding the problem by not getting stuck on App Engine is not trivial, but in my opinion the right call.

10 March

KindleFeeds, an RSS reader Andrew and I wrote

Check out Kindle Feeds, a cool little app Andrew and I wrote. It lets you subscribe to RSS feeds, and generates a kindle-compliant “book” that you can download on to your kindle. The book has a table of contents and a nice link at the top which will fetch a new version of the book with only new posts. It’s really quite easy and you can update anywhere you have cell phone coverage.


In case you’re wondering here’s a bit of background:

A while back, Andrew wrote this cool application in python that let you store static HTML pages from the web into kindle docs that you could then download at will. (The old version of this was called Bibliorize and still lives up on www.bibliorize.com. But I’m gonna merge the two this week sometime and maybe find a new home for it somewhere.)

This seemed awesome, but had a few drawbacks; the main one that you had to manually add each page you wanted to read. That’s a lot of work for a lazy person like me, and not so useful when most of the things I read come from RSS(/atom/whatever) feeds. So, before a recent flight to SF, it dawned on me that the solution was to expand Andrew’s app to allow users to subscribe to RSS feeds. Also, this app needed to be able to automatically update nicely, so that no feeds were repeated. Updating OTA was cool, of course. I wanted to remove the need for users to log in on their Kindle, a painstaking and error-prone process. So I spent the six or so hours coding (coding without access to the Internet is surprisingly difficult!). And with a few more hours later, I think this app does all that!

There are a lot of bugs and things to improve though, not the least of which is the hideous colour scheme. We also need to pretty up the handling of dates and make the table of contents a bit more usable. Also we have to settle on a name for it.

Stay tuned!!