title: Dealing with Padding / Stuff Bits Entropy Encoded JPEG
body: <p>When <a href="http://www.impulseadventure.com/photo/jpeg-huffman-coding.html" rel="nofollow">decoding entropy encoded DC values in JPEG</a> (or the <a href="https://en.wikipedia.org/wiki/Lossless_JPEG" rel="nofollow">entropy encoded prediction differences in lossless JPEG</a>), how do I distinguish between <code>1</code> bits that have been stuffed to pad a byte before a marker and a Huffman coded value?</p>
  
  <p>For example if I see:</p>
  
  <pre><code>0xAF 0xFF 0xD9
  </code></pre>
  
  <p>and I have already consumed the bits in <code>[0xA]</code>, how can I tell if the next <code>0xF</code> is padded or should be decoded?</p>
  
  <p>This is from the JPEG Spec:</p>
  
  <blockquote>
    <p>F.1.2.3 Byte stuffing </p>
    
    <p>In order to provide code space for marker codes
    which can be located in the compressed image data without decoding,
    byte stuffing is used. </p>
    
    <p>Whenever, in the course of normal encoding, the
    byte value X’FF’ is created in the code string, a X’00’ byte is
    stuffed into the code string. If a X’00’ byte is detected after a
    X’FF’ byte, the decoder must discard it. If the byte is not zero, a
    marker has been detected, and shall be interpreted to the extent
    needed to complete the decoding of the scan. </p>
    
    <p>Byte alignment of markers
    is achieved by padding incomplete bytes with 1-bits. If padding with
    1-bits creates a X’FF’ value, a zero byte is stuffed before adding the
    marker.</p>
  </blockquote>