using Febe.Core.Codecs.H264; namespace Febe.Tests.Codecs.H264; /// /// Conformance streams rewritten with the tools of the Extended and Baseline profiles that no stream of the ITU-T series /// uses: the same pictures split into data partitions, with redundant slices, with the slices of each picture in another /// order. The macroblocks and their bits do not change, so the official reconstruction stays the expected result. /// internal static class StreamRewriter { /// /// Every non-IDR slice (NAL unit 1) as partitions A, B and C (§7.3.2.8–§7.3.2.10): the decoder reads the original /// stream and says where the residual of each macroblock lies; A keeps the header and everything else, B the residual /// of the intra macroblocks, C that of the inter ones. A partition with nothing in it is left out, as are those that /// and drop. Only CAVLC without constrained intra prediction and /// without I_PCM: with them the bits would not stay the same (§9.2.1, pcm_alignment_zero_bit). /// internal static byte[] Partition(byte[] stream, bool keepB = true, bool keepC = true) { var decoder = new H264Decoder(); var residual = new List<(int Start, int End, bool Intra, bool Pcm)>(); decoder.ResidualRead = (start, end, intra, pcm) => residual.Add((start, end, intra, pcm)); var sequences = new Dictionary(); var pictures = new Dictionary(); var output = new List(); var sliceId = 0; foreach (var unit in Units(stream)) { var nal = NalUnits.Parse(unit); Remember(nal, sequences, pictures); residual.Clear(); decoder.DecodeUnit(unit); if (nal.Type != 1) { output.Add(unit); continue; } var reader = nal.Reader(); var header = SliceHeader.Parse(reader, nal, sequences, pictures, out _, out var pps); if (pps.Cabac || pps.ConstrainedIntraPred || residual.Exists(r => r.Pcm)) { throw new InvalidOperationException("Flusso non adatto: CABAC, predizione intra vincolata o I_PCM."); } // slice_id: 0 for the first slice of each picture, then one more per slice (the streams are in order). sliceId = header.FirstMb == 0 ? 0 : sliceId + 1; var a = new BitWriter(); a.Copy(nal.Rbsp, 8, reader.Position); a.Ue((uint)sliceId); var b = PartitionStart(sliceId, pps, header); var c = PartitionStart(sliceId, pps, header); var position = reader.Position; foreach (var (start, end, intra, _) in residual) { a.Copy(nal.Rbsp, position, start); (intra ? b : c).Copy(nal.Rbsp, start, end); position = end; } a.Copy(nal.Rbsp, position, StopBit(nal)); var refIdc = (byte)(nal.RefIdc << 5); output.Add(Unit((byte)(refIdc | 2), a)); if (keepB && residual.Exists(r => r.Intra)) { output.Add(Unit((byte)(refIdc | 3), b)); } if (keepC && residual.Exists(r => !r.Intra)) { output.Add(Unit((byte)(refIdc | 4), c)); } } return Join(output); } /// /// A partitioned stream () with the partition A of some slices lost: of every other slice /// whose partitions B or C come right after those of the slice before, when that slice is still waiting for nothing /// a decoder could take them for (a slice_id of its own, or the slice before already has both B and C). With /// the whole slice is lost instead, its B and C with it. is the /// number of slices that lost their partition A. /// internal static byte[] DropPartitionsA(byte[] partitioned, bool alsoBAndC, out int dropped) { var units = Units(partitioned); var output = new List(); dropped = 0; var candidates = 0; (int Start, int End)? previous = null; var i = 0; while (i < units.Count) { if ((units[i][0] & 0x1F) != 2) { output.Add(units[i]); previous = null; i++; continue; } var end = i + 1; while (end < units.Count && (units[end][0] & 0x1F) is 3 or 4) { end++; } var drop = false; if (previous is { } before && end > i + 1 && end - i - 1 <= 2) { var full = before.End - before.Start == 3; var id = SliceIdOf(units[i + 1]); var beforeId = before.End > before.Start + 1 ? SliceIdOf(units[before.Start + 1]) : id; drop = (full || id != beforeId) && candidates++ % 2 == 0; } if (drop) { dropped++; if (!alsoBAndC) { output.AddRange(units.GetRange(i + 1, end - i - 1)); } } else { output.AddRange(units.GetRange(i, end - i)); } // A slice that lost its partition A is no slice the next one can follow: the decoder still waits for the // one before it. previous = drop ? null : (i, end); i = end; } return Join(output); } /// slice_id, the first syntax element of a partition B or C. private static int SliceIdOf(byte[] unit) => NalUnits.Parse(unit).Reader().ReadUe(Sps.MaxFrameMbs - 1); /// /// The same stream with redundant_pic_cnt_present_flag set in every PPS (§7.3.2.2) and, after the slices of each /// picture, a redundant copy of them (redundant_pic_cnt 1) whose header is the primary one and whose data are random /// bits: a decoder that decodes a redundant slice cannot give the official reconstruction. /// internal static byte[] AddRedundantSlices(byte[] stream, int seed) { var random = new Random(seed); var sequences = new Dictionary(); var pictures = new Dictionary(); var output = new List(); var redundant = new List(); foreach (var unit in Units(stream)) { var nal = NalUnits.Parse(unit); var slice = nal.Type is 1 or 5; var header = slice ? SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _) : null; if (!slice || header!.FirstMb == 0) { output.AddRange(redundant); redundant.Clear(); } if (nal.Type == 8) { Remember(nal, sequences, pictures); output.Add(SetRedundantFlag(nal)); continue; } Remember(nal, sequences, pictures); if (!slice) { output.Add(unit); continue; } var reader = nal.Reader(); SliceHeader.Parse(reader, nal, sequences, pictures, out var sps, out var pps); var headerEnd = reader.Position; var insert = RedundantPicCntPosition(nal, sps, pps); output.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 0, null)); var garbage = new byte[16 + random.Next(48)]; random.NextBytes(garbage); redundant.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 1, garbage)); } output.AddRange(redundant); return Join(output); } /// /// The slices of each picture in reverse order (arbitrary slice order, §7.4.3: Baseline and Extended). A picture ends /// at a NAL unit that is not a slice or at a slice whose header differs as in §7.4.1.2.4: the source may already send /// its slices out of order. /// internal static byte[] ReverseSlices(byte[] stream) { var sequences = new Dictionary(); var pictures = new Dictionary(); var output = new List(); var picture = new List(); var current = ""; foreach (var unit in Units(stream)) { var nal = NalUnits.Parse(unit); Remember(nal, sequences, pictures); var slice = nal.Type is 1 or 5; var key = ""; if (slice) { var h = SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _); key = $"{h.FrameNum} {h.PpsId} {h.Structure} {nal.RefIdc == 0} {nal.Type} {h.IdrPicId} {h.PocLsb} {h.DeltaPocBottom} {h.DeltaPoc0} {h.DeltaPoc1}"; } if (!slice || key != current) { current = key; picture.Reverse(); output.AddRange(picture); picture.Clear(); } if (slice) { picture.Add(unit); } else { output.Add(unit); } } picture.Reverse(); output.AddRange(picture); return Join(output); } /// The NAL units of an Annex B stream, each with its header and without start code. internal static List Units(byte[] stream) { var units = new List(); var position = 0; while (NalUnits.NextAnnexB(stream, ref position, out var range)) { units.Add(stream[range]); } return units; } internal static byte[] Join(IEnumerable units) { var output = new List(); foreach (var unit in units) { output.AddRange((byte[])[0, 0, 0, 1]); output.AddRange(unit); } return [.. output]; } private static void Remember(NalUnit nal, Dictionary sequences, Dictionary pictures) { if (nal.Type == 7) { var sps = Sps.Parse(nal.Reader()); sequences[sps.Id] = sps; } else if (nal.Type == 8) { var pps = Pps.Parse(nal.Reader(), sequences); pictures[pps.Id] = pps; } } /// slice_id, then redundant_pic_cnt when the PPS has it (§7.3.2.10). private static BitWriter PartitionStart(int sliceId, Pps pps, SliceHeader header) { var bits = new BitWriter(); bits.Ue((uint)sliceId); if (pps.RedundantPicCntPresent) { bits.Ue((uint)header.RedundantPicCnt); } return bits; } private static byte[] Unit(byte header, BitWriter bits) { bits.Trailing(); return [header, .. bits.ToArray()]; } /// The position of the rbsp_stop_one_bit: the last bit set of the payload. private static int StopBit(NalUnit nal) { var last = nal.Length - 1; while (nal.Rbsp[last] == 0) { last--; } return (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(nal.Rbsp[last]); } /// Where redundant_pic_cnt goes in a slice header: after the picture order count fields (§7.3.3). private static int RedundantPicCntPosition(NalUnit nal, Sps sps, Pps pps) { var r = nal.Reader(); r.ReadUe(); // first_mb_in_slice r.ReadUe(); // slice_type r.ReadUe(); // pic_parameter_set_id r.Read(sps.Log2MaxFrameNum); var field = false; if (!sps.FrameMbsOnly && (field = r.ReadFlag())) { r.ReadFlag(); // bottom_field_flag } if (nal.Type == 5) { r.ReadUe(); // idr_pic_id } if (sps.PocType == 0) { r.Read(sps.Log2MaxPocLsb); if (pps.BottomFieldPicOrderInFramePresent && !field) { r.ReadSe(); } } else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero) { r.ReadSe(); if (pps.BottomFieldPicOrderInFramePresent && !field) { r.ReadSe(); } } return r.Position; } /// /// The slice with redundant_pic_cnt inserted at ; with its slice /// data are those bytes instead of the original ones (CABAC data start again at a byte, after cabac_alignment_one_bit). /// private static byte[] WithRedundantPicCnt(NalUnit nal, int insert, int headerEnd, bool cabac, int count, byte[]? garbage) { var bits = new BitWriter(); bits.Copy(nal.Rbsp, 8, insert); bits.Ue((uint)count); bits.Copy(nal.Rbsp, insert, headerEnd); if (cabac) { bits.AlignWithOnes(); if (garbage is null) { bits.Copy(nal.Rbsp, (headerEnd + 7) / 8 * 8, nal.Length * 8); return [nal.Rbsp[0], .. bits.ToArray()]; } } if (garbage is null) { bits.Copy(nal.Rbsp, headerEnd, StopBit(nal)); } else { bits.Copy(garbage, 0, garbage.Length * 8); } bits.Trailing(); return [nal.Rbsp[0], .. bits.ToArray()]; } /// The PPS with redundant_pic_cnt_present_flag set: the fields before it read again (§7.3.2.2). private static byte[] SetRedundantFlag(NalUnit nal) { var r = nal.Reader(); r.ReadUe(); // pic_parameter_set_id r.ReadUe(); // seq_parameter_set_id r.ReadFlag(); // entropy_coding_mode_flag r.ReadFlag(); // bottom_field_pic_order_in_frame_present_flag var groups = (int)r.ReadUe() + 1; if (groups > 1) { var type = r.ReadUe(); switch (type) { case 0: for (var i = 0; i < groups; i++) { r.ReadUe(); } break; case 2: for (var i = 0; i < 2 * (groups - 1); i++) { r.ReadUe(); } break; case 3 or 4 or 5: r.ReadFlag(); r.ReadUe(); break; case 6: { var size = (int)r.ReadUe() + 1; var bitsPerId = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)(groups - 1)); r.Skip(size * bitsPerId); break; } } } r.ReadUe(); // num_ref_idx_l0_default_active_minus1 r.ReadUe(); // num_ref_idx_l1_default_active_minus1 r.ReadFlag(); // weighted_pred_flag r.Read(2); // weighted_bipred_idc r.ReadSe(); // pic_init_qp_minus26 r.ReadSe(); // pic_init_qs_minus26 r.ReadSe(); // chroma_qp_index_offset r.ReadFlag(); // deblocking_filter_control_present_flag r.ReadFlag(); // constrained_intra_pred_flag var flag = r.Position; if (r.ReadFlag()) { throw new InvalidOperationException("Il PPS ha già redundant_pic_cnt_present_flag."); } var bits = new BitWriter(); bits.Copy(nal.Rbsp, 8, flag); bits.Bits(1, 1); bits.Copy(nal.Rbsp, flag + 1, StopBit(nal)); bits.Trailing(); return [nal.Rbsp[0], .. bits.ToArray()]; } }