Partially based on a patch by Timo Rothenpieler <timo@rothenpieler.org>. Additional scaling list handling fix by Jun Zhao <mypopydev@gmail.com>.