Sunday 19 January 2020

Escapeless, Restartable, Binary Encoding

Imagine you are broadcasting a message over the air by Morse code. The message (or plain text) is made up of words of capital letters separated by spaces:

THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

But, for some unexplained reason, you cannot transmit spaces – only the twenty-six letters. How would you come up with a protocol for transmitting messages such that a receiver can unambiguously reconstruct the plain text?

The obvious first stab is to transmit the message without spaces and hope the receiver can guess where the spaces should be:

THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG

This is fine for relatively intelligent humans, but fraught with problems for machines. And it's far from "unambiguous":

ADAPTORBIT
BANALLIES
TEACHART
UNCLEARRAY
UNDONEGATE

Another solution is to designate one letter as an escape character and append a discriminator after each occurrence. For instance, we could use "Z" as the escape character and use "ZS" to signify a space and "ZZ" to signify a single "Z" in the original message:

THEZSQUICKZSBROWNZSFOXZSJUMPSZSOVERZSTHEZSLAZZYZSDOG

Escaping is common in programming language source files with a finite character set: for example, "\" is utilised in string constants in many "curly brace" languages. Generally, one picks an "unlikely" character as the escape.

There are two problems with escaping in this manner:
  1. The length of the encoded message depends on the number of occurrences of the escape character in the plain text. A pathological case is where the plain text consists solely of repeats of the escape character (e.g. "ZZZZZZZZ"); this results in an encoding that is twice the size of the original.
  2. If part of the message is lost or corrupted, it is very difficult to reconstruct (or re-synchronise) the plain text particular when an escape sequence is "cracked" (e.g. "...SBROWNZ...")
We can address Point 2 by using a more sophisticated encoding scheme that is "restartable". This means that if part of the message is corrupt or missing we can, at least, re-synchronise with the data stream at a later point. An example of a restartable stream is UTF-8: you can always distinguish the start of a new code point from a continuation by looking at the top two bits of the byte. However, this doesn't solve the problem of variable encoding size and pathological bloat.

In encoding theory, this problem is characterised as encoding data in one alphabet into another smaller alphabet. In the case above, we're trying to encode a message in a 27-code alphabet into a 26-code one.

In real life, it's quite common to want to transmit arbitrary 8-bit binary data over a one-way channel as a series of distinct messages. If the communications channel isn't perfect, we probably want to be able to re-synchronise to the start of the next message after a failure. If the channel is indeed one-way, we cannot ask the sender to re-transmit; so it is up to the receiver to recover as best they can.

If we use a unique sentinel between the messages, this process is analogous to trying to encode a 257-code alphabet (256 byte values + 1 sentinel) using a 256-code alphabet (a byte stream).

This looks like a tall order and if you naively try to convert an arbitrarily-long, base-257 number to base-256 you quickly run out of steam. However, a nice trick outlined by Ivan Kosarev leads to a breakthrough.

Supposing we separate the binary messages in their encoded form using a single zero byte: 0x00. We must be careful not to use 0x00 within the encoded message otherwise we wouldn't be able to re-synchronise to the start of the next message after a failure. We could choose a non-zero byte value as a substitute for 0x00 in the original message and replace all occurrences of zero with the zero-substitute value. However, how do we choose the zero-substitute value in such a way that it is guaranteed not to occur in the original message?

Consider dividing the original messages up into 254-byte chunks. Within each chunk, there is guaranteed to be at least one non-zero byte value that does not occur. (We could not use 255-byte chunks because of the edge case where all byte values 0x01 to 0xFF occur leaving no non-zero value for the zero-substitute) For each chunk, pick the highest byte value that does not occur as the zero-substitute for that chunk.

Our encoding algorithm then becomes:

for each message:
  split message into chunks of 254 bytes (last may be smaller)
  for each chunk:
    substitute := greatest byte value not present within chunk
    output substitute
    for each byte in chunk:
      if byte == 0x00:
        output substitute
      else:
        output byte
  output 0x00

This isn't quite a true streaming algorithm because you've got to collect 254-byte chunks to find the appropriate zero-substitute. But it's close.

Decoding requires less bookkeeping:

message := empty byte buffer
count := 0
for each byte in input stream:
  if byte == 0x00:
    output message
    reset message to empty byte buffer
    count := 0
  else if count == 0:
    substitute := byte
    count := 254
  else
    count := count - 1
    if byte == sentinel:
      append 0x00 to message
    else:
      append byte to message

Both the encoder and decoder can be implemented on machines with very limited resources. Neither needs to know anything about the format of the messages they are processing.

If a failure is detected, you can quickly fast-forward the data stream to the beginning of the next message by searching for a 0x00 byte. Note that we assume that some robust checksum is encoded into the messages to detect corruption with high probability.

Crucially, the relationship between the size of the plain messages and their encoded forms does not rely on the content of the messages:

encoded_size == floor((plain_size * 255 + 253) / 254) + 1

The "encoded_size" includes the zero byte separator between messages. For large messages, the data overhead (excluding the separator) tends towards less than 0.4%. For small messages (less than the chunk size), the overhead is never more than one byte.

An interesting variant is to XOR the current substitute value with all bytes so as to obfuscate the payload:

for each message:
  split message into chunks of 254 bytes (last may be smaller)
  for each chunk:
    substitute := greatest byte value not present within chunk
    output substitute
    for each byte in chunk:
      output (byte xor substitute)
  output 0x00

Decoding with obfuscation:

message := empty byte buffer
count := 0
for each byte in input stream:
  if byte == 0x00:
    output message
    reset message to empty byte buffer
    count := 0
  else if count == 0:
    substitute := byte
    count := 254
  else
    count := count - 1
    append (byte xor substitute) to message