Make hd encoder ordering aware and one-pass

The encoder algorithm is simplified and it now preserves ordering
of the headers. It also becomes one-pass encoder.