<?xml version="1.0" encoding="utf-8"?>
<!-- name="GENERATOR" content="github.com/mmarkdown/mmark Mmark Markdown Processor - mmark.nl" -->
<rfc docName="draft-ietf-cellar-ffv1-v4-05" version="3" ipr="trust200902" submissionType="IETF" category="std" xml:lang="en" consensus="true" xmlns:xi="http://www.w3.org/2001/XInclude">

<front>
<title abbrev="FFV1">FFV1 Video Coding Format Version 4</title><seriesInfo value="draft-ietf-cellar-ffv1-v4-05" stream="IETF" status="standard" name="Internet-Draft"></seriesInfo>
<author initials="M." surname="Niedermayer" fullname="Michael Niedermayer"><organization></organization><address><postal><street></street>
</postal><email>michael@niedermayer.cc</email>
</address></author>
<author initials="D." surname="Rice" fullname="Dave Rice"><organization></organization><address><postal><street></street>
</postal><email>dave@dericed.com</email>
</address></author>
<author initials="J." surname="Martinez" fullname="Jerome Martinez"><organization></organization><address><postal><street></street>
</postal><email>jerome@mediaarea.net</email>
</address></author>
<date/>
<area>art</area>
<workgroup>cellar</workgroup>

<abstract>
<t>This document defines FFV1, a lossless intra-frame video encoding format. FFV1 is designed to efficiently compress video data in a variety of pixel formats. Compared to uncompressed video, FFV1 offers storage compression, frame fixity, and self-description, which makes FFV1 useful as a preservation or intermediate video format.</t>
</abstract>

</front>

<middle>

<section anchor="introduction"><name>Introduction</name>
<t>This document describes FFV1, a lossless video encoding format. The design of FFV1 considers the storage of image characteristics, data fixity, and the optimized use of encoding time and storage requirements. FFV1 is designed to support a wide range of lossless video applications such as long-term audiovisual preservation, scientific imaging, screen recording, and other video encoding scenarios that seek to avoid the generational loss of lossy video encodings.</t>
<t>This document defines a version 4 of FFV1. Prior versions of FFV1 are defined within <xref target="I-D.ietf-cellar-ffv1"></xref>.</t>
<t>The latest version of this document is available at <eref target="https://raw.github.com/FFmpeg/FFV1/master/ffv1.md">https://raw.github.com/FFmpeg/FFV1/master/ffv1.md</eref></t>
<t>This document assumes familiarity with mathematical and coding concepts such as Range coding <xref target="range-coding"></xref> and YCbCr color spaces <xref target="YCbCr"></xref>.</t>
</section>

<section anchor="notation-and-conventions"><name>Notation and Conventions</name>
<t>The key words &quot;MUST&quot;, &quot;MUST NOT&quot;, &quot;REQUIRED&quot;, &quot;SHALL&quot;, &quot;SHALL NOT&quot;, &quot;SHOULD&quot;, &quot;SHOULD NOT&quot;, &quot;RECOMMENDED&quot;, &quot;MAY&quot;, and &quot;OPTIONAL&quot; in this document are to be interpreted as described in <xref target="RFC2119"></xref>.</t>

<section anchor="definitions"><name>Definitions</name>
<t><tt>Container</tt>: Format that encapsulates <tt>Frames</tt> (see <eref target="#frame">the section on Frames</eref>) and (when required) a <tt>Configuration Record</tt> into a bitstream.</t>
<t><tt>Sample</tt>: The smallest addressable representation of a color component or a luma component in a <tt>Frame</tt>. Examples of <tt>Sample</tt> are Luma, Blue Chrominance, Red Chrominance, Transparency, Red, Green, and Blue.</t>
<t><tt>Plane</tt>: A discrete component of a static image comprised of <tt>Samples</tt> that represent a specific quantification of <tt>Samples</tt> of that image.</t>
<t><tt>Pixel</tt>: The smallest addressable representation of a color in a <tt>Frame</tt>. It is composed of 1 or more <tt>Samples</tt>.</t>
<t><tt>ESC</tt>:   An ESCape symbol to indicate that the symbol to be stored is too large for normal storage and that an alternate storage method is used.</t>
<t><tt>MSB</tt>:   Most Significant Bit, the bit that can cause the largest change in magnitude of the symbol.</t>
<t><tt>RCT</tt>:   Reversible Color Transform, a near linear, exactly reversible integer transform that converts between RGB and YCbCr representations of a <tt>Pixel</tt>.</t>
<t><tt>VLC</tt>:   Variable Length Code, a code that maps source symbols to a variable number of bits.</t>
<t><tt>RGB</tt>:   A reference to the method of storing the value of a <tt>Pixel</tt> by using three numeric values that represent Red, Green, and Blue.</t>
<t><tt>YCbCr</tt>: A reference to the method of storing the value of a <tt>Pixel</tt> by using three numeric values that represent the luma of the <tt>Pixel</tt> (Y) and the chrominance of the <tt>Pixel</tt> (Cb and Cr). YCbCr word is used for historical reasons and currently references any color space relying on 1 luma <tt>Sample</tt> and 2 chrominance <tt>Samples</tt>, e.g. YCbCr, YCgCo or ICtCp. The exact meaning of the three numeric values is unspecified.</t>
<t><tt>TBA</tt>:   To Be Announced. Used in reference to the development of future iterations of the FFV1 specification.</t>
</section>

<section anchor="conventions"><name>Conventions</name>

<section anchor="pseudo-code"><name>Pseudo-code</name>
<t>The FFV1 bitstream is described in this document using pseudo-code. Note that the pseudo-code is used for clarity in order to illustrate the structure of FFV1 and not intended to specify any particular implementation. The pseudo-code used is based upon the C programming language <xref target="ISO.9899.1990"></xref> and uses its <tt>if/else</tt>, <tt>while</tt> and <tt>for</tt> functions as well as functions defined within this document.</t>
</section>

<section anchor="arithmetic-operators"><name>Arithmetic Operators</name>
<t>Note: the operators and the order of precedence are the same as used in the C programming language <xref target="ISO.9899.1990"></xref>.</t>
<t><tt>a + b</tt>       means a plus b.</t>
<t><tt>a - b</tt>       means a minus b.</t>
<t><tt>-a</tt>          means negation of a.</t>
<t><tt>a * b</tt>       means a multiplied by b.</t>
<t><tt>a / b</tt>       means a divided by b.</t>
<t><tt>a ^ b</tt>       means a raised to the b-th power.</t>
<t><tt>a &amp; b</tt>       means bit-wise &quot;and&quot; of a and b.</t>
<t><tt>a | b</tt>       means bit-wise &quot;or&quot; of a and b.</t>
<t><tt>a &gt;&gt; b</tt>      means arithmetic right shift of two’s complement integer representation of a by b binary digits.</t>
<t><tt>a &lt;&lt; b</tt>      means arithmetic left shift of two’s complement integer representation of a by b binary digits.</t>
</section>

<section anchor="assignment-operators"><name>Assignment Operators</name>
<t><tt>a = b</tt>       means a is assigned b.</t>
<t><tt>a++</tt>         is equivalent to a is assigned a + 1.</t>
<t><tt>a--</tt>         is equivalent to a is assigned a - 1.</t>
<t><tt>a += b</tt>      is equivalent to a is assigned a + b.</t>
<t><tt>a -= b</tt>      is equivalent to a is assigned a - b.</t>
<t><tt>a *= b</tt>      is equivalent to a is assigned a * b.</t>
</section>

<section anchor="comparison-operators"><name>Comparison Operators</name>
<t><tt>a &gt; b</tt>       means a is greater than b.</t>
<t><tt>a &gt;= b</tt>      means a is greater than or equal to b.</t>
<t><tt>a &lt; b</tt>       means a is less than b.</t>
<t><tt>a &lt;= b</tt>      means a is less than or equal b.</t>
<t><tt>a == b</tt>      means a is equal to b.</t>
<t><tt>a != b</tt>      means a is not equal to b.</t>
<t><tt>a &amp;&amp; b</tt>      means Boolean logical &quot;and&quot; of a and b.</t>
<t><tt>a || b</tt>      means Boolean logical &quot;or&quot; of a and b.</t>
<t><tt>!a</tt>          means Boolean logical &quot;not&quot; of a.</t>
<t><tt>a ? b : c</tt>   if a is true, then b, otherwise c.</t>
</section>

<section anchor="mathematical-functions"><name>Mathematical Functions</name>
<t>floor(a)              the largest integer less than or equal to a</t>
<t>ceil(a)               the smallest integer greater than or equal to a</t>
<t>sign(a)               extracts the sign of a number, i.e. if a &lt; 0 then -1, else if a &gt; 0 then 1, else 0</t>
<t>abs(a)                the absolute value of a, i.e. abs(a) = sign(a)*a</t>
<t>log2(a)               the base-two logarithm of a</t>
<t>min(a,b)              the smallest of two values a and b</t>
<t>max(a,b)              the largest of two values a and b</t>
<t>median(a,b,c)         the numerical middle value in a data set of a, b, and c, i.e. a+b+c-min(a,b,c)-max(a,b,c)</t>
<t>a_{b}                 the b-th value of a sequence of a</t>
<t>a_{b,c}               the 'b,c'-th value of a sequence of a</t>
</section>

<section anchor="order-of-operation-precedence"><name>Order of Operation Precedence</name>
<t>When order of precedence is not indicated explicitly by use of parentheses, operations are evaluated in the following order (from top to bottom, operations of same precedence being evaluated from left to right). This order of operations is based on the order of operations used in Standard C.</t>

<artwork>a++, a--
!a, -a
a ^ b
a * b, a / b, a % b
a + b, a - b
a &lt;&lt; b, a &gt;&gt; b
a &lt; b, a &lt;= b, a &gt; b, a &gt;= b
a == b, a != b
a &amp; b
a | b
a &amp;&amp; b
a || b
a ? b : c
a = b, a += b, a -= b, a *= b
</artwork>
</section>

<section anchor="range"><name>Range</name>
<t><tt>a...b</tt> means any value starting from a to b, inclusive.</t>
</section>

<section anchor="numbytes"><name>NumBytes</name>
<t><tt>NumBytes</tt> is a non-negative integer that expresses the size in 8-bit octets of a particular FFV1 <tt>Configuration Record</tt> or <tt>Frame</tt>. FFV1 relies on its <tt>Container</tt> to store the <tt>NumBytes</tt> values, see <eref target="#mapping-ffv1-into-containers">the section on the Mapping FFV1 into Containers</eref>.</t>
</section>

<section anchor="bitstream-functions"><name>Bitstream Functions</name>

<section anchor="remaining-bits-in-bitstream"><name>remaining_bits_in_bitstream</name>
<t><tt>remaining_bits_in_bitstream( )</tt> means the count of remaining bits after the pointer in that <tt>Configuration Record</tt> or <tt>Frame</tt>. It is computed from the <tt>NumBytes</tt> value multiplied by 8 minus the count of bits of that <tt>Configuration Record</tt> or <tt>Frame</tt> already read by the bitstream parser.</t>
</section>

<section anchor="remaining-symbols-in-syntax"><name>remaining_symbols_in_syntax</name>
<t><tt>remaining_symbols_in_syntax( )</tt> is true as long as the RangeCoder has not consumed all the given input bytes.</t>
</section>

<section anchor="byte-aligned"><name>byte_aligned</name>
<t><tt>byte_aligned( )</tt> is true if <tt>remaining_bits_in_bitstream( NumBytes )</tt> is a multiple of 8, otherwise false.</t>
</section>

<section anchor="get-bits"><name>get_bits</name>
<t><tt>get_bits( i )</tt> is the action to read the next <tt>i</tt> bits in the bitstream, from most significant bit to least significant bit, and to return the corresponding value. The pointer is increased by <tt>i</tt>.</t>
</section>
</section>
</section>
</section>

<section anchor="sample-coding"><name>Sample Coding</name>
<t>For each <tt>Slice</tt> (as described in <eref target="#slice">the section on Slices</eref>) of a <tt>Frame</tt>, the <tt>Planes</tt>, <tt>Lines</tt>, and <tt>Samples</tt> are coded in an order determined by the <tt>Color Space</tt> (see <eref target="#color-spaces">the section on Color Space</eref>). Each <tt>Sample</tt> is predicted by the median predictor as described in <eref target="#median-predictor">the section of the Median Predictor</eref> from other <tt>Samples</tt> within the same <tt>Plane</tt> and the difference is stored using the method described in <eref target="#coding-of-the-sample-difference">Coding of the Sample Difference</eref>.</t>

<section anchor="border"><name>Border</name>
<t>A border is assumed for each coded <tt>Slice</tt> for the purpose of the median predictor and context according to the following rules:</t>

<ul>
<li><t>one column of <tt>Samples</tt> to the left of the coded slice is assumed as identical to the <tt>Samples</tt> of the leftmost column of the coded slice shifted down by one row. The value of the topmost <tt>Sample</tt> of the column of <tt>Samples</tt> to the left of the coded slice is assumed to be <tt>0</tt></t>
</li>
<li><t>one column of <tt>Samples</tt> to the right of the coded slice is assumed as identical to the <tt>Samples</tt> of the rightmost column of the coded slice</t>
</li>
<li><t>an additional column of <tt>Samples</tt> to the left of the coded slice and two rows of <tt>Samples</tt> above the coded slice are assumed to be <tt>0</tt></t>
</li>
</ul>
<t>The following table depicts a slice of 9 <tt>Samples</tt> <tt>a,b,c,d,e,f,g,h,i</tt> in a 3x3 arrangement along with its assumed border.</t>

<artwork>+---+---+---+---+---+---+---+---+
| 0 | 0 |   | 0 | 0 | 0 |   | 0 |
+---+---+---+---+---+---+---+---+
| 0 | 0 |   | 0 | 0 | 0 |   | 0 |
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+
| 0 | 0 |   | a | b | c |   | c |
+---+---+---+---+---+---+---+---+
| 0 | a |   | d | e | f |   | f |
+---+---+---+---+---+---+---+---+
| 0 | d |   | g | h | i |   | i |
+---+---+---+---+---+---+---+---+
</artwork>
</section>

<section anchor="samples"><name>Samples</name>
<t>Relative to any <tt>Sample</tt> <tt>X</tt>, six other relatively positioned <tt>Samples</tt> from the coded <tt>Samples</tt> and presumed border are identified according to the labels used in the following diagram. The labels for these relatively positioned <tt>Samples</tt> are used within the median predictor and context.</t>

<artwork>+---+---+---+---+
|   |   | T |   |
+---+---+---+---+
|   |tl | t |tr |
+---+---+---+---+
| L | l | X |   |
+---+---+---+---+
</artwork>
<t>The labels for these relative <tt>Samples</tt> are made of the first letters of the words Top, Left and Right.</t>
</section>

<section anchor="median-predictor"><name>Median Predictor</name>
<t>The prediction for any <tt>Sample</tt> value at position <tt>X</tt> may be computed based upon the relative neighboring values of <tt>l</tt>, <tt>t</tt>, and <tt>tl</tt> via this equation:</t>
<t><tt>median(l, t, l + t - tl)</tt>.</t>
<t>Note, this prediction template is also used in <xref target="ISO.14495-1.1999"></xref> and <xref target="HuffYUV"></xref>.</t>
<t>Exception for the median predictor:
if <tt>colorspace_type == 0 &amp;&amp; bits_per_raw_sample == 16 &amp;&amp; ( coder_type == 1 || coder_type == 2 )</tt>, the following median predictor MUST be used:</t>
<t><tt>median(left16s, top16s, left16s + top16s - diag16s)</tt></t>
<t>where:</t>

<artwork>left16s = l  &gt;= 32768 ? ( l  - 65536 ) : l
top16s  = t  &gt;= 32768 ? ( t  - 65536 ) : t
diag16s = tl &gt;= 32768 ? ( tl - 65536 ) : tl
</artwork>
<t>Background: a two's complement signed 16-bit signed integer was used for storing <tt>Sample</tt> values in all known implementations of FFV1 bitstream. So in some circumstances, the most significant bit was wrongly interpreted (used as a sign bit instead of the 16th bit of an unsigned integer). Note that when the issue is discovered, the only configuration of all known implementations being impacted is 16-bit YCbCr with no Pixel transformation with Range Coder coder, as other potentially impacted configurations (e.g. 15/16-bit JPEG2000-RCT with Range Coder coder, or 16-bit content with Golomb Rice coder) were implemented nowhere <xref target="ISO.15444-1.2016"></xref>. In the meanwhile, 16-bit JPEG2000-RCT with Range Coder coder was implemented without this issue in one implementation and validated by one conformance checker. It is expected (to be confirmed) to remove this exception for the median predictor in the next version of the FFV1 bitstream.</t>
</section>

<section anchor="context"><name>Context</name>
<t>Relative to any <tt>Sample</tt> <tt>X</tt>, the Quantized Sample Differences <tt>L-l</tt>, <tt>l-tl</tt>, <tt>tl-t</tt>, <tt>T-t</tt>, and <tt>t-tr</tt> are used as context:</t>

<artwork>context = Q_{0}[l − tl] +
          Q_{1}[tl − t] +
          Q_{2}[t − tr] +
          Q_{3}[L − l]  +
          Q_{4}[T − t]
</artwork>
<t>If <tt>context &gt;= 0</tt> then <tt>context</tt> is used and the difference between the <tt>Sample</tt> and its predicted value is encoded as is, else <tt>-context</tt> is used and the difference between the <tt>Sample</tt> and its predicted value is encoded with a flipped sign.</t>
</section>

<section anchor="quantization-table-sets"><name>Quantization Table Sets</name>
<t>The FFV1 bitstream contains 1 or more Quantization Table Sets. Each Quantization Table Set contains exactly 5 Quantization Tables with each Quantization Table corresponding to 1 of the 5 Quantized Sample Differences. For each Quantization Table, both the number of quantization steps and their distribution are stored in the FFV1 bitstream; each Quantization Table has exactly 256 entries, and the 8 least significant bits of the Quantized Sample Difference are used as index:</t>

<artwork>Q_{j}[k] = quant_tables[i][j][k&amp;255]
</artwork>
<t>In this formula, <tt>i</tt> is the Quantization Table Set index, <tt>j</tt> is the Quantized Table index, <tt>k</tt> the Quantized Sample Difference.</t>
</section>

<section anchor="quantization-table-set-indexes"><name>Quantization Table Set Indexes</name>
<t>For each <tt>Plane</tt> of each slice, a Quantization Table Set is selected from an index:</t>

<ul>
<li><t>For Y <tt>Plane</tt>, <tt>quant_table_set_index[ 0 ]</tt> index is used</t>
</li>
<li><t>For Cb and Cr <tt>Planes</tt>, <tt>quant_table_set_index[ 1 ]</tt> index is used</t>
</li>
<li><t>For extra <tt>Plane</tt>, <tt>quant_table_set_index[ (version &lt;= 3 || chroma_planes) ? 2 : 1 ]</tt> index is used</t>
</li>
</ul>
<t>Background: in first implementations of FFV1 bitstream, the index for Cb and Cr <tt>Planes</tt> was stored even if it is not used (chroma_planes set to 0), this index is kept for version &lt;= 3 in order to keep compatibility with FFV1 bitstreams in the wild.</t>
</section>

<section anchor="color-spaces"><name>Color spaces</name>
<t>FFV1 supports several color spaces. The count of allowed coded planes and the meaning of the extra <tt>Plane</tt> are determined by the selected color space.</t>
<t>The FFV1 bitstream interleaves data in an order determined by the color space. In YCbCr for each <tt>Plane</tt>, each <tt>Line</tt> is coded from top to bottom and for each <tt>Line</tt>, each <tt>Sample</tt> is coded from left to right. In JPEG2000-RCT for each <tt>Line</tt> from top to bottom, each <tt>Plane</tt> is coded and for each <tt>Plane</tt>, each <tt>Sample</tt> is encoded from left to right.</t>

<section anchor="ycbcr"><name>YCbCr</name>
<t>This color space allows 1 to 4 <tt>Planes</tt>.</t>
<t>The Cb and Cr <tt>Planes</tt> are optional, but if used then MUST be used together. Omitting the Cb and Cr <tt>Planes</tt> codes the frames in grayscale without color data.</t>
<t>An optional transparency <tt>Plane</tt> can be used to code transparency data.</t>
<t>An FFV1 <tt>Frame</tt> using YCbCr MUST use one of the following arrangements:</t>

<ul>
<li><t>Y</t>
</li>
<li><t>Y, Transparency</t>
</li>
<li><t>Y, Cb, Cr</t>
</li>
<li><t>Y, Cb, Cr, Transparency</t>
</li>
</ul>
<t>The Y <tt>Plane</tt> MUST be coded first. If the Cb and Cr <tt>Planes</tt> are used then they MUST be coded after the Y <tt>Plane</tt>. If a transparency <tt>Plane</tt> is used, then it MUST be coded last.</t>
</section>

<section anchor="rgb"><name>RGB</name>
<t>This color space allows 3 or 4 <tt>Planes</tt>.</t>
<t>An optional transparency <tt>Plane</tt> can be used to code transparency data.</t>
<t>JPEG2000-RCT is a Reversible Color Transform that codes RGB (red, green, blue) <tt>Planes</tt> losslessly in a modified YCbCr color space <xref target="ISO.15444-1.2016"></xref>. Reversible Pixel transformations between YCbCr and RGB use the following formulae.</t>

<artwork>Cb=b-g
</artwork>

<artwork>Cr=r-g
</artwork>

<artwork>Y=g+(Cb+Cr)&gt;&gt;2
</artwork>

<artwork>g=Y-(Cb+Cr)&gt;&gt;2
</artwork>

<artwork>r=Cr+g
</artwork>

<artwork>b=Cb+g
</artwork>
<t>Exception for the JPEG2000-RCT conversion: if bits<em>per</em>raw<em>sample is between 9 and 15 inclusive and extra</em>plane is 0, the following formulae for reversible conversions between YCbCr and RGB MUST be used instead of the ones above:</t>

<artwork>Cb=g-b
</artwork>

<artwork>Cr=r-b
</artwork>

<artwork>Y=b+(Cb+Cr)&gt;&gt;2
</artwork>

<artwork>b=Y-(Cb+Cr)&gt;&gt;2
</artwork>

<artwork>r=Cr+b
</artwork>

<artwork>g=Cb+b
</artwork>
<t>Background: At the time of this writing, in all known implementations of FFV1 bitstream, when bits<em>per</em>raw<em>sample was between 9 and 15 inclusive and extra</em>plane is 0, GBR <tt>Planes</tt> were used as BGR <tt>Planes</tt> during both encoding and decoding. In the meanwhile, 16-bit JPEG2000-RCT was implemented without this issue in one implementation and validated by one conformance checker. Methods to address this exception for the transform are under consideration for the next version of the FFV1 bitstream.</t>
<t>When FFV1 uses the JPEG2000-RCT, the horizontal <tt>Lines</tt> are interleaved to improve caching efficiency since it is most likely that the JPEG2000-RCT will immediately be converted to RGB during decoding. The interleaved coding order is also Y, then Cb, then Cr, and then if used transparency.</t>
<t>As an example, a <tt>Frame</tt> that is two <tt>Pixels</tt> wide and two <tt>Pixels</tt> high, could be comprised of the following structure:</t>

<artwork>+------------------------+------------------------+
| Pixel[1,1]             | Pixel[2,1]             |
| Y[1,1] Cb[1,1] Cr[1,1] | Y[2,1] Cb[2,1] Cr[2,1] |
+------------------------+------------------------+
| Pixel[1,2]             | Pixel[2,2]             |
| Y[1,2] Cb[1,2] Cr[1,2] | Y[2,2] Cb[2,2] Cr[2,2] |
+------------------------+------------------------+
</artwork>
<t>In JPEG2000-RCT, the coding order would be left to right and then top to bottom, with values interleaved by <tt>Lines</tt> and stored in this order:</t>
<t>Y[1,1] Y[2,1] Cb[1,1] Cb[2,1] Cr[1,1] Cr[2,1] Y[1,2] Y[2,2] Cb[1,2] Cb[2,2] Cr[1,2] Cr[2,2]</t>
</section>
</section>

<section anchor="coding-of-the-sample-difference"><name>Coding of the Sample Difference</name>
<t>Instead of coding the n+1 bits of the Sample Difference with Huffman or Range coding (or n+2 bits, in the case of JPEG2000-RCT), only the n (or n+1, in the case of JPEG2000-RCT) least significant bits are used, since this is sufficient to recover the original <tt>Sample</tt>. In the equation below, the term &quot;bits&quot; represents bits<em>per</em>raw<em>sample+1 for JPEG2000-RCT or bits</em>per<em>raw</em>sample otherwise:</t>

<artwork>coder_input =
    [(sample_difference + 2^(bits−1)) &amp; (2^bits − 1)] − 2^(bits−1)
</artwork>

<section anchor="range-coding-mode"><name>Range Coding Mode</name>
<t>Early experimental versions of FFV1 used the CABAC Arithmetic coder from H.264 as defined in <xref target="ISO.14496-10.2014"></xref> but due to the uncertain patent/royalty situation, as well as its slightly worse performance, CABAC was replaced by a Range coder based on an algorithm defined by G. Nigel and N. Martin in 1979 <xref target="range-coding"></xref>.</t>

<section anchor="range-binary-values"><name>Range Binary Values</name>
<t>To encode binary digits efficiently a Range coder is used. <tt>C_{i}</tt> is the i-th Context. <tt>B_{i}</tt> is the i-th byte of the bytestream. <tt>b_{i}</tt> is the i-th Range coded binary value, <tt>S_{0,i}</tt> is the i-th initial state. The length of the bytestream encoding n binary symbols is <tt>j_{n}</tt> bytes.</t>

<artwork>r_{i} = floor( ( R_{i} * S_{i,C_{i}} ) / 2^8 )
</artwork>

<artwork>S_{i+1,C_{i}} =  zero_state_{S_{i,C_{i}}} XOR
          l_i =  L_i                      XOR
          t_i =  R_i - r_i                &lt;==
          b_i =  0                        &lt;==&gt;
          L_i &lt;  R_i - r_i
</artwork>

<artwork>S_{i+1,C_{i}} =  one_state_{S_{i,C_{i}}}  XOR
          l_i =  L_i - R_i + r_i          XOR
          t_i =  r_i                      &lt;==
          b_i =  1                        &lt;==&gt;
          L_i &gt;= R_i - r_i
</artwork>

<artwork>S_{i+1,k} = S_{i,k} &lt;== C_i != k
</artwork>

<artwork>R_{i+1} =  2^8 * t_{i}                   XOR
L_{i+1} =  2^8 * l_{i} + B_{j_{i}}       XOR
j_{i+1} =  j_{i} + 1                     &lt;==
t_{i}   &lt;  2^8
</artwork>

<artwork>R_{i+1} =  t_{i}                         XOR
L_{i+1} =  l_{i}                         XOR
j_{i+1} =  j_{i}                         &lt;==
t_{i}   &gt;= 2^8
</artwork>

<artwork>R_{0} = 65280
</artwork>

<artwork>L_{0} = 2^8 * B_{0} + B_{1}
</artwork>

<artwork>j_{0} = 2
</artwork>

<section anchor="termination"><name>Termination</name>
<t>The range coder can be used in 3 modes.</t>

<ul>
<li><t>In <tt>Open mode</tt> when decoding, every symbol the reader attempts to read is available. In this mode arbitrary data can have been appended without affecting the range coder output. This mode is not used in FFV1.</t>
</li>
<li><t>In <tt>Closed mode</tt> the length in bytes of the bytestream is provided to the range decoder. Bytes beyond the length are read as 0 by the range decoder. This is generally 1 byte shorter than the open mode.</t>
</li>
<li><t>In <tt>Sentinel mode</tt> the exact length in bytes is not known and thus the range decoder MAY read into the data that follows the range coded bytestream by one byte. In <tt>Sentinel mode</tt>, the end of the range coded bytestream is a binary symbol with state 129, which value SHALL be discarded. After reading this symbol, the range decoder will have read one byte beyond the end of the range coded bytestream. This way the byte position of the end can be determined. Bytestreams written in <tt>Sentinel mode</tt> can be read in <tt>Closed mode</tt> if the length can be determined, in this case the last (sentinel) symbol will be read non-corrupted and be of value 0.</t>
</li>
</ul>
<t>Above describes the range decoding, encoding is defined as any process which produces a decodable bytestream.</t>
<t>There are 3 places where range coder termination is needed in FFV1.
First is in the <tt>Configuration Record</tt>, in this case the size of the range coded bytestream is known and handled as <tt>Closed mode</tt>.
Second is the switch from the <tt>Slice Header</tt> which is range coded to Golomb coded slices as <tt>Sentinel mode</tt>.
Third is the end of range coded Slices which need to terminate before the CRC at their end. This can be handled as <tt>Sentinel mode</tt> or as <tt>Closed mode</tt> if the CRC position has been determined.</t>
</section>
</section>

<section anchor="range-non-binary-values"><name>Range Non Binary Values</name>
<t>To encode scalar integers, it would be possible to encode each bit separately and use the past bits as context. However that would mean 255 contexts per 8-bit symbol that is not only a waste of memory but also requires more past data to reach a reasonably good estimate of the probabilities. Alternatively assuming a Laplacian distribution and only dealing with its variance and mean (as in Huffman coding) would also be possible, however, for maximum flexibility and simplicity, the chosen method uses a single symbol to encode if a number is 0, and if not, encodes the number using its exponent, mantissa and sign. The exact contexts used are best described by the following code, followed by some comments.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
void put_symbol(RangeCoder *c, uint8_t *state, int v, int \   |
is_signed) {                                                  |
    int i;                                                    |
    put_rac(c, state+0, !v);                                  |
    if (v) {                                                  |
        int a= abs(v);                                        |
        int e= log2(a);                                       |
                                                              |
        for (i = 0; i &lt; e; i++) {                             |
            put_rac(c, state+1+min(i,9), 1);  //1..10         |
        }                                                     |
                                                              |
        put_rac(c, state+1+min(i,9), 0);                      |
        for (i = e-1; i &gt;= 0; i--) {                          |
            put_rac(c, state+22+min(i,9), (a&gt;&gt;i)&amp;1); //22..31 |
        }                                                     |
                                                              |
        if (is_signed) {                                      |
            put_rac(c, state+11 + min(e, 10), v &lt; 0); //11..21|
        }                                                     |
    }                                                         |
}                                                             |
</sourcecode>
</section>

<section anchor="initial-values-for-the-context-model"><name>Initial Values for the Context Model</name>
<t>At keyframes all Range coder state variables are set to their initial state.</t>
</section>

<section anchor="state-transition-table"><name>State Transition Table</name>

<artwork>one_state_{i} =
       default_state_transition_{i} + state_transition_delta_{i}
</artwork>

<artwork>zero_state_{i} = 256 - one_state_{256-i}
</artwork>
</section>

<section anchor="default-state-transition"><name>default_state_transition</name>

<artwork>  0,  0,  0,  0,  0,  0,  0,  0, 20, 21, 22, 23, 24, 25, 26, 27,

 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42,

 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57,

 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,

 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,

 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99,100,101,102,103,

104,105,106,107,108,109,110,111,112,113,114,114,115,116,117,118,

119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,133,

134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,

150,151,152,152,153,154,155,156,157,158,159,160,161,162,163,164,

165,166,167,168,169,170,171,171,172,173,174,175,176,177,178,179,

180,181,182,183,184,185,186,187,188,189,190,190,191,192,194,194,

195,196,197,198,199,200,201,202,202,204,205,206,207,208,209,209,

210,211,212,213,215,215,216,217,218,219,220,220,222,223,224,225,

226,227,227,229,229,230,231,232,234,234,235,236,237,238,239,240,

241,242,243,244,245,246,247,248,248,  0,  0,  0,  0,  0,  0,  0,
</artwork>
</section>

<section anchor="alternative-state-transition-table"><name>Alternative State Transition Table</name>
<t>The alternative state transition table has been built using iterative minimization of frame sizes and generally performs better than the default. To use it, the coder_type (see <eref target="#codertype">the section on coder_type</eref>) MUST be set to 2 and the difference to the default MUST be stored in the <tt>Parameters</tt>, see <eref target="#parameters">the section on Parameters</eref>. The reference implementation of FFV1 in FFmpeg uses this table by default at the time of this writing when Range coding is used.</t>

<artwork>  0, 10, 10, 10, 10, 16, 16, 16, 28, 16, 16, 29, 42, 49, 20, 49,

 59, 25, 26, 26, 27, 31, 33, 33, 33, 34, 34, 37, 67, 38, 39, 39,

 40, 40, 41, 79, 43, 44, 45, 45, 48, 48, 64, 50, 51, 52, 88, 52,

 53, 74, 55, 57, 58, 58, 74, 60,101, 61, 62, 84, 66, 66, 68, 69,

 87, 82, 71, 97, 73, 73, 82, 75,111, 77, 94, 78, 87, 81, 83, 97,

 85, 83, 94, 86, 99, 89, 90, 99,111, 92, 93,134, 95, 98,105, 98,

105,110,102,108,102,118,103,106,106,113,109,112,114,112,116,125,

115,116,117,117,126,119,125,121,121,123,145,124,126,131,127,129,

165,130,132,138,133,135,145,136,137,139,146,141,143,142,144,148,

147,155,151,149,151,150,152,157,153,154,156,168,158,162,161,160,

172,163,169,164,166,184,167,170,177,174,171,173,182,176,180,178,

175,189,179,181,186,183,192,185,200,187,191,188,190,197,193,196,

197,194,195,196,198,202,199,201,210,203,207,204,205,206,208,214,

209,211,221,212,213,215,224,216,217,218,219,220,222,228,223,225,

226,224,227,229,240,230,231,232,233,234,235,236,238,239,237,242,

241,243,242,244,245,246,247,248,249,250,251,252,252,253,254,255,
</artwork>
</section>
</section>

<section anchor="golomb-rice-mode"><name>Golomb Rice Mode</name>
<t>The end of the bitstream of the <tt>Frame</tt> is filled with 0-bits until that the bitstream contains a multiple of 8 bits.</t>

<section anchor="signed-golomb-rice-codes"><name>Signed Golomb Rice Codes</name>
<t>This coding mode uses Golomb Rice codes. The VLC is split into 2 parts, the prefix stores the most significant bits and the suffix stores the k least significant bits or stores the whole number in the ESC case.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
int get_ur_golomb(k) {                                        |
    for (prefix = 0; prefix &lt; 12; prefix++) {                 |
        if (get_bits(1)) {                                    |
            return get_bits(k) + (prefix &lt;&lt; k)                |
        }                                                     |
    }                                                         |
    return get_bits(bits) + 11                                |
}                                                             |
                                                              |
int get_sr_golomb(k) {                                        |
    v = get_ur_golomb(k);                                     |
    if (v &amp; 1) return - (v &gt;&gt; 1) - 1;                         |
    else       return   (v &gt;&gt; 1);                             |
}
</sourcecode>

<section anchor="prefix"><name>Prefix</name>
<table>
<thead>
<tr>
<th align="left">bits</th>
<th align="left">value</th>
</tr>
</thead>

<tbody>
<tr>
<td align="left">1</td>
<td align="left">0</td>
</tr>

<tr>
<td align="left">01</td>
<td align="left">1</td>
</tr>

<tr>
<td align="left">...</td>
<td align="left">...</td>
</tr>

<tr>
<td align="left">0000 0000 0001</td>
<td align="left">11</td>
</tr>

<tr>
<td align="left">0000 0000 0000</td>
<td align="left">ESC</td>
</tr>
</tbody>
</table></section>

<section anchor="suffix"><name>Suffix</name>
<table>
<thead>
<tr>
<th align="left"></th>
<th align="left"></th>
</tr>
</thead>

<tbody>
<tr>
<td align="left">non ESC</td>
<td align="left">the k least significant bits MSB first</td>
</tr>

<tr>
<td align="left">ESC</td>
<td align="left">the value - 11, in MSB first order, ESC may only be used if the value cannot be coded as non ESC</td>
</tr>
</tbody>
</table></section>

<section anchor="examples"><name>Examples</name>
<table>
<thead>
<tr>
<th align="center">k</th>
<th align="left">bits</th>
<th align="right">value</th>
</tr>
</thead>

<tbody>
<tr>
<td align="center">0</td>
<td align="left"><tt>1</tt></td>
<td align="right">0</td>
</tr>

<tr>
<td align="center">0</td>
<td align="left"><tt>001</tt></td>
<td align="right">2</td>
</tr>

<tr>
<td align="center">2</td>
<td align="left"><tt>1 00</tt></td>
<td align="right">0</td>
</tr>

<tr>
<td align="center">2</td>
<td align="left"><tt>1 10</tt></td>
<td align="right">2</td>
</tr>

<tr>
<td align="center">2</td>
<td align="left"><tt>01 01</tt></td>
<td align="right">5</td>
</tr>

<tr>
<td align="center">any</td>
<td align="left"><tt>000000000000 10000000</tt></td>
<td align="right">139</td>
</tr>
</tbody>
</table></section>
</section>

<section anchor="run-mode"><name>Run Mode</name>
<t>Run mode is entered when the context is 0 and left as soon as a non-0 difference is found. The level is identical to the predicted one. The run and the first different level are coded.</t>

<section anchor="run-length-coding"><name>Run Length Coding</name>
<t>The run value is encoded in 2 parts, the prefix part stores the more significant part of the run as well as adjusting the run_index that determines the number of bits in the less significant part of the run. The 2nd part of the value stores the less significant part of the run as it is. The run_index is reset for each <tt>Plane</tt> and slice to 0.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
log2_run[41]={                                                |
 0, 0, 0, 0, 1, 1, 1, 1,                                      |
 2, 2, 2, 2, 3, 3, 3, 3,                                      |
 4, 4, 5, 5, 6, 6, 7, 7,                                      |
 8, 9,10,11,12,13,14,15,                                      |
16,17,18,19,20,21,22,23,                                      |
24,                                                           |
};                                                            |
                                                              |
if (run_count == 0 &amp;&amp; run_mode == 1) {                        |
    if (get_bits(1)) {                                        |
        run_count = 1 &lt;&lt; log2_run[run_index];                 |
        if (x + run_count &lt;= w) {                             |
            run_index++;                                      |
        }                                                     |
    } else {                                                  |
        if (log2_run[run_index]) {                            |
            run_count = get_bits(log2_run[run_index]);        |
        } else {                                              |
            run_count = 0;                                    |
        }                                                     |
        if (run_index) {                                      |
            run_index--;                                      |
        }                                                     |
        run_mode = 2;                                         |
    }                                                         |
}                                                             |
</sourcecode>
<t>The log2_run function is also used within <xref target="ISO.14495-1.1999"></xref>.</t>
</section>

<section anchor="level-coding"><name>Level Coding</name>
<t>Level coding is identical to the normal difference coding with the exception that the 0 value is removed as it cannot occur:</t>

<sourcecode type="c">    diff = get_vlc_symbol(context_state);
    if (diff &gt;= 0) {
        diff++;
    }
</sourcecode>
<t>Note, this is different from JPEG-LS, which doesn’t use prediction in run mode and uses a different encoding and context model for the last difference On a small set of test <tt>Samples</tt> the use of prediction slightly improved the compression rate.</t>
</section>
</section>

<section anchor="scalar-mode"><name>Scalar Mode</name>
<t>Each difference is coded with the per context mean prediction removed and a per context value for k.</t>

<sourcecode type="c">get_vlc_symbol(state) {
    i = state-&gt;count;
    k = 0;
    while (i &lt; state-&gt;error_sum) {
        k++;
        i += i;
    }

    v = get_sr_golomb(k);

    if (2 * state-&gt;drift &lt; -state-&gt;count) {
        v = -1 - v;
    }

    ret = sign_extend(v + state-&gt;bias, bits);

    state-&gt;error_sum += abs(v);
    state-&gt;drift     += v;

    if (state-&gt;count == 128) {
        state-&gt;count     &gt;&gt;= 1;
        state-&gt;drift     &gt;&gt;= 1;
        state-&gt;error_sum &gt;&gt;= 1;
    }
    state-&gt;count++;
    if (state-&gt;drift &lt;= -state-&gt;count) {
        state-&gt;bias = max(state-&gt;bias - 1, -128);

        state-&gt;drift = max(state-&gt;drift + state-&gt;count,
                           -state-&gt;count + 1);
    } else if (state-&gt;drift &gt; 0) {
        state-&gt;bias = min(state-&gt;bias + 1, 127);

        state-&gt;drift = min(state-&gt;drift - state-&gt;count, 0);
    }

    return ret;
}
</sourcecode>
</section>

<section anchor="initial-values-for-the-vlc-context-state"><name>Initial Values for the VLC context state</name>
<t>At keyframes all coder state variables are set to their initial state.</t>

<sourcecode type="c">    drift     = 0;
    error_sum = 4;
    bias      = 0;
    count     = 1;
</sourcecode>
</section>
</section>
</section>
</section>

<section anchor="bitstream"><name>Bitstream</name>
<t>An FFV1 bitstream is composed of a series of 1 or more <tt>Frames</tt> and (when required) a <tt>Configuration Record</tt>.</t>
<t>Within the following sub-sections, pseudo-code is used to explain the structure of each FFV1 bitstream component, as described in <eref target="#pseudocode">the section on Pseudo-Code</eref>. The following table lists symbols used to annotate that pseudo-code in order to define the storage of the data referenced in that line of pseudo-code.</t>
<table>
<thead>
<tr>
<th>Symbol</th>
<th>Definition</th>
</tr>
</thead>

<tbody>
<tr>
<td>u(n)</td>
<td>unsigned big endian integer using n bits</td>
</tr>

<tr>
<td>sg</td>
<td>Golomb Rice coded signed scalar symbol coded with the method described in <eref target="#golomb-rice-mode">Signed Golomb Rice Codes</eref></td>
</tr>

<tr>
<td>br</td>
<td>Range coded Boolean (1-bit) symbol with the method described in <eref target="#range-binary-values">Range binary values</eref></td>
</tr>

<tr>
<td>ur</td>
<td>Range coded unsigned scalar symbol coded with the method described in <eref target="#range-non-binary-values">Range non binary values</eref></td>
</tr>

<tr>
<td>sr</td>
<td>Range coded signed scalar symbol coded with the method described in <eref target="#range-non-binary-values">Range non binary values</eref></td>
</tr>
</tbody>
</table><t>The same context that is initialized to 128 is used for all fields in the header.</t>
<t>The following MUST be provided by external means during initialization of the decoder:</t>
<t><tt>frame_pixel_width</tt> is defined as <tt>Frame</tt> width in <tt>Pixels</tt>.</t>
<t><tt>frame_pixel_height</tt> is defined as <tt>Frame</tt> height in <tt>Pixels</tt>.</t>
<t>Default values at the decoder initialization phase:</t>
<t><tt>ConfigurationRecordIsPresent</tt> is set to 0.</t>

<section anchor="parameters"><name>Parameters</name>
<t>The <tt>Parameters</tt> section contains significant characteristics about the decoding configuration used for all instances of <tt>Frame</tt> (in FFV1 version 0 and 1) or the whole FFV1 bitstream (other versions), including the stream version, color configuration, and quantization tables. The pseudo-code below describes the contents of the bitstream.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
Parameters( ) {                                               |
    version                                                   | ur
    if (version &gt;= 3) {                                       |
        micro_version                                         | ur
    }                                                         |
    coder_type                                                | ur
    if (coder_type &gt; 1) {                                     |
        for (i = 1; i &lt; 256; i++) {                           |
            state_transition_delta[ i ]                       | sr
        }                                                     |
    }                                                         |
    colorspace_type                                           | ur
    if (version &gt;= 1) {                                       |
        bits_per_raw_sample                                   | ur
    }                                                         |
    chroma_planes                                             | br
    log2_h_chroma_subsample                                   | ur
    log2_v_chroma_subsample                                   | ur
    extra_plane                                               | br
    if (version &gt;= 3) {                                       |
        num_h_slices - 1                                      | ur
        num_v_slices - 1                                      | ur
        quant_table_set_count                                 | ur
    }                                                         |
    for (i = 0; i &lt; quant_table_set_count; i++) {             |
        QuantizationTableSet( i )                             |
    }                                                         |
    if (version &gt;= 3) {                                       |
        for (i = 0; i &lt; quant_table_set_count; i++) {         |
            states_coded                                      | br
            if (states_coded) {                               |
                for (j = 0; j &lt; context_count[ i ]; j++) {    |
                    for (k = 0; k &lt; CONTEXT_SIZE; k++) {      |
                        initial_state_delta[ i ][ j ][ k ]    | sr
                    }                                         |
                }                                             |
            }                                                 |
        }                                                     |
        ec                                                    | ur
        intra                                                 | ur
    }                                                         |
}                                                             |
</sourcecode>

<section anchor="version"><name>version</name>
<t><tt>version</tt> specifies the version of the FFV1 bitstream.</t>
<t>Each version is incompatible with other versions: decoders SHOULD reject a file due to an unknown version.</t>
<t>Decoders SHOULD reject a file with version &lt;= 1 &amp;&amp; ConfigurationRecordIsPresent == 1.</t>
<t>Decoders SHOULD reject a file with version &gt;= 3 &amp;&amp; ConfigurationRecordIsPresent == 0.</t>
<table>
<thead>
<tr>
<th align="left">value</th>
<th align="left">version</th>
</tr>
</thead>

<tbody>
<tr>
<td align="left">0</td>
<td align="left">FFV1 version 0</td>
</tr>

<tr>
<td align="left">1</td>
<td align="left">FFV1 version 1</td>
</tr>

<tr>
<td align="left">2</td>
<td align="left">reserved*</td>
</tr>

<tr>
<td align="left">3</td>
<td align="left">FFV1 version 3</td>
</tr>

<tr>
<td align="left">4</td>
<td align="left">FFV1 version 4</td>
</tr>

<tr>
<td align="left">Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table><t>* Version 2 was never enabled in the encoder thus version 2 files SHOULD NOT exist, and this document does not describe them to keep the text simpler.</t>
</section>

<section anchor="micro-version"><name>micro_version</name>
<t><tt>micro_version</tt> specifies the micro-version of the FFV1 bitstream.</t>
<t>After a version is considered stable (a micro-version value is assigned to be the first stable variant of a specific version), each new micro-version after this first stable variant is compatible with the previous micro-version: decoders SHOULD NOT reject a file due to an unknown micro-version equal or above the micro-version considered as stable.</t>
<t>Meaning of micro_version for version 3:</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">micro_version</th>
</tr>
</thead>

<tbody>
<tr>
<td>0...3</td>
<td align="left">reserved*</td>
</tr>

<tr>
<td>4</td>
<td align="left">first stable variant</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table><t>* development versions may be incompatible with the stable variants.</t>
<t>Meaning of micro_version for version 4 (note: at the time of writing of this specification, version 4 is not considered stable so the first stable version value is to be announced in the future):</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">micro_version</th>
</tr>
</thead>

<tbody>
<tr>
<td>0...TBA</td>
<td align="left">reserved*</td>
</tr>

<tr>
<td>TBA</td>
<td align="left">first stable variant</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table><t>* development versions which may be incompatible with the stable variants.</t>
</section>

<section anchor="coder-type"><name>coder_type</name>
<t><tt>coder_type</tt> specifies the coder used.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">coder used</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">Golomb Rice</td>
</tr>

<tr>
<td>1</td>
<td align="left">Range Coder with default state transition table</td>
</tr>

<tr>
<td>2</td>
<td align="left">Range Coder with custom state transition table</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table></section>

<section anchor="state-transition-delta"><name>state_transition_delta</name>
<t><tt>state_transition_delta</tt> specifies the Range coder custom state transition table.</t>
<t>If state<em>transition</em>delta is not present in the FFV1 bitstream, all Range coder custom state transition table elements are assumed to be 0.</t>
</section>

<section anchor="colorspace-type"><name>colorspace_type</name>
<t><tt>colorspace_type</tt> specifies the color space encoded, the pixel transformation used by the encoder, the extra plane content, as well as interleave method.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">color space encoded</th>
<th align="left">pixel transformation</th>
<th align="left">extra plane content</th>
<th align="left">interleave method</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">YCbCr</td>
<td align="left">None</td>
<td align="left">Transparency</td>
<td align="left"><tt>Plane</tt> then <tt>Line</tt></td>
</tr>

<tr>
<td>1</td>
<td align="left">RGB</td>
<td align="left">JPEG2000-RCT</td>
<td align="left">Transparency</td>
<td align="left"><tt>Line</tt> then <tt>Plane</tt></td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
<td align="left">reserved for future use</td>
<td align="left">reserved for future use</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table><t>Restrictions:</t>
<t>If <tt>colorspace_type</tt> is 1, then <tt>chroma_planes</tt> MUST be 1, <tt>log2_h_chroma_subsample</tt> MUST be 0, and <tt>log2_v_chroma_subsample</tt> MUST be 0.</t>
</section>

<section anchor="chroma-planes"><name>chroma_planes</name>
<t><tt>chroma_planes</tt> indicates if chroma (color) <tt>Planes</tt> are present.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">presence</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">chroma <tt>Planes</tt> are not present</td>
</tr>

<tr>
<td>1</td>
<td align="left">chroma <tt>Planes</tt> are present</td>
</tr>
</tbody>
</table></section>

<section anchor="bits-per-raw-sample"><name>bits_per_raw_sample</name>
<t><tt>bits_per_raw_sample</tt> indicates the number of bits for each <tt>Sample</tt>. Inferred to be 8 if not present.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">bits for each sample</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">reserved*</td>
</tr>

<tr>
<td>Other</td>
<td align="left">the actual bits for each <tt>Sample</tt></td>
</tr>
</tbody>
</table><t>* Encoders MUST NOT store bits<em>per</em>raw<em>sample = 0
Decoders SHOULD accept and interpret bits</em>per<em>raw</em>sample = 0 as 8.</t>
</section>

<section anchor="log2-h-chroma-subsample"><name>log2_h_chroma_subsample</name>
<t><tt>log2_h_chroma_subsample</tt> indicates the subsample factor, stored in powers to which the number 2 must be raised, between luma and chroma width (<tt>chroma_width = 2^(-log2_h_chroma_subsample) * luma_width</tt>).</t>
</section>

<section anchor="log2-v-chroma-subsample"><name>log2_v_chroma_subsample</name>
<t><tt>log2_v_chroma_subsample</tt> indicates the subsample factor, stored in powers to which the number 2 must be raised, between luma and chroma height (<tt>chroma_height=2^(-log2_v_chroma_subsample) * luma_height</tt>).</t>
</section>

<section anchor="extra-plane"><name>extra_plane</name>
<t><tt>extra_plane</tt> indicates if an extra <tt>Plane</tt> is present.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">presence</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">extra <tt>Plane</tt> is not present</td>
</tr>

<tr>
<td>1</td>
<td align="left">extra <tt>Plane</tt> is present</td>
</tr>
</tbody>
</table></section>

<section anchor="num-h-slices"><name>num_h_slices</name>
<t><tt>num_h_slices</tt> indicates the number of horizontal elements of the slice raster.</t>
<t>Inferred to be 1 if not present.</t>
</section>

<section anchor="num-v-slices"><name>num_v_slices</name>
<t><tt>num_v_slices</tt> indicates the number of vertical elements of the slice raster.</t>
<t>Inferred to be 1 if not present.</t>
</section>

<section anchor="quant-table-set-count"><name>quant_table_set_count</name>
<t><tt>quant_table_set_count</tt> indicates the number of Quantization Table Sets.</t>
<t>Inferred to be 1 if not present.</t>
<t>MUST NOT be 0.</t>
</section>

<section anchor="states-coded"><name>states_coded</name>
<t><tt>states_coded</tt> indicates if the respective Quantization Table Set has the initial states coded.</t>
<t>Inferred to be 0 if not present.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">initial states</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">initial states are not present and are assumed to be all 128</td>
</tr>

<tr>
<td>1</td>
<td align="left">initial states are present</td>
</tr>
</tbody>
</table></section>

<section anchor="initial-state-delta"><name>initial_state_delta</name>
<t><tt>initial_state_delta[ i ][ j ][ k ]</tt> indicates the initial Range coder state, it is encoded using <tt>k</tt> as context index and</t>

<artwork>pred = j ? initial_states[ i ][j - 1][ k ] : 128
</artwork>

<artwork>initial_state[ i ][ j ][ k ] =
       ( pred + initial_state_delta[ i ][ j ][ k ] ) &amp; 255
</artwork>
</section>

<section anchor="ec"><name>ec</name>
<t><tt>ec</tt> indicates the error detection/correction type.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">error detection/correction type</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">32-bit CRC on the global header</td>
</tr>

<tr>
<td>1</td>
<td align="left">32-bit CRC per slice and the global header</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table></section>

<section anchor="intra"><name>intra</name>
<t><tt>intra</tt> indicates the relationship between the instances of <tt>Frame</tt>.</t>
<t>Inferred to be 0 if not present.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">relationship</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">Frames are independent or dependent (keyframes and non keyframes)</td>
</tr>

<tr>
<td>1</td>
<td align="left">Frames are independent (keyframes only)</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table></section>
</section>

<section anchor="configuration-record"><name>Configuration Record</name>
<t>In the case of a FFV1 bitstream with <tt>version &gt;= 3</tt>, a <tt>Configuration Record</tt> is stored in the underlying <tt>Container</tt>, at the track header level. It contains the <tt>Parameters</tt> used for all instances of <tt>Frame</tt>. The size of the <tt>Configuration Record</tt>, <tt>NumBytes</tt>, is supplied by the underlying <tt>Container</tt>.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
ConfigurationRecord( NumBytes ) {                             |
    ConfigurationRecordIsPresent = 1                          |
    Parameters( )                                             |
    while (remaining_symbols_in_syntax(NumBytes - 4)) {       |
        reserved_for_future_use                               | br/ur/sr
    }                                                         |
    configuration_record_crc_parity                           | u(32)
}                                                             |
</sourcecode>

<section anchor="reserved-for-future-use"><name>reserved_for_future_use</name>
<t><tt>reserved_for_future_use</tt> has semantics that are reserved for future use.</t>
<t>Encoders conforming to this version of this specification SHALL NOT write this value.</t>
<t>Decoders conforming to this version of this specification SHALL ignore its value.</t>
</section>

<section anchor="configuration-record-crc-parity"><name>configuration_record_crc_parity</name>
<t><tt>configuration_record_crc_parity</tt> 32 bits that are chosen so that the <tt>Configuration Record</tt> as a whole has a crc remainder of 0.</t>
<t>This is equivalent to storing the crc remainder in the 32-bit parity.</t>
<t>The CRC generator polynomial used is the standard IEEE CRC polynomial (0x104C11DB7) with initial value 0.</t>
</section>

<section anchor="mapping-ffv1-into-containers"><name>Mapping FFV1 into Containers</name>
<t>This <tt>Configuration Record</tt> can be placed in any file format supporting <tt>Configuration Records</tt>, fitting as much as possible with how the file format uses to store <tt>Configuration Records</tt>. The <tt>Configuration Record</tt> storage place and <tt>NumBytes</tt> are currently defined and supported by this version of this specification for the following formats:</t>

<section anchor="avi-file-format"><name>AVI File Format</name>
<t>The <tt>Configuration Record</tt> extends the stream format chunk (&quot;AVI &quot;, &quot;hdlr&quot;, &quot;strl&quot;, &quot;strf&quot;) with the ConfigurationRecord bitstream.</t>
<t>See <xref target="AVI"></xref> for more information about chunks.</t>
<t><tt>NumBytes</tt> is defined as the size, in bytes, of the strf chunk indicated in the chunk header minus the size of the stream format structure.</t>
</section>

<section anchor="iso-base-media-file-format"><name>ISO Base Media File Format</name>
<t>The <tt>Configuration Record</tt> extends the sample description box (&quot;moov&quot;, &quot;trak&quot;, &quot;mdia&quot;, &quot;minf&quot;, &quot;stbl&quot;, &quot;stsd&quot;) with a &quot;glbl&quot; box that contains the ConfigurationRecord bitstream. See <xref target="ISO.14496-12.2015"></xref> for more information about boxes.</t>
<t><tt>NumBytes</tt> is defined as the size, in bytes, of the &quot;glbl&quot; box indicated in the box header minus the size of the box header.</t>
</section>

<section anchor="nut-file-format"><name>NUT File Format</name>
<t>The codec_specific_data element (in &quot;stream_header&quot; packet) contains the ConfigurationRecord bitstream. See <xref target="NUT"></xref> for more information about elements.</t>
<t><tt>NumBytes</tt> is defined as the size, in bytes, of the codec_specific_data element as indicated in the &quot;length&quot; field of codec_specific_data</t>
</section>

<section anchor="matroska-file-format"><name>Matroska File Format</name>
<t>FFV1 SHOULD use <tt>V_FFV1</tt> as the Matroska <tt>Codec ID</tt>. For FFV1 versions 2 or less, the Matroska <tt>CodecPrivate</tt> Element SHOULD NOT be used. For FFV1 versions 3 or greater, the Matroska <tt>CodecPrivate</tt> Element MUST contain the FFV1 <tt>Configuration Record</tt> structure and no other data. See <xref target="Matroska"></xref> for more information about elements.</t>
<t><tt>NumBytes</tt> is defined as the <tt>Element Data Size</tt> of the <tt>CodecPrivate</tt> Element.</t>
</section>
</section>
</section>

<section anchor="frame"><name>Frame</name>
<t>A <tt>Frame</tt> is an encoded representation of a complete static image. The whole <tt>Frame</tt> is provided by the underlaying container.</t>
<t>A <tt>Frame</tt> consists of the keyframe field, <tt>Parameters</tt> (if version &lt;=1), and a sequence of independent slices. The pseudo-code below describes the contents of a <tt>Frame</tt>.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
Frame( NumBytes ) {                                           |
    keyframe                                                  | br
    if (keyframe &amp;&amp; !ConfigurationRecordIsPresent {           |
        Parameters( )                                         |
    }                                                         |
    while (remaining_bits_in_bitstream( NumBytes )) {         |
        Slice( )                                              |
    }                                                         |
}                                                             |
</sourcecode>
<t>Architecture overview of slices in a <tt>Frame</tt>:</t>
<table>
<thead>
<tr>
<th align="left"></th>
</tr>
</thead>

<tbody>
<tr>
<td align="left">first slice header</td>
</tr>

<tr>
<td align="left">first slice content</td>
</tr>

<tr>
<td align="left">first slice footer</td>
</tr>

<tr>
<td align="left">---------------------------------------------------------------</td>
</tr>

<tr>
<td align="left">second slice header</td>
</tr>

<tr>
<td align="left">second slice content</td>
</tr>

<tr>
<td align="left">second slice footer</td>
</tr>

<tr>
<td align="left">---------------------------------------------------------------</td>
</tr>

<tr>
<td align="left">...</td>
</tr>

<tr>
<td align="left">---------------------------------------------------------------</td>
</tr>

<tr>
<td align="left">last slice header</td>
</tr>

<tr>
<td align="left">last slice content</td>
</tr>

<tr>
<td align="left">last slice footer</td>
</tr>
</tbody>
</table></section>

<section anchor="slice"><name>Slice</name>
<t>A <tt>Slice</tt> is an independent spatial sub-section of a <tt>Frame</tt> that is encoded separately from an other region of the same <tt>Frame</tt>. The use of more than one <tt>Slice</tt> per <tt>Frame</tt> can be useful for taking advantage of the opportunities of multithreaded encoding and decoding.</t>
<t>A <tt>Slice</tt> consists of a <tt>Slice Header</tt> (when relevant), a <tt>Slice Content</tt>, and a <tt>Slice Footer</tt> (when relevant). The pseudo-code below describes the contents of a <tt>Slice</tt>.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
Slice( ) {                                                    |
    if (version &gt;= 3) {                                       |
        SliceHeader( )                                        |
    }                                                         |
    SliceContent( )                                           |
    if (coder_type == 0) {                                    |
        while (!byte_aligned()) {                             |
            padding                                           | u(1)
        }                                                     |
    }                                                         |
    if (version &lt;= 1) {                                       |
        while (remaining_bits_in_bitstream( NumBytes ) != 0) {|
            reserved                                          | u(1)
        }                                                     |
    }                                                         |
    if (version &gt;= 3) {                                       |
        SliceFooter( )                                        |
    }                                                         |
}                                                             |
</sourcecode>
<t><tt>padding</tt> specifies a bit without any significance and used only for byte alignment.
MUST be 0.</t>
<t><tt>reserved</tt> specifies a bit without any significance in this revision of the specification and may have a significance in a later revision of this specification.</t>
<t>Encoders SHOULD NOT fill these bits.</t>
<t>Decoders SHOULD ignore these bits.</t>
<t>Note in case these bits are used in a later revision of this specification: any revision of this specification SHOULD care about avoiding to add 40 bits of content after <tt>SliceContent</tt> for version 0 and 1 of the bitstream. Background: due to some non conforming encoders, some bitstreams where found with 40 extra bits corresponding to <tt>error_status</tt> and <tt>slice_crc_parity</tt>, a decoder conforming to the revised specification could not do the difference between a revised bitstream and a buggy bitstream.</t>
</section>

<section anchor="slice-header"><name>Slice Header</name>
<t>A <tt>Slice Header</tt> provides information about the decoding configuration of the <tt>Slice</tt>, such as its spatial position, size, and aspect ratio. The pseudo-code below describes the contents of the <tt>Slice Header</tt>.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
SliceHeader( ) {                                              |
    slice_x                                                   | ur
    slice_y                                                   | ur
    slice_width - 1                                           | ur
    slice_height - 1                                          | ur
    for (i = 0; i &lt; quant_table_set_index_count; i++) {       |
        quant_table_set_index[ i ]                            | ur
    }                                                         |
    picture_structure                                         | ur
    sar_num                                                   | ur
    sar_den                                                   | ur
    if (version &gt;= 4) {                                       |   
        reset_contexts                                        | br
        slice_coding_mode                                     | ur
    }                                                         |   
}                                                             |
</sourcecode>

<section anchor="slice-x"><name>slice_x</name>
<t><tt>slice_x</tt> indicates the x position on the slice raster formed by num<em>h</em>slices.</t>
<t>Inferred to be 0 if not present.</t>
</section>

<section anchor="slice-y"><name>slice_y</name>
<t><tt>slice_y</tt> indicates the y position on the slice raster formed by num<em>v</em>slices.</t>
<t>Inferred to be 0 if not present.</t>
</section>

<section anchor="slice-width"><name>slice_width</name>
<t><tt>slice_width</tt> indicates the width on the slice raster formed by num<em>h</em>slices.</t>
<t>Inferred to be 1 if not present.</t>
</section>

<section anchor="slice-height"><name>slice_height</name>
<t><tt>slice_height</tt> indicates the height on the slice raster formed by num<em>v</em>slices.</t>
<t>Inferred to be 1 if not present.</t>
</section>

<section anchor="quant-table-set-index-count"><name>quant_table_set_index_count</name>
<t><tt>quant_table_set_index_count</tt> is defined as <tt>1 + ( ( chroma_planes || version &lt;= 3 ) ? 1 : 0 ) + ( extra_plane ? 1 : 0 )</tt>.</t>
</section>

<section anchor="quant-table-set-index"><name>quant_table_set_index</name>
<t><tt>quant_table_set_index</tt> indicates the Quantization Table Set index to select the Quantization Table Set and the initial states for the slice.</t>
<t>Inferred to be 0 if not present.</t>
</section>

<section anchor="picture-structure"><name>picture_structure</name>
<t><tt>picture_structure</tt> specifies the temporal and spatial relationship of each <tt>Line</tt> of the <tt>Frame</tt>.</t>
<t>Inferred to be 0 if not present.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">picture structure used</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">unknown</td>
</tr>

<tr>
<td>1</td>
<td align="left">top field first</td>
</tr>

<tr>
<td>2</td>
<td align="left">bottom field first</td>
</tr>

<tr>
<td>3</td>
<td align="left">progressive</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table></section>

<section anchor="sar-num"><name>sar_num</name>
<t><tt>sar_num</tt> specifies the <tt>Sample</tt> aspect ratio numerator.</t>
<t>Inferred to be 0 if not present.</t>
<t>A value of 0 means that aspect ratio is unknown.</t>
<t>Encoders MUST write 0 if <tt>Sample</tt> aspect ratio is unknown.</t>
<t>If <tt>sar_den</tt> is 0, decoders SHOULD ignore the encoded value and consider that <tt>sar_num</tt> is 0.</t>
</section>

<section anchor="sar-den"><name>sar_den</name>
<t><tt>sar_den</tt> specifies the <tt>Sample</tt> aspect ratio denominator.</t>
<t>Inferred to be 0 if not present.</t>
<t>A value of 0 means that aspect ratio is unknown.</t>
<t>Encoders MUST write 0 if <tt>Sample</tt> aspect ratio is unknown.</t>
<t>If <tt>sar_num</tt> is 0, decoders SHOULD ignore the encoded value and consider that <tt>sar_den</tt> is 0.</t>
</section>

<section anchor="reset-contexts"><name>reset_contexts</name>
<t><tt>reset_contexts</tt> indicates if slice contexts must be reset.</t>
<t>Inferred to be 0 if not present.</t>
</section>

<section anchor="slice-coding-mode"><name>slice_coding_mode</name>
<t><tt>slice_coding_mode</tt> indicates the slice coding mode.</t>
<t>Inferred to be 0 if not present.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">slice coding mode</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">Range Coding or Golomb Rice</td>
</tr>

<tr>
<td>1</td>
<td align="left">raw PCM</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table></section>
</section>

<section anchor="slice-content"><name>Slice Content</name>
<t>A <tt>Slice Content</tt> contains all <tt>Line</tt> elements part of the <tt>Slice</tt>.</t>
<t>Depending on the configuration, <tt>Line</tt> elements are ordered by <tt>Plane</tt> then by row (YCbCr) or by row then by <tt>Plane</tt> (RGB).</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
SliceContent( ) {                                             |
    if (colorspace_type == 0) {                               |
        for (p = 0; p &lt; primary_color_count; p++) {           |
            for (y = 0; y &lt; plane_pixel_height[ p ]; y++) {   |
                Line( p, y )                                  |
            }                                                 |
        }                                                     |
    } else if (colorspace_type == 1) {                        |
        for (y = 0; y &lt; slice_pixel_height; y++) {            |
            for (p = 0; p &lt; primary_color_count; p++) {       |
                Line( p, y )                                  |
            }                                                 |
        }                                                     |
    }                                                         |
}                                                             |
</sourcecode>

<section anchor="primary-color-count"><name>primary_color_count</name>
<t><tt>primary_color_count</tt> is defined as <tt>1 + ( chroma_planes ? 2 : 0 ) + ( extra_plane ? 1 : 0 )</tt>.</t>
</section>

<section anchor="plane-pixel-height"><name>plane_pixel_height</name>
<t><tt>plane_pixel_height[ p ]</tt> is the height in pixels of plane p of the slice.</t>
<t><tt>plane_pixel_height[ 0 ]</tt> and <tt>plane_pixel_height[ 1 + ( chroma_planes ? 2 : 0 ) ]</tt> value is <tt>slice_pixel_height</tt>.</t>
<t>If <tt>chroma_planes</tt> is set to 1, <tt>plane_pixel_height[ 1 ]</tt> and <tt>plane_pixel_height[ 2 ]</tt> value is <tt>ceil(slice_pixel_height / log2_v_chroma_subsample)</tt>.</t>
</section>

<section anchor="slice-pixel-height"><name>slice_pixel_height</name>
<t><tt>slice_pixel_height</tt> is the height in pixels of the slice.</t>
<t>Its value is <tt>floor(( slice_y + slice_height ) * slice_pixel_height / num_v_slices) - slice_pixel_y</tt>.</t>
</section>

<section anchor="slice-pixel-y"><name>slice_pixel_y</name>
<t><tt>slice_pixel_y</tt> is the slice vertical position in pixels.</t>
<t>Its value is <tt>floor(slice_y * frame_pixel_height / num_v_slices)</tt>.</t>
</section>
</section>

<section anchor="line"><name>Line</name>
<t>A <tt>Line</tt> is a list of the sample differences (relative to the predictor) of primary color components. The pseudo-code below describes the contents of the <tt>Line</tt>.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
Line( p, y ) {                                                |
    if (colorspace_type == 0) {                               |
        for (x = 0; x &lt; plane_pixel_width[ p ]; x++) {        |
            sample_difference[ p ][ y ][ x ]                  |
        }                                                     |
    } else if (colorspace_type == 1) {                        |
        for (x = 0; x &lt; slice_pixel_width; x++) {             |
            sample_difference[ p ][ y ][ x ]                  |
        }                                                     |
    }                                                         |
}                                                             |
</sourcecode>

<section anchor="plane-pixel-width"><name>plane_pixel_width</name>
<t><tt>plane_pixel_width[ p ]</tt> is the width in <tt>Pixels</tt> of <tt>Plane</tt> p of the slice.</t>
<t><tt>plane_pixel_width[ 0 ]</tt> and <tt>plane_pixel_width[ 1 + ( chroma_planes ? 2 : 0 ) ]</tt> value is <tt>slice_pixel_width</tt>.</t>
<t>If <tt>chroma_planes</tt> is set to 1, <tt>plane_pixel_width[ 1 ]</tt> and <tt>plane_pixel_width[ 2 ]</tt> value is <tt>ceil(slice_pixel_width / (1 &lt;&lt; log2_h_chroma_subsample))</tt>.</t>
</section>

<section anchor="slice-pixel-width"><name>slice_pixel_width</name>
<t><tt>slice_pixel_width</tt> is the width in <tt>Pixels</tt> of the slice.</t>
<t>Its value is <tt>floor(( slice_x + slice_width ) * slice_pixel_width / num_h_slices) - slice_pixel_x</tt>.</t>
</section>

<section anchor="slice-pixel-x"><name>slice_pixel_x</name>
<t><tt>slice_pixel_x</tt> is the slice horizontal position in <tt>Pixels</tt>.</t>
<t>Its value is <tt>floor(slice_x * frame_pixel_width / num_h_slices)</tt>.</t>
</section>

<section anchor="sample-difference"><name>sample_difference</name>
<t><tt>sample_difference[ p ][ y ][ x ]</tt> is the sample difference for <tt>Sample</tt> at <tt>Plane</tt> <tt>p</tt>, y position <tt>y</tt>, and x position <tt>x</tt>. The <tt>Sample</tt> value is computed based on median predictor and context described in <eref target="#samples">the section on Samples</eref>.</t>
</section>
</section>

<section anchor="slice-footer"><name>Slice Footer</name>
<t>A <tt>Slice Footer</tt> provides information about slice size and (optionally) parity. The pseudo-code below describes the contents of the <tt>Slice Footer</tt>.</t>
<t>Note: <tt>Slice Footer</tt> is always byte aligned.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
SliceFooter( ) {                                              |
    slice_size                                                | u(24)
    if (ec) {                                                 |
        error_status                                          | u(8)
        slice_crc_parity                                      | u(32)
    }                                                         |
}                                                             |
</sourcecode>

<section anchor="slice-size"><name>slice_size</name>
<t><tt>slice_size</tt> indicates the size of the slice in bytes.</t>
<t>Note: this allows finding the start of slices before previous slices have been fully decoded, and allows parallel decoding as well as error resilience.</t>
</section>

<section anchor="error-status"><name>error_status</name>
<t><tt>error_status</tt> specifies the error status.</t>
<table>
<thead>
<tr>
<th>value</th>
<th align="left">error status</th>
</tr>
</thead>

<tbody>
<tr>
<td>0</td>
<td align="left">no error</td>
</tr>

<tr>
<td>1</td>
<td align="left">slice contains a correctable error</td>
</tr>

<tr>
<td>2</td>
<td align="left">slice contains a uncorrectable error</td>
</tr>

<tr>
<td>Other</td>
<td align="left">reserved for future use</td>
</tr>
</tbody>
</table></section>

<section anchor="slice-crc-parity"><name>slice_crc_parity</name>
<t><tt>slice_crc_parity</tt> 32 bits that are chosen so that the slice as a whole has a crc remainder of 0.</t>
<t>This is equivalent to storing the crc remainder in the 32-bit parity.</t>
<t>The CRC generator polynomial used is the standard IEEE CRC polynomial (0x104C11DB7) with initial value 0.</t>
</section>
</section>

<section anchor="quantization-table-set"><name>Quantization Table Set</name>
<t>The Quantization Table Sets are stored by storing the number of equal entries -1 of the first half of the table (represented as <tt>len - 1</tt> in the pseudo-code below) using the method described in <eref target="#range-non-binary-values">Range Non Binary Values</eref>. The second half doesn’t need to be stored as it is identical to the first with flipped sign. <tt>scale</tt> and <tt>len_count[ i ][ j ]</tt> are temporary values used for the computing of <tt>context_count[ i ]</tt> and are not used outside Quantization Table Set pseudo-code.</t>
<t>Example:</t>
<t>Table: 0 0 1 1 1 1 2 2 -2 -2 -2 -1 -1 -1 -1 0</t>
<t>Stored values: 1, 3, 1</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
QuantizationTableSet( i ) {                                   |
    scale = 1                                                 |
    for (j = 0; j &lt; MAX_CONTEXT_INPUTS; j++) {                |
        QuantizationTable( i, j, scale )                      |
        scale *= 2 * len_count[ i ][ j ] - 1                  |
    }                                                         |
    context_count[ i ] = ceil( scale / 2 )                    |
}                                                             |
</sourcecode>
<t>MAX_CONTEXT_INPUTS is 5.</t>

<sourcecode type="c">pseudo-code                                                   | type
--------------------------------------------------------------|-----
QuantizationTable(i, j, scale) {                              |
    v = 0                                                     |
    for (k = 0; k &lt; 128;) {                                   |
        len - 1                                               | ur
        for (a = 0; a &lt; len; a++) {                           |
            quant_tables[ i ][ j ][ k ] = scale * v           |
            k++                                               |
        }                                                     |
        v++                                                   |
    }                                                         |
    for (k = 1; k &lt; 128; k++) {                               |
        quant_tables[ i ][ j ][ 256 - k ] = \                 |
        -quant_tables[ i ][ j ][ k ]                          |
    }                                                         |
    quant_tables[ i ][ j ][ 128 ] = \                         |
    -quant_tables[ i ][ j ][ 127 ]                            |
    len_count[ i ][ j ] = v                                   |
}                                                             |
</sourcecode>

<section anchor="quant-tables"><name>quant_tables</name>
<t><tt>quant_tables[ i ][ j ][ k ]</tt> indicates the quantification table value of the Quantized Sample Difference <tt>k</tt> of the Quantization Table <tt>j</tt> of the Set Quantization Table Set <tt>i</tt>.</t>
</section>

<section anchor="context-count"><name>context_count</name>
<t><tt>context_count[ i ]</tt> indicates the count of contexts for Quantization Table Set <tt>i</tt>.</t>
</section>
</section>
</section>

<section anchor="restrictions"><name>Restrictions</name>
<t>To ensure that fast multithreaded decoding is possible, starting with version 3 and if <tt>frame_pixel_width * frame_pixel_height</tt> is more than 101376, <tt>slice_width * slice_height</tt> MUST be less or equal to <tt>num_h_slices * num_v_slices / 4</tt>.
Note: 101376 is the frame size in <tt>Pixels</tt> of a 352x288 frame also known as CIF (&quot;Common Intermediate Format&quot;) frame size format.</t>
<t>For each <tt>Frame</tt>, each position in the slice raster MUST be filled by one and only one slice of the <tt>Frame</tt> (no missing slice position, no slice overlapping).</t>
<t>For each <tt>Frame</tt> with keyframe value of 0, each slice MUST have the same value of <tt>slice_x, slice_y, slice_width, slice_height</tt> as a slice in the previous <tt>Frame</tt>, except if <tt>reset_contexts</tt> is 1.</t>
</section>

<section anchor="security-considerations"><name>Security Considerations</name>
<t>Like any other codec, (such as <xref target="RFC6716"></xref>), FFV1 should not be used with insecure ciphers or cipher-modes that are vulnerable to known plaintext attacks. Some of the header bits as well as the padding are easily predictable.</t>
<t>Implementations of the FFV1 codec need to take appropriate security considerations into account, as outlined in <xref target="RFC4732"></xref>. It is extremely important for the decoder to be robust against malicious payloads. Malicious payloads must not cause the decoder to overrun its allocated memory or to take an excessive amount of resources to decode. The same applies to the encoder, even though problems in encoders are typically rarer. Malicious video streams must not cause the encoder to misbehave because this would allow an attacker to attack transcoding gateways. A frequent security problem in image and video codecs is also to not check for integer overflows in <tt>Pixel</tt> count computations, that is to allocate width * height without considering that the multiplication result may have overflowed the arithmetic types range.
The range coder could, if implemented naively, read one byte over the end. The implementation must ensure that no read outside allocated and initialized memory occurs.</t>
<t>The reference implementation <xref target="REFIMPL"></xref> contains no known buffer overflow or cases where a specially crafted packet or video segment could cause a significant increase in CPU load.</t>
<t>The reference implementation <xref target="REFIMPL"></xref> was validated in the following conditions:</t>

<ul>
<li><t>Sending the decoder valid packets generated by the reference encoder and verifying that the decoder's output matches the encoder's input.</t>
</li>
<li><t>Sending the decoder packets generated by the reference encoder and then subjected to random corruption.</t>
</li>
<li><t>Sending the decoder random packets that are not FFV1.</t>
</li>
</ul>
<t>In all of the conditions above, the decoder and encoder was run inside the <xref target="VALGRIND"></xref> memory debugger as well as clangs address sanitizer <xref target="Address-Sanitizer"></xref>, which track reads and writes to invalid memory regions as well as the use of uninitialized memory.  There were no errors reported on any of the tested conditions.</t>
</section>

<section anchor="media-type-definition"><name>Media Type Definition</name>
<t>This registration is done using the template defined in <xref target="RFC6838"></xref> and following <xref target="RFC4855"></xref>.</t>
<t>Type name:  video</t>
<t>Subtype name:  FFV1</t>
<t>Required parameters:  None.</t>
<t>Optional parameters:</t>
<t>This parameter is used to signal the capabilities of a receiver implementation. This parameter MUST NOT be used for any other purpose.</t>
<t>version:  The version of the FFV1 encoding as defined by <eref target="#version">the section on version</eref>.</t>
<t>micro_version:  The micro_version of the FFV1 encoding as defined by <eref target="#micro-version">the section on micro_version</eref>.</t>
<t>coder_type:  The coder_type of the FFV1 encoding as defined by <eref target="#coder-type">the section on coder_type</eref>.</t>
<t>colorspace_type:  The colorspace_type of the FFV1 encoding as defined by <eref target="#colorspace-type">the section on colorspace_type</eref>.</t>
<t>bits_per_raw_sample:  The bits_per_raw_sample of the FFV1 encoding as defined by <eref target="#bits-per-raw-sample">the section on bits_per_raw_sample</eref>.</t>
<t>max-slices: The value of max-slices is an integer indicating the maximum count of slices with a frames of the FFV1 encoding.</t>
<t>Encoding considerations:</t>
<t>This media type is defined for encapsulation in several audiovisual container formats and contains binary data; see <eref target="#mapping-ffv1-into-containers">the section on "Mapping FFV1 into Containers"</eref>. This media type is framed binary data Section 4.8 of <xref target="RFC6838"></xref>.</t>
<t>Security considerations:</t>
<t>See <eref target="#security-considerations">the "Security Considerations" section</eref> of this document.</t>
<t>Interoperability considerations:  None.</t>
<t>Published specification:</t>
<t><xref target="I-D.ietf-cellar-ffv1"></xref> and RFC XXXX.</t>
<t>[RFC Editor: Upon publication as an RFC, please replace &quot;XXXX&quot; with the number assigned to this document and remove this note.]</t>
<t>Applications which use this media type:</t>
<t>Any application that requires the transport of lossless video can use this media type. Some examples are, but not limited to screen recording, scientific imaging, and digital video preservation.</t>
<t>Fragment identifier considerations:  N/A.</t>
<t>Additional information:  None.</t>
<t>Person &amp; email address to contact for further information:  Michael Niedermayer <eref target="mailto:michael@niedermayer.cc">michael@niedermayer.cc</eref></t>
<t>Intended usage:  COMMON</t>
<t>Restrictions on usage:  None.</t>
<t>Author:  Dave Rice <eref target="mailto:dave@dericed.com">dave@dericed.com</eref></t>
<t>Change controller:  IETF cellar working group delegated from the IESG.</t>
</section>

<section anchor="iana-considerations"><name>IANA Considerations</name>
<t>The IANA is requested to register the following values:</t>

<ul>
<li><t>Media type registration as described in <eref target="#media-type-definition">Media Type Definition</eref>.</t>
</li>
</ul>
</section>

<section anchor="appendixes"><name>Appendixes</name>

<section anchor="decoder-implementation-suggestions"><name>Decoder implementation suggestions</name>

<section anchor="multi-threading-support-and-independence-of-slices"><name>Multi-threading Support and Independence of Slices</name>
<t>The FFV1 bitstream is parsable in two ways: in sequential order as described in this document or with the pre-analysis of the footer of each slice. Each slice footer contains a slice_size field so the boundary of each slice is computable without having to parse the slice content. That allows multi-threading as well as independence of slice content (a bitstream error in a slice header or slice content has no impact on the decoding of the other slices).</t>
<t>After having checked keyframe field, a decoder SHOULD parse slice_size fields, from slice_size of the last slice at the end of the <tt>Frame</tt> up to slice_size of the first slice at the beginning of the <tt>Frame</tt>, before parsing slices, in order to have slices boundaries. A decoder MAY fallback on sequential order e.g. in case of a corrupted <tt>Frame</tt> (frame size unknown, slice_size of slices not coherent...) or if there is no possibility of seeking into the stream.</t>
</section>
</section>
</section>

<section anchor="changelog"><name>Changelog</name>
<t>See <eref target="https://github.com/FFmpeg/FFV1/commits/master">https://github.com/FFmpeg/FFV1/commits/master</eref></t>
</section>

</middle>

<back>
<references><name>Normative References</name>
<xi:include href="https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.4732.xml"/>
<xi:include href="https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6838.xml"/>
<xi:include href="https://xml2rfc.ietf.org/public/rfc/bibxml-ids/reference.I-D.ietf-cellar-ffv1.xml"/>
<reference anchor="ISO.15444-1.2016" target="">
  <front>
    <title>Information technology -- JPEG 2000 image coding system: Core coding system</title>
    <author>
      <organization>International Organization for Standardization</organization>
    </author>
    <date year="2016" month="October"></date>
  </front>
</reference>
<xi:include href="https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6716.xml"/>
<xi:include href="https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.4855.xml"/>
<reference anchor="ISO.9899.1990" target="">
  <front>
    <title>Programming languages - C</title>
    <author>
      <organization>International Organization for Standardization</organization>
    </author>
    <date year="1990"></date>
  </front>
</reference>
<xi:include href="https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.2119.xml"/>
</references>
<references><name>Informative References</name>
<reference anchor="HuffYUV" target="https://web.archive.org/web/20040402121343/http://cultact-server.novi.dk/kpo/huffyuv/huffyuv.html">
  <front>
    <title>HuffYUV</title>
    <author fullname="Ben Rudiak-Gould" initials="B." surname="Rudiak-Gould"></author>
    <date year="2003" month="December"></date>
  </front>
</reference>
<reference anchor="ISO.14496-10.2014" target="">
  <front>
    <title>Information technology -- Coding of audio-visual objects -- Part 10: Advanced Video Coding</title>
    <author>
      <organization>International Organization for Standardization</organization>
    </author>
    <date year="2014" month="September"></date>
  </front>
</reference>
<reference anchor="Address-Sanitizer" target="https://clang.llvm.org/docs/AddressSanitizer.html">
  <front>
    <title>ASAN AddressSanitizer website</title>
    <author>
      <organization>The Clang Team</organization>
    </author>
    <date year="undated"></date>
  </front>
</reference>
<reference anchor="YCbCr" target="https://en.wikipedia.org/w/index.php?title=YCbCr">
  <front>
    <title>YCbCr</title>
    <author>
      <organization>Wikipedia</organization>
    </author>
    <date year="undated"></date>
  </front>
</reference>
<reference anchor="NUT" target="https://ffmpeg.org/~michael/nut.txt">
  <front>
    <title>NUT Open Container Format</title>
    <author fullname="Michael Niedermayer" initials="M." surname="Niedermayer"></author>
    <date year="2013" month="December"></date>
  </front>
</reference>
<reference anchor="REFIMPL" target="https://ffmpeg.org">
  <front>
    <title>The reference FFV1 implementation / the FFV1 codec in FFmpeg</title>
    <author fullname="Michael Niedermayer" initials="M." surname="Niedermayer"></author>
    <date year="undated"></date>
  </front>
</reference>
<reference anchor="VALGRIND" target="https://valgrind.org/">
  <front>
    <title>Valgrind website</title>
    <author>
      <organization>Valgrind Developers</organization>
    </author>
    <date year="undated"></date>
  </front>
</reference>
<reference anchor="range-coding" target="">
  <front>
    <title>Range encoding: an algorithm for removing redundancy from a digitised message.</title>
    <author initials="G." surname="Nigel"></author>
    <author initials="N." surname="Martin"></author>
    <date year="1979" month="July"></date>
  </front>
</reference>
<reference anchor="ISO.14495-1.1999" target="">
  <front>
    <title>Information technology -- Lossless and near-lossless compression of continuous-tone still images: Baseline</title>
    <author>
      <organization>International Organization for Standardization</organization>
    </author>
    <date year="1999" month="December"></date>
  </front>
</reference>
<reference anchor="ISO.14496-12.2015" target="">
  <front>
    <title>Information technology -- Coding of audio-visual objects -- Part 12: ISO base media file format</title>
    <author>
      <organization>International Organization for Standardization</organization>
    </author>
    <date year="2015" month="December"></date>
  </front>
</reference>
<reference anchor="Matroska" target="https://datatracker.ietf.org/doc/draft-lhomme-cellar-matroska/">
  <front>
    <title>Matroska</title>
    <author>
      <organization>IETF</organization>
    </author>
    <date year="2016"></date>
  </front>
</reference>
<reference anchor="AVI" target="https://msdn.microsoft.com/en-us/library/windows/desktop/dd318189%28v=vs.85%29.aspx">
  <front>
    <title>AVI RIFF File Reference</title>
    <author>
      <organization>Microsoft</organization>
    </author>
    <date year="undated"></date>
  </front>
</reference>
</references>

</back>

</rfc>
