cherry-pick encoding fixes from @lste