Code copied from Libav, commit 26e4f0c70. Will eventually be moved to -ugly because underlying code is GPL.