using Febe.Core.Codecs.H265; using Lps = Febe.Core.Codecs.H264.CabacTables; namespace Febe.Tests.Codecs.H265; /// /// Tiny HEVC streams written bit by bit from the syntax of ITU-T H.265 (§7.3), their slice data with a CABAC encoder /// that mirrors the decoding engine of §9.3.4.3: 4:2:0 parameter sets with 16×16 coding tree blocks, I pictures whose /// coding tree units are one intra coding unit predicted from nothing (every sample at the middle of its range) and P /// pictures whose coding tree units are skipped. A picture can stop after its first coding tree unit, so pictures of /// any size cost a few bytes. They reach what the conformance streams do not: missing references, reference picture /// sets larger than the buffer, parameter sets repeated inside a picture, the screen content extensions, large weighted /// prediction offsets. /// internal static class H265SyntheticStreams { internal const int Cra = 21; internal const int TrailR = 1; /// Settings of the sequence parameter set. internal sealed record SequenceSettings( int Width = 16, int Height = 16, int MaxDecPicBufferingMinus1 = 4, int BitDepth = 8, bool LongTermRefsPresent = false, bool HighPrecisionOffsets = false, bool SccExtension = false, int ProfileIdc = 1); /// Settings of the picture parameter set. internal sealed record PictureSettings( bool OutputFlagPresent = false, bool WeightedPred = false, bool SccExtension = false, int InitQpMinus26 = 0); /// A slice segment: its NAL unit type and the syntax elements of its header that the tests vary. internal sealed record SliceSettings(int NalType, int PocLsb) { public bool First { get; init; } = true; /// slice_segment_address of a segment that is not the first. public int Address { get; init; } /// Picture size in coding tree blocks (for the bits of the address and to know the last one). public int CtbCount { get; init; } = 1; /// Coding tree units coded in the segment, from its address; the slice ends after them. public int Ctus { get; init; } = 1; /// Coding tree blocks per row (for the contexts of cu_skip_flag). public int WidthInCtbs { get; init; } = 1; /// The negative deltas of the short-term set, each with used_by_curr_pic_s0_flag. public (int Delta, bool Used)[] Negative { get; init; } = []; /// poc_lsb_lt and used_by_curr_pic_lt_flag of the long-term entries (the SPS must allow them). public (int PocLsb, bool Used)[] LongTerm { get; init; } = []; /// num_ref_idx_l0_active_minus1 + 1, written with the override flag when it is not 1. public int ActiveRefs { get; init; } = 1; /// pic_output_flag, written when the PPS has output_flag_present_flag. public bool? OutputFlag { get; init; } /// luma_offset_l0 of reference 0, with a weight table, when the PPS has weighted_pred_flag. public int? LumaOffset { get; init; } } /// A sequence parameter set NAL unit (§7.3.2.2), without start code. internal static byte[] Sps(SequenceSettings s) { var bits = new BitWriter(); bits.Bits(0, 4); // sps_video_parameter_set_id bits.Bits(0, 3); // sps_max_sub_layers_minus1 bits.Bits(1, 1); // sps_temporal_id_nesting_flag // profile_tier_level(1, 0): space, tier, profile, 32 compatibility flags, 48 bits of constraints, level. bits.Bits(0, 3); bits.Bits((uint)s.ProfileIdc, 5); bits.Bits(1u << (31 - s.ProfileIdc), 32); bits.Bits(0, 24); bits.Bits(0, 24); bits.Bits(186, 8); // general_level_idc: 6.2 bits.Ue(0); // sps_seq_parameter_set_id bits.Ue(1); // chroma_format_idc: 4:2:0 bits.Ue((uint)s.Width); bits.Ue((uint)s.Height); bits.Bits(0, 1); // conformance_window_flag bits.Ue((uint)s.BitDepth - 8); bits.Ue((uint)s.BitDepth - 8); bits.Ue(4); // log2_max_pic_order_cnt_lsb_minus4: 8 bits bits.Bits(1, 1); // sps_sub_layer_ordering_info_present_flag bits.Ue((uint)s.MaxDecPicBufferingMinus1); bits.Ue(0); // sps_max_num_reorder_pics bits.Ue(0); // sps_max_latency_increase_plus1 bits.Ue(0); // log2_min_luma_coding_block_size_minus3: 8×8 bits.Ue(1); // log2_diff_max_min_luma_coding_block_size: 16×16 coding tree blocks bits.Ue(0); // log2_min_luma_transform_block_size_minus2: 4×4 bits.Ue(2); // log2_diff_max_min_luma_transform_block_size: 16×16 bits.Ue(0); // max_transform_hierarchy_depth_inter bits.Ue(0); // max_transform_hierarchy_depth_intra bits.Bits(0, 1); // scaling_list_enabled_flag bits.Bits(0, 1); // amp_enabled_flag bits.Bits(0, 1); // sample_adaptive_offset_enabled_flag bits.Bits(0, 1); // pcm_enabled_flag bits.Ue(0); // num_short_term_ref_pic_sets bits.Bits(s.LongTermRefsPresent ? 1u : 0u, 1); if (s.LongTermRefsPresent) { bits.Ue(0); // num_long_term_ref_pics_sps } bits.Bits(0, 1); // sps_temporal_mvp_enabled_flag bits.Bits(0, 1); // strong_intra_smoothing_enabled_flag bits.Bits(0, 1); // vui_parameters_present_flag var extension = s.HighPrecisionOffsets || s.SccExtension; bits.Bits(extension ? 1u : 0u, 1); if (extension) { bits.Bits(s.HighPrecisionOffsets ? 1u : 0u, 1); // sps_range_extension_flag bits.Bits(0, 2); // sps_multilayer_extension_flag, sps_3d_extension_flag bits.Bits(s.SccExtension ? 1u : 0u, 1); bits.Bits(0, 4); // sps_extension_4bits if (s.HighPrecisionOffsets) { // Range extension flags: only high_precision_offsets_enabled_flag (the seventh). bits.Bits(0b0000_0010_0, 9); } // sps_scc_extension() is not written: the decoder refuses the stream before it would need it. } return Nal(33, bits); } /// A picture parameter set NAL unit (§7.3.2.3), without start code: deblocking off, no tiles or wavefronts. internal static byte[] Pps(PictureSettings p) { var bits = new BitWriter(); bits.Ue(0); // pps_pic_parameter_set_id bits.Ue(0); // pps_seq_parameter_set_id bits.Bits(0, 1); // dependent_slice_segments_enabled_flag bits.Bits(p.OutputFlagPresent ? 1u : 0u, 1); bits.Bits(0, 3); // num_extra_slice_header_bits bits.Bits(0, 1); // sign_data_hiding_enabled_flag bits.Bits(0, 1); // cabac_init_present_flag bits.Ue(0); // num_ref_idx_l0_default_active_minus1 bits.Ue(0); // num_ref_idx_l1_default_active_minus1 bits.Se(p.InitQpMinus26); bits.Bits(0, 1); // constrained_intra_pred_flag bits.Bits(0, 1); // transform_skip_enabled_flag bits.Bits(0, 1); // cu_qp_delta_enabled_flag bits.Se(0); // pps_cb_qp_offset bits.Se(0); // pps_cr_qp_offset bits.Bits(0, 1); // pps_slice_chroma_qp_offsets_present_flag bits.Bits(p.WeightedPred ? 1u : 0u, 1); bits.Bits(0, 1); // weighted_bipred_flag bits.Bits(0, 1); // transquant_bypass_enabled_flag bits.Bits(0, 1); // tiles_enabled_flag bits.Bits(0, 1); // entropy_coding_sync_enabled_flag bits.Bits(0, 1); // pps_loop_filter_across_slices_enabled_flag bits.Bits(1, 1); // deblocking_filter_control_present_flag bits.Bits(0, 1); // deblocking_filter_override_enabled_flag bits.Bits(1, 1); // pps_deblocking_filter_disabled_flag bits.Bits(0, 1); // pps_scaling_list_data_present_flag bits.Bits(0, 1); // lists_modification_present_flag bits.Ue(0); // log2_parallel_merge_level_minus2 bits.Bits(0, 1); // slice_segment_header_extension_present_flag bits.Bits(p.SccExtension ? 1u : 0u, 1); if (p.SccExtension) { bits.Bits(0, 3); // pps_range_extension_flag, pps_multilayer_extension_flag, pps_3d_extension_flag bits.Bits(1, 1); // pps_scc_extension_flag bits.Bits(0, 4); // pps_extension_4bits; pps_scc_extension() is not written } return Nal(34, bits); } /// A slice segment NAL unit (§7.3.6, §7.3.8), without start code, for the parameter sets above. internal static byte[] Slice(SliceSettings s, SequenceSettings sequence, PictureSettings picture) { var bits = new BitWriter(); bits.Bits(s.First ? 1u : 0u, 1); if (s.NalType is >= 16 and <= 23) { bits.Bits(0, 1); // no_output_of_prior_pics_flag } bits.Ue(0); // slice_pic_parameter_set_id if (!s.First) { var addressBits = 0; while ((1 << addressBits) < s.CtbCount) { addressBits++; } bits.Bits((uint)s.Address, addressBits); } var intra = s.NalType is >= 16 and <= 23; bits.Ue(intra ? 2u : 1u); // slice_type: I or P if (picture.OutputFlagPresent) { bits.Bits(s.OutputFlag ?? true ? 1u : 0u, 1); } bits.Bits((uint)s.PocLsb, 8); bits.Bits(0, 1); // short_term_ref_pic_set_sps_flag: the set follows bits.Ue((uint)s.Negative.Length); bits.Ue(0); // num_positive_pics var previous = 0; foreach (var (delta, used) in s.Negative) { bits.Ue((uint)(previous - delta - 1)); // delta_poc_s0_minus1, from the previous entry bits.Bits(used ? 1u : 0u, 1); previous = delta; } if (sequence.LongTermRefsPresent) { bits.Ue((uint)s.LongTerm.Length); foreach (var (pocLsb, used) in s.LongTerm) { bits.Bits((uint)pocLsb, 8); bits.Bits(used ? 1u : 0u, 1); bits.Bits(0, 1); // delta_poc_msb_present_flag } } if (!intra) { bits.Bits(s.ActiveRefs != 1 ? 1u : 0u, 1); // num_ref_idx_active_override_flag if (s.ActiveRefs != 1) { bits.Ue((uint)s.ActiveRefs - 1); } if (picture.WeightedPred) { bits.Ue(6); // luma_log2_weight_denom bits.Se(0); // delta_chroma_log2_weight_denom for (var i = 0; i < s.ActiveRefs; i++) { bits.Bits(i == 0 ? 1u : 0u, 1); // luma_weight_l0_flag } bits.Bits(0, s.ActiveRefs); // chroma_weight_l0_flag bits.Se(0); // delta_luma_weight_l0 bits.Se(s.LumaOffset ?? 0); } bits.Ue(4); // five_minus_max_num_merge_cand: one candidate, no merge_idx } bits.Se(0); // slice_qp_delta bits.Bits(1, 1); // byte_alignment() bits.Align(); var cabac = new CabacWriter(bits, intra ? 0 : 1, 26 + picture.InitQpMinus26); for (var k = 0; k < s.Ctus; k++) { var address = s.Address + k; cabac.Decision(CabacTables.SplitCuFlag, 0); if (intra) { cabac.Decision(CabacTables.PrevIntraLumaPredFlag, 1); cabac.Bypass(0); // mpm_idx 0 cabac.Decision(CabacTables.IntraChromaPredMode, 0); // the luma mode cabac.Decision(CabacTables.CbfChroma, 0); cabac.Decision(CabacTables.CbfChroma, 0); cabac.Decision(CabacTables.CbfLuma + 1, 0); } else { // cu_skip_flag: one more for each neighbour (left, above) of the same slice, all skipped. var x = address % s.WidthInCtbs; var y = address / s.WidthInCtbs; var ctx = (x > 0 && address > s.Address ? 1 : 0) + (y > 0 && address - s.WidthInCtbs >= s.Address ? 1 : 0); cabac.Decision(CabacTables.CuSkipFlag + ctx, 1); } cabac.Terminate(k == s.Ctus - 1 ? 1 : 0); // end_of_slice_segment_flag } bits.Align(); return Nal(s.NalType, bits, stopBit: false); } /// NAL units with start codes, one after the other. internal static byte[] AnnexB(params byte[][] units) => [.. units.SelectMany(u => (byte[])[0, 0, 0, 1, .. u])]; private static byte[] Nal(int type, BitWriter bits, bool stopBit = true) { if (stopBit) { bits.Bits(1, 1); // rbsp_stop_one_bit bits.Align(); } return [(byte)(type << 1), 1, .. bits.ToArray()]; } /// /// The arithmetic encoder that matches the decoding engine bit for bit (the encoding flowcharts of ITU-T H.264 /// §9.3.4, whose arithmetic HEVC keeps), with the context variables initialised by the decoder's own code. /// private sealed class CabacWriter { private readonly BitWriter bits; private readonly byte[] contexts; private int low; private int range = 510; private int outstanding; private bool firstBit = true; public CabacWriter(BitWriter bits, int initType, int sliceQp) { this.bits = bits; var engine = new CabacEngine(); engine.InitContexts(initType, sliceQp); contexts = (byte[])engine.Contexts.Clone(); } public void Decision(int ctx, int bin) { int s = contexts[ctx]; var p = s >> 1; var mps = s & 1; int lps = Lps.RangeLps[(p << 2) + ((range >> 6) & 3)]; range -= lps; if (bin != mps) { low += range; range = lps; if (p == 0) { mps ^= 1; } contexts[ctx] = (byte)((Lps.NextStateLps[p] << 1) | mps); } else if (p < 62) { contexts[ctx] = (byte)(s + 2); } Renormalise(); } public void Bypass(int bin) { low <<= 1; if (bin != 0) { low += range; } if (low >= 1024) { Put(1); low -= 1024; } else if (low < 512) { Put(0); } else { low -= 512; outstanding++; } } public void Terminate(int bin) { range -= 2; if (bin == 0) { Renormalise(); return; } // EncodeFlush: the last bit written is the stop bit of the slice data. low += range; range = 2; Renormalise(); Put((low >> 9) & 1); bits.Bits((uint)(((low >> 7) & 3) | 1), 2); } private void Renormalise() { while (range < 256) { if (low < 256) { Put(0); } else if (low >= 512) { low -= 512; Put(1); } else { low -= 256; outstanding++; } range <<= 1; low <<= 1; } } private void Put(int bit) { if (firstBit) { firstBit = false; } else { bits.Bits((uint)bit, 1); } for (; outstanding > 0; outstanding--) { bits.Bits((uint)(1 - bit), 1); } } } private sealed class BitWriter { private readonly List bits = []; public void Bits(uint value, int count) { for (var i = count - 1; i >= 0; i--) { bits.Add(((value >> i) & 1) != 0); } } public void Ue(uint value) { var code = value + 1; var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code); Bits(0, length - 1); Bits(code, length); } public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1)); public void Align() { while (bits.Count % 8 != 0) { bits.Add(false); } } public byte[] ToArray() { var bytes = new byte[(bits.Count + 7) / 8]; for (var i = 0; i < bits.Count; i++) { if (bits[i]) { bytes[i / 8] |= (byte)(0x80 >> (i % 8)); } } // Emulation prevention (§7.4.2): never two zero bytes followed by a byte up to 3. var output = new List(); var zeros = 0; foreach (var b in bytes) { if (zeros >= 2 && b <= 3) { output.Add(3); zeros = 0; } output.Add(b); zeros = b == 0 ? zeros + 1 : 0; } return [.. output]; } } }