Patch by Baptiste with some fixes by me. Originally committed as revision 25880 to svn://svn.ffmpeg.org/ffmpeg/trunk