namespace Febe.Tests.Codecs.H264; /// The bits of an RBSP written one by one (§7.2): fixed-length fields, Exp-Golomb codes, bits copied from another RBSP. internal sealed class BitWriter { private readonly List bits = []; /// Bits written so far. public int Count => bits.Count; 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)); /// Zero bits up to the next byte. public void Align() { while (bits.Count % 8 != 0) { bits.Add(false); } } /// One bits up to the next byte (cabac_alignment_one_bit). public void AlignWithOnes() { while (bits.Count % 8 != 0) { bits.Add(true); } } /// Bits (included) to (excluded) of , most significant first. public void Copy(byte[] data, int from, int to) { for (var i = from; i < to; i++) { bits.Add(((data[i >> 3] >> (7 - (i & 7))) & 1) != 0); } } /// rbsp_trailing_bits(): the stop bit and zeros up to the byte. public void Trailing() { bits.Add(true); Align(); } /// The bytes, padded with zeros to the byte, with emulation prevention (§7.4.1). 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.1): never two zero bytes followed by a byte up to 3. var output = new List(bytes.Length + 16); 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]; } }