RFC 9043: FFV1 Video Coding Format Versions 0, 1, and 3 (original) (raw)

3. Sample Coding

For each Slice (as described in Section 4.5) of a Frame, the Planes, Lines, and Samples are coded in an order determined by the color space (see Section 3.7). Each Sample is predicted by the median predictor as described in Section 3.3 from other Samples within the same Plane, and the difference is stored using the method described in Section 3.8.

3.1. Border

A border is assumed for each coded Slice for the purpose of the median predictor and context according to the following rules:

Figure 2 depicts a Slice of nine Samples a,b,c,d,e,f,g,h,i in a three-by-three arrangement along with its assumed border.

+---+---+---+---+---+---+---+---+ | 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 | +---+---+---+---+---+---+---+---+

Figure 2:A depiction of FFV1's assumed border for a set of example Samples.

3.2. Samples

Relative to any Sample X, six other relatively positioned Samples from the coded Samples and presumed border are identified according to the labels used in Figure 3. The labels for these relatively positioned Samples are used within the median predictor and context.

+---+---+---+---+ | | | T | | +---+---+---+---+ | |tl | t |tr | +---+---+---+---+ | L | l | X | | +---+---+---+---+

Figure 3:A depiction of how relatively positioned Samples are referenced within this document.

The labels for these relative Samples are made of the first letters of the words Top, Left, and Right.

3.4. Quantization Table Sets

Quantization Tables are used on Sample Differences (see Section 3.8), so Quantized Sample Differences are stored in the bitstream.

The FFV1 bitstream contains one or more Quantization Table Sets. Each Quantization Table Set contains exactly five Quantization Tables with each Quantization Table corresponding to one of the five 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 eight least significant bits of the Quantized Sample Difference are used as an index:

In this formula, i is the Quantization Table Set index, j is the Quantized Table index, and k is the Quantized Sample Difference (see Section 4.1.1).

3.5. Context

Relative to any Sample X, the Quantized Sample Differences L-l, l-tl, tl-t, T-t, and t-tr are used as context:

svg

Figure 5:Description of the computing of the Context.

If context >= 0 then context is used, and the difference between the Sample and its predicted value is encoded as is; else -context is used, and the difference between the Sample and its predicted value is encoded with a flipped sign.

3.6. Quantization Table Set Indexes

For each Plane of each Slice, a Quantization Table Set is selected from an index:

Background: in the first implementations of the FFV1 bitstream, the index for Cb and Cr Planes was stored even if it was not used (chroma_planes set to 0), this index is kept for version <= 3 in order to keep compatibility with FFV1 bitstreams in the wild.

3.7. Color Spaces

FFV1 supports several color spaces. The count of allowed coded Planes and the meaning of the extra Plane are determined by the selected color space.

The FFV1 bitstream interleaves data in an order determined by the color space. In YCbCr for each Plane, each Line is coded from top to bottom, and for each Line, each Sample is coded from left to right. In JPEG 2000 RCT for each Line from top to bottom, each Plane is coded, and for each Plane, each Sample is encoded from left to right.

3.7.1. YCbCr

This color space allows one to four Planes.

The Cb and Cr Planes are optional, but if they are used, then they MUST be used together. Omitting the Cb and Cr Planes codes the frames in gray scale without color data.

An optional transparency Plane can be used to code transparency data.

An FFV1 Frame using YCbCr MUST use one of the following arrangements:

The Y Plane MUST be coded first. If the Cb and Cr Planes are used, then they MUST be coded after the Y Plane. If a transparency Plane is used, then it MUST be coded last.

3.7.2. RGB

This color space allows three or four Planes.

An optional transparency Plane can be used to code transparency data.

JPEG 2000 RCT is a Reversible Color Transform that codes RGB (Red, Green, Blue) Planes losslessly in a modified YCbCr color space [ISO.15444-1.2019]. Reversible pixel transformations between YCbCr and RGB use the following formulae:

Cb and Cr are positively offset by 1 << bits_per_raw_sample after the conversion from RGB to the modified YCbCr, and they are negatively offset by the same value before the conversion from the modified YCbCr to RGB in order to have only nonnegative values after the conversion.

When FFV1 uses the JPEG 2000 RCT, the horizontal Lines are interleaved to improve caching efficiency since it is most likely that the JPEG 2000 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.

As an example, a Frame that is two pixels wide and two pixels high could comprise the following structure:

+------------------------+------------------------+ | 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) | +------------------------+------------------------+

In JPEG 2000 RCT, the coding order is left to right and then top to bottom, with values interleaved by Lines and stored in this order:

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)

3.7.2.1. RGB Exception

If bits_per_raw_sample is between 9 and 15 inclusive and extra_plane is 0, the following formulae for reversible conversions between YCbCr and RGB MUST be used instead of the ones above:

Background: At the time of this writing, in all known implementations of the FFV1 bitstream, when bits_per_raw_sample was between 9 and 15 inclusive and extra_plane was 0, Green Blue Red (GBR) Planes were used as Blue Green Red (BGR) Planes during both encoding and decoding. Meanwhile, 16-bit JPEG 2000 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.

3.8. Coding of the Sample Difference

Instead of coding the n+1 bits of the Sample Difference with Huffman or Range coding (or n+2 bits, in the case of JPEG 2000 RCT), only the n (or n+1, in the case of JPEG 2000 RCT) least significant bits are used, since this is sufficient to recover the original Sample. In Figure 10, the term bits represents bits_per_raw_sample + 1 for JPEG 2000 RCT or bits_per_raw_sample otherwise:

3.8.1. Range Coding Mode

Early experimental versions of FFV1 used the Context-Adaptive Binary Arithmetic Coding (CABAC) coder from H.264 as defined in [ISO.14496-10.2020], 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 N. Martin in 1979 [Range-Encoding].

3.8.1.1. Range Binary Values

To encode binary digits efficiently, a range coder is used. A range coder encodes a series of binary symbols by using a probability estimation within each context. The sizes of each of the two subranges are proportional to their estimated probability. The Quantization Table is used to choose the context used from the surrounding image sample values for the case of coding the Sample Differences. The coding of integers is done by coding multiple binary values. The range decoder will read bytes until it can determine into which subrange the input falls to return the next binary symbol.

To describe Range coding for FFV1, the following values are used:

Ci

the i-th context.

Bi

the i-th byte of the bytestream.

Ri

the Range at the i-th symbol.

ri

the boundary between two subranges of Ri: a subrange of ri values and a subrange Ri - ri values.

Li

the Low value of the Range at the i-th symbol.

li

a temporary variable to carry over or adjust the Low value of the Range between range coding operations.

ti

a temporary variable to transmit subranges between range coding operations.

bi

the i-th range-coded binary value.

S0, i

the i-th initial state.

jn

the length of the bytestream encoding n binary symbols.

The following range coder state variables are initialized to the following values. The Range is initialized to a value of 65,280 (expressed in base 16 as 0xFF00) as depicted in Figure 11. The Low is initialized according to the value of the first two bytes as depicted in Figure 12. ji tracks the length of the bytestream encoding while incrementing from an initial value of j0 to a final value of jn. j0 is initialized to 2 as depicted in Figure 13.

The following equations define how the range coder variables evolve as it reads or writes symbols.

svg

Figure 15:This formula shows the linking of the decoded symbol (represented as bi), the updated state (represented as Si+1,Ci), and the updated range (represented as a range from li to ti).

svg

Figure 16:If the value of k is unequal to the i-th value of context, in other words, if the state is unchanged from the last symbol coding, then the value of the state is carried over to the next symbol coding.

svg

Figure 17:This formula shows the linking of the range coder with the reading or writing of the bytestream.

range = 0xFF00;
end   = 0;
low   = get_bits(16);
if (low >= range) {
    low = range;
    end = 1;
}

Figure 18:A pseudocode description of the initialization of range coder variables in Range binary mode.

refill() { if (range < 256) { range = range * 256; low = low * 256; if (!end) { c.low += get_bits(8); if (remaining_bits_in_bitstream( NumBytes ) == 0) { end = 1; } } } }

Figure 19:A pseudocode description of refilling the binary value buffer of the range coder.

get_rac(state) { rangeoff = (range * state) / 256; range -= rangeoff; if (low < range) { state = zero_state[state]; refill(); return 0; } else { low -= range; state = one_state[state]; range = rangeoff; refill(); return 1; } }

Figure 20:A pseudocode description of the read of a binary value in Range binary mode.

3.8.1.1.1. Termination

The range coder can be used in three modes:

The above describes the range decoding. Encoding is defined as any process that produces a decodable bytestream.

There are three places where range coder termination is needed in FFV1. The first is in the Configuration Record, which in this case the size of the range-coded bytestream is known and handled as Closed mode. The second is the switch from the Slice Header, which is range coded to Golomb-coded Slices as Sentinel mode. The third is the end of range-coded Slices, which need to terminate before the CRC at their end. This can be handled as Sentinel mode or as Closed mode if the CRC position has been determined.

3.8.1.2. Range Nonbinary Values

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, which is not only a waste of memory but also requires more past data to reach a reasonably good estimate of the probabilities. Alternatively, it would also be possible to assume a Laplacian distribution and only deal with its variance and mean (as in Huffman coding). However, for maximum flexibility and simplicity, the chosen method uses a single symbol to encode if a number is 0, and if the number is nonzero, it encodes the number using its exponent, mantissa, and sign. The exact contexts used are best described by Figure 21.

int get_symbol(RangeCoder *c, uint8_t *state, int is_signed) { if (get_rac(c, state + 0) { return 0; }

int e = 0;
while (get_rac(c, state + 1 + min(e, 9)) { //1..10
    e++;
}

int a = 1;
for (int i = e - 1; i >= 0; i--) {
    a = a * 2 + get_rac(c, state + 22 + min(i, 9));  // 22..31
}

if (!is_signed) {
    return a;
}

if (get_rac(c, state + 11 + min(e, 10))) { //11..21
    return -a;
} else {
    return a;
}

}

Figure 21:A pseudocode description of the contexts of Range nonbinary values.

get_symbol is used for the read out of sample_difference indicated in Figure 10.

get_rac returns a boolean computed from the bytestream as described by the formula found in Figure 14 and by the pseudocode found in Figure 20.

3.8.1.3. Initial Values for the Context Model

When the keyframe value (see Section 4.4) is 1, all range coder state variables are set to their initial state.

3.8.1.4. State Transition Table

In Range Coding Mode, a state transition table is used, indicating to which state the decoder will move based on the current state and the value extracted from Figure 20.

3.8.1.5. default_state_transition

By default, the following state transition table is used:

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,

Figure 24:Default state transition table for Range coding.

3.8.1.6. Alternative State Transition Table

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 Section 4.2.3) MUST be set to 2, and the difference to the default MUST be stored in the Parameters, see Section 4.2. At the time of this writing, the reference implementation of FFV1 in FFmpeg uses Figure 25 by default when Range coding is used.

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,

Figure 25:Alternative state transition table for Range coding.

3.8.2. Golomb Rice Mode

The end of the bitstream of the Frame is padded with zeroes until the bitstream contains a multiple of eight bits.

3.8.2.1. Signed Golomb Rice Codes

This coding mode uses Golomb Rice codes. The VLC is split into two parts: the prefix and suffix. The prefix stores the most significant bits or indicates if the symbol is too large to be stored (this is known as the ESC case, see Section 3.8.2.1.1). The suffix either stores the k least significant bits or stores the whole number in the ESC case.

int get_ur_golomb(k) { for (prefix = 0; prefix < 12; prefix++) { if (get_bits(1)) { return get_bits(k) + (prefix << k); } } return get_bits(bits) + 11; }

Figure 26:A pseudocode description of the read of an unsigned integer in Golomb Rice mode.

int get_sr_golomb(k) { v = get_ur_golomb(k); if (v & 1) return - (v >> 1) - 1; else return (v >> 1); }

Figure 27:A pseudocode description of the read of a signed integer in Golomb Rice mode.

3.8.2.1.1. Prefix

Table 1:Description of the coding of the prefix of signed Golomb Rice codes.

bits value
1 0
01 1
... ...
0000 0000 01 9
0000 0000 001 10
0000 0000 0001 11
0000 0000 0000 ESC

ESC is 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.

3.8.2.1.2. Suffix

Table 2:Description of the coding of the suffix of signed Golomb Rice codes.

non-ESC the k least significant bits MSB first
ESC the value - 11, in MSB first order

ESC MUST NOT be used if the value can be coded as non-ESC.

3.8.2.1.3. Examples

Table 3 shows practical examples of how signed Golomb Rice codes are decoded based on the series of bits extracted from the bitstream as described by the method above:

Table 3:Examples of decoded, signed Golomb Rice codes.

k bits value
0 1 0
0 001 2
2 1 00 0
2 1 10 2
2 01 01 5
any 000000000000 10000000 139
3.8.2.2. Run Mode

Run mode is entered when the context is 0 and left as soon as a nonzero difference is found. The Sample Difference is identical to the predicted one. The run and the first different Sample Difference are coded as defined in Section 3.8.2.4.1.

3.8.2.2.1. Run Length Coding

The run value is encoded in two 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 second part of the value stores the less significant part of the run as it is. The run_index is reset to zero for each Plane and Slice.

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 && run_mode == 1) { if (get_bits(1)) { run_count = 1 << log2_run[run_index]; if (x + run_count <= 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; } }

The log2_run array is also used within [ISO.14495-1.1999].

3.8.2.3. Sign Extension

sign_extend is the function of increasing the number of bits of an input binary number in two's complement signed number representation while preserving the input number's sign (positive/negative) and value, in order to fit in the output bit width. It MAY be computed with the following:

sign_extend(input_number, input_bits) { negative_bias = 1 << (input_bits - 1); bits_mask = negative_bias - 1; output_number = input_number & bits_mask; // Remove negative bit is_negative = input_number & negative_bias; // Test negative bit if (is_negative) output_number -= negative_bias; return output_number }

3.8.2.4. Scalar Mode

Each difference is coded with the per context mean prediction removed and a per context value for k.

get_vlc_symbol(state) { i = state->count; k = 0; while (i < state->error_sum) { k++; i += i; }

v = get_sr_golomb(k);

if (2 * state->drift < -state->count) {
    v = -1 - v;
}

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

state->error_sum += abs(v);
state->drift     += v;

if (state->count == 128) {
    state->count     >>= 1;
    state->drift     >>= 1;
    state->error_sum >>= 1;
}
state->count++;
if (state->drift <= -state->count) {
    state->bias = max(state->bias - 1, -128);

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

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

return ret;

}

3.8.2.4.1. Golomb Rice Sample Difference Coding

Level coding is identical to the normal difference coding with the exception that the 0 value is removed as it cannot occur:

diff = get_vlc_symbol(context_state);
if (diff >= 0) {
    diff++;
}

Note that this is different from JPEG-LS (lossless JPEG), 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 Samples, the use of prediction slightly improved the compression rate.

3.8.2.5. Initial Values for the VLC Context State

When keyframe (see Section 4.4) value is 1, all VLC coder state variables are set to their initial state.

drift     = 0;
error_sum = 4;
bias      = 0;
count     = 1;