Lock the encoder early during write.

Previously, only the flush operation was interlocked, which lead to
buffer corruption due to the fact that the buffer itself wasn't guarded,
meaning multiple threads could've been able to write there
simultaneously.