port implementation from MPlayer