Rust PNG Decoder

Matthieu Pizenberg
Pure Rust PNG decoder with good performances in WebAssembly
2019

Code

This project aims at implementing a pure Rust PNGĀ decoder, in order to facilitate usage of PNG images in the context of WebAssembly. The code is available online on GitHub at mpizenberg/png-decoder. There already exists a well-known PNG decoding crate image-rs/image-png. At the time I needed WebAssembly support though, it was too slow for real time decoding of images in the browser. I have discussed performances issues on GitHub. As displayed in the following flame graph, it was taking 100 ms to decode two 640x480 PNGĀ images, one for the color image, the other for the depth.

From the fact that OpenCV decodes images much faster, and that Rust should have similar performances than C++, I decided to give a try at a new PNG decoder. This implementation keeps in mind that it should be "wasm-friendly", meaning we limit the number of memory allocations, which is more costly in WebAssembly.

The PNG specification is available online. Under the hood, the pixel metadata is compressed with the deflate algorithm, whose spec is also available online. PNG is a simple structured format. A file contains successive data blocks called chunks of different types. The most interesting types are IHDR (header), IDAT (data) and IEND (end of file). The body of the image is composed by successive IDAT blocks containing transformed lines of the image (called "filtered") to reduce entropy, then compressed with the deflate algorithm. I have implemented the parsing with a fast parser combinator library called nom. The unfiltering is just simple code. Fortunately, a very fast deflate decoder (often called "inflate") already exists in Rust, so we reused that crate named miniz-oxide.

After a few round of optimizations, the performances of the decoding code are great, especially for images with a majority of Sub scanline filters (like the "depth", "eye", "rgb" and "texture_alpha" images in table below). I've written down an approach comparison with the png crate in rust discourse forum in case interested. Below is a table summarizing decoding timings for images I used while writing the code.

Imagethispng crateOpenCVthis (wasm)png (wasm)
depth.png4.0 ms9.1 ms4.0 ms8.5 ms30.7 ms
eye.png0.48 ms0.96 ms0.72 ms1.5 ms5.9 ms
inkscape.png7.1 ms9.6 ms6.6 ms13.4 ms30.2 ms
rgb.png6.6 ms16.0 ms6.5 ms13.7 ms52.1 ms
screen.png6.5 ms10.2 ms6.6 ms11.6 ms29.8 ms
texture_alpha.png0.68 ms1.94 ms0.99 ms1.8 ms8.0 ms
transparent.png15.2 ms17.4 ms13.2 ms26.1 ms55.8 ms