Friday, August 11, 2006

Having fun with Bitmaps in AS3

So, I wanted to grab a snapshot from my camera in Flash Player and send the image to the server to share it in a web conference.

Thanks to the excellent work of Tinic Uro of Adobe I started off with adding his AS3 port of a JPEG encoder to my app to make sure that it doesn't send megabytes data to my server. Have a look here for his article on the AS3 JPEGEncoder.

It turned out that my pc is a bit slow and will take about 8 seconds to encode a 640x480 bitmap. This wouldn't be so bad if Flash Player was multi-threaded, but as it is, the player (and the browser that runs it) will block during the encoding. On my newer laptop, the encoding only takes about 1 second. But hey, I'm probably not the only one that has an older PC, so I decided to do something about the blocking.

I modified the JPEGEncoder class so that it chops up the work in chunks and automatically adapts the chunksize to a maximum blocking delay that is configurable. It also emits ProgressEvent's and a complete event when done. And I threw in a cancel() function as well. Here's the source for JPEGEncoder with ProgressEvent.

With this modification, the encoder pauses for 10 ms about every 200ms to let the player do other things like updating the display list while only adding about 5% to the processing time. And I added a progress bar to show the user how the encoder is doing.

Have fun with it.