namespace Febe.Core.Codecs.H265;
/// A short-term reference picture set (§7.3.7, §7.4.8): the POC deltas of the negative and positive pictures.
internal sealed class ShortTermRps
{
/// At most sps_max_dec_pic_buffering_minus1 + 1 ≤ 16 pictures in each half.
internal const int MaxPictures = 16;
internal int NumNegative;
internal int NumPositive;
internal readonly int[] DeltaPocS0 = new int[MaxPictures];
internal readonly int[] DeltaPocS1 = new int[MaxPictures];
internal readonly bool[] UsedS0 = new bool[MaxPictures];
internal readonly bool[] UsedS1 = new bool[MaxPictures];
internal int NumDeltaPocs => NumNegative + NumPositive;
///
/// st_ref_pic_set(stRpsIdx): is stRpsIdx, the sets already read
/// from the SPS (all of them when the set is in a slice header, where equals their number).
///
internal static ShortTermRps Parse(BitReader r, int index, int spsCount, IReadOnlyList spsSets)
{
var rps = new ShortTermRps();
var interPrediction = index != 0 && r.ReadFlag();
if (interPrediction)
{
var deltaIdx = index == spsCount ? r.ReadUe(index - 1) + 1 : 1;
var reference = spsSets[index - deltaIdx];
var sign = r.ReadFlag();
var deltaRps = (r.ReadUe(32767) + 1) * (sign ? -1 : 1);
var count = reference.NumDeltaPocs;
Span used = stackalloc bool[(MaxPictures * 2) + 1];
Span useDelta = stackalloc bool[(MaxPictures * 2) + 1];
for (var j = 0; j <= count; j++)
{
used[j] = r.ReadFlag();
useDelta[j] = used[j] || r.ReadFlag();
}
// (7-61) and (7-62).
var i = 0;
for (var j = reference.NumPositive - 1; j >= 0; j--)
{
var dPoc = reference.DeltaPocS1[j] + deltaRps;
if (dPoc < 0 && useDelta[reference.NumNegative + j])
{
rps.Add0(ref i, dPoc, used[reference.NumNegative + j]);
}
}
if (deltaRps < 0 && useDelta[count])
{
rps.Add0(ref i, deltaRps, used[count]);
}
for (var j = 0; j < reference.NumNegative; j++)
{
var dPoc = reference.DeltaPocS0[j] + deltaRps;
if (dPoc < 0 && useDelta[j])
{
rps.Add0(ref i, dPoc, used[j]);
}
}
rps.NumNegative = i;
i = 0;
for (var j = reference.NumNegative - 1; j >= 0; j--)
{
var dPoc = reference.DeltaPocS0[j] + deltaRps;
if (dPoc > 0 && useDelta[j])
{
rps.Add1(ref i, dPoc, used[j]);
}
}
if (deltaRps > 0 && useDelta[count])
{
rps.Add1(ref i, deltaRps, used[count]);
}
for (var j = 0; j < reference.NumPositive; j++)
{
var dPoc = reference.DeltaPocS1[j] + deltaRps;
if (dPoc > 0 && useDelta[reference.NumNegative + j])
{
rps.Add1(ref i, dPoc, used[reference.NumNegative + j]);
}
}
rps.NumPositive = i;
}
else
{
rps.NumNegative = r.ReadUe(MaxPictures);
rps.NumPositive = r.ReadUe(MaxPictures);
if (rps.NumDeltaPocs > MaxPictures)
{
throw new H265Exception("Insieme di riferimento con troppe immagini.");
}
var poc = 0;
for (var i = 0; i < rps.NumNegative; i++)
{
poc -= r.ReadUe(32767) + 1;
rps.DeltaPocS0[i] = poc;
rps.UsedS0[i] = r.ReadFlag();
}
poc = 0;
for (var i = 0; i < rps.NumPositive; i++)
{
poc += r.ReadUe(32767) + 1;
rps.DeltaPocS1[i] = poc;
rps.UsedS1[i] = r.ReadFlag();
}
}
return rps;
}
private void Add0(ref int i, int dPoc, bool used)
{
if (i >= MaxPictures)
{
throw new H265Exception("Insieme di riferimento con troppe immagini.");
}
DeltaPocS0[i] = dPoc;
UsedS0[i++] = used;
}
private void Add1(ref int i, int dPoc, bool used)
{
if (i >= MaxPictures)
{
throw new H265Exception("Insieme di riferimento con troppe immagini.");
}
DeltaPocS1[i] = dPoc;
UsedS1[i++] = used;
}
}
///
/// Scaling factors (§7.3.4, §7.4.5): ScalingFactor[sizeId][matrixId] as raster arrays (y * size + x), sizeId 0 to 3 for
/// 4×4 to 32×32 and matrixId 0 to 5 (intra Y, Cb, Cr, then inter Y, Cb, Cr).
///
internal sealed class ScalingList
{
private ScalingList()
{
}
/// Factors[sizeId * 6 + matrixId].
internal byte[][] Factors { get; } = new byte[24][];
/// The lists when scaling_list_enabled_flag is 1 and no list is sent: table 7-5 and table 7-6.
internal static ScalingList Default()
{
var lists = new byte[24][];
var dc = new int[24];
for (var sizeId = 0; sizeId < 4; sizeId++)
{
for (var matrixId = 0; matrixId < 6; matrixId++)
{
SetDefault(lists, dc, sizeId, matrixId);
}
}
return Build(lists, dc);
}
/// scaling_list_data().
internal static ScalingList Parse(BitReader r)
{
var lists = new byte[24][];
var dc = new int[24];
for (var sizeId = 0; sizeId < 4; sizeId++)
{
var coefNum = Math.Min(64, 1 << (4 + (sizeId << 1)));
for (var matrixId = 0; matrixId < 6; matrixId += sizeId == 3 ? 3 : 1)
{
var id = (sizeId * 6) + matrixId;
if (!r.ReadFlag())
{
// scaling_list_pred_matrix_id_delta: 0 is the default list, otherwise a copy of an earlier one.
var step = sizeId == 3 ? 3 : 1;
var delta = r.ReadUe(matrixId / step);
if (delta == 0)
{
SetDefault(lists, dc, sizeId, matrixId);
}
else
{
var reference = (sizeId * 6) + matrixId - (delta * step);
lists[id] = lists[reference];
dc[id] = dc[reference];
}
}
else
{
var list = new byte[coefNum];
var nextCoef = 8;
if (sizeId > 1)
{
nextCoef = r.ReadSe(-7, 247) + 8;
dc[id] = nextCoef;
}
for (var i = 0; i < coefNum; i++)
{
var delta = r.ReadSe(-128, 127);
nextCoef = (nextCoef + delta + 256) % 256;
list[i] = (byte)nextCoef;
}
lists[id] = list;
if (sizeId <= 1)
{
dc[id] = list[0];
}
}
}
}
// 32×32 chroma lists exist only for ChromaArrayType 3 (§7.3.4): they are those of the 16×16 ones.
foreach (var matrixId in (ReadOnlySpan)[1, 2, 4, 5])
{
lists[18 + matrixId] = lists[12 + matrixId];
dc[18 + matrixId] = dc[12 + matrixId];
}
return Build(lists, dc);
}
private static void SetDefault(byte[][] lists, int[] dc, int sizeId, int matrixId)
{
var id = (sizeId * 6) + matrixId;
if (sizeId == 0)
{
lists[id] = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16];
}
else
{
lists[id] = matrixId < 3 ? H265Tables.DefaultScalingIntra : H265Tables.DefaultScalingInter;
}
dc[id] = 16;
}
/// ScalingFactor from the lists (7-40 to 7-44): lists in diagonal order, upsampled beyond 8×8, with the DC.
private static ScalingList Build(byte[][] lists, int[] dc)
{
var result = new ScalingList();
for (var sizeId = 0; sizeId < 4; sizeId++)
{
var size = 4 << sizeId;
var scan = sizeId == 0 ? H265Tables.ScanOrder[2][0] : H265Tables.ScanOrder[3][0];
var ratio = sizeId <= 1 ? 1 : size / 8;
for (var matrixId = 0; matrixId < 6; matrixId++)
{
var id = (sizeId * 6) + matrixId;
var list = lists[id];
var factors = new byte[size * size];
for (var i = 0; i < list.Length; i++)
{
var x = scan[i] & 0xFF;
var y = scan[i] >> 8;
for (var j = 0; j < ratio; j++)
{
for (var k = 0; k < ratio; k++)
{
factors[((y * ratio) + j) * size + (x * ratio) + k] = list[i];
}
}
}
if (sizeId >= 2)
{
factors[0] = (byte)dc[id];
}
result.Factors[id] = factors;
}
}
return result;
}
}
/// A sequence parameter set (§7.3.2.2), with what decoding needs.
internal sealed class Sps
{
/// MaxLumaPs of level 6.2 (table A.8): the largest picture of any level.
internal const int MaxLumaPs = 35_651_584;
/// Largest width or height of any level: Sqrt(MaxLumaPs × 8).
internal const int MaxDimension = 16_888;
internal int Id;
internal int MaxSubLayersMinus1;
internal int ProfileIdc;
internal int ChromaFormatIdc;
internal bool SeparateColourPlane;
internal int Width;
internal int Height;
internal int ConfLeft, ConfRight, ConfTop, ConfBottom;
internal int BitDepthY;
internal int BitDepthC;
internal int Log2MaxPocLsb;
internal readonly int[] MaxDecPicBufferingMinus1 = new int[8];
internal readonly int[] MaxNumReorderPics = new int[8];
internal readonly int[] MaxLatencyIncreasePlus1 = new int[8];
internal int Log2MinCbSize;
internal int Log2CtbSize;
internal int Log2MinTbSize;
internal int Log2MaxTbSize;
internal int MaxTransformHierarchyDepthInter;
internal int MaxTransformHierarchyDepthIntra;
internal bool ScalingListEnabled;
internal ScalingList? ScalingList;
internal bool AmpEnabled;
internal bool SaoEnabled;
internal bool PcmEnabled;
internal int PcmBitDepthY;
internal int PcmBitDepthC;
internal int Log2MinPcmCbSize;
internal int Log2MaxPcmCbSize;
internal bool PcmLoopFilterDisabled;
internal readonly List ShortTermRpsList = [];
internal bool LongTermRefsPresent;
internal int NumLongTermRefPicsSps;
internal readonly int[] LtRefPicPocLsbSps = new int[32];
internal readonly bool[] UsedByCurrPicLtSps = new bool[32];
internal bool TemporalMvpEnabled;
internal bool StrongIntraSmoothing;
// Range extension (§7.3.2.2.2): every tool is decoded except extended precision and the bypass alignment.
internal bool TransformSkipRotationEnabled;
internal bool TransformSkipContextEnabled;
internal bool ImplicitRdpcmEnabled;
internal bool ExplicitRdpcmEnabled;
internal bool ExtendedPrecisionProcessing;
internal bool IntraSmoothingDisabled;
internal bool HighPrecisionOffsetsEnabled;
internal bool PersistentRiceAdaptationEnabled;
internal bool CabacBypassAlignmentEnabled;
/// VUI colour description: matrix_coeffs (2 = unspecified) and video_full_range_flag.
internal int MatrixCoefficients = 2;
internal bool FullRange;
internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc;
internal int SubWidthC => ChromaFormatIdc is 1 or 2 ? 2 : 1;
internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1;
internal int CtbSize => 1 << Log2CtbSize;
internal int WidthInCtbs => (Width + CtbSize - 1) >> Log2CtbSize;
internal int HeightInCtbs => (Height + CtbSize - 1) >> Log2CtbSize;
internal int CtbCount => WidthInCtbs * HeightInCtbs;
internal int QpBdOffsetY => 6 * (BitDepthY - 8);
internal int QpBdOffsetC => 6 * (BitDepthC - 8);
internal int HighestTid => MaxSubLayersMinus1;
///
/// The range extension tools the decoder does not handle: extended_precision_processing_flag and
/// cabac_bypass_alignment_enabled_flag, which only the 16-bit and High Throughput 4:4:4 profiles use.
///
internal bool UsesUnsupportedTools => ExtendedPrecisionProcessing || CabacBypassAlignmentEnabled;
/// log2 of SubWidthC and SubHeightC (table 6-1).
internal int ChromaShiftX => SubWidthC - 1;
internal int ChromaShiftY => SubHeightC - 1;
internal static Sps Parse(BitReader r)
{
var s = new Sps();
r.Skip(4); // sps_video_parameter_set_id
s.MaxSubLayersMinus1 = r.ReadInt(3);
if (s.MaxSubLayersMinus1 > 6)
{
throw new H265Exception("SPS con troppi sottolivelli temporali.");
}
r.Skip(1); // sps_temporal_id_nesting_flag
s.ProfileIdc = ProfileTierLevel.Skip(r, true, s.MaxSubLayersMinus1);
s.Id = r.ReadUe(15);
s.ChromaFormatIdc = r.ReadUe(3);
if (s.ChromaFormatIdc == 3)
{
s.SeparateColourPlane = r.ReadFlag();
}
s.Width = r.ReadUe(MaxDimension);
s.Height = r.ReadUe(MaxDimension);
if (s.Width == 0 || s.Height == 0 || (long)s.Width * s.Height > MaxLumaPs)
{
throw new H265Exception("Dimensioni dell'immagine HEVC non valide.");
}
if (r.ReadFlag())
{
s.ConfLeft = r.ReadUe(MaxDimension) * s.SubWidthC;
s.ConfRight = r.ReadUe(MaxDimension) * s.SubWidthC;
s.ConfTop = r.ReadUe(MaxDimension) * s.SubHeightC;
s.ConfBottom = r.ReadUe(MaxDimension) * s.SubHeightC;
if (s.ConfLeft + s.ConfRight >= s.Width || s.ConfTop + s.ConfBottom >= s.Height)
{
throw new H265Exception("Finestra di conformità che non lascia immagine.");
}
}
s.BitDepthY = r.ReadUe(8) + 8;
s.BitDepthC = r.ReadUe(8) + 8;
s.Log2MaxPocLsb = r.ReadUe(12) + 4;
var orderingInfo = r.ReadFlag();
for (var i = orderingInfo ? 0 : s.MaxSubLayersMinus1; i <= s.MaxSubLayersMinus1; i++)
{
s.MaxDecPicBufferingMinus1[i] = r.ReadUe(15);
s.MaxNumReorderPics[i] = r.ReadUe(s.MaxDecPicBufferingMinus1[i]);
s.MaxLatencyIncreasePlus1[i] = (int)Math.Min(r.ReadUe(), int.MaxValue);
}
if (!orderingInfo)
{
for (var i = 0; i < s.MaxSubLayersMinus1; i++)
{
s.MaxDecPicBufferingMinus1[i] = s.MaxDecPicBufferingMinus1[s.MaxSubLayersMinus1];
s.MaxNumReorderPics[i] = s.MaxNumReorderPics[s.MaxSubLayersMinus1];
s.MaxLatencyIncreasePlus1[i] = s.MaxLatencyIncreasePlus1[s.MaxSubLayersMinus1];
}
}
s.Log2MinCbSize = r.ReadUe(3) + 3;
s.Log2CtbSize = s.Log2MinCbSize + r.ReadUe(3);
s.Log2MinTbSize = r.ReadUe(3) + 2;
s.Log2MaxTbSize = s.Log2MinTbSize + r.ReadUe(3);
if (s.Log2CtbSize > 6 || s.Log2CtbSize < 4 || s.Log2MinTbSize >= s.Log2MinCbSize || s.Log2MaxTbSize > Math.Min(s.Log2CtbSize, 5)
|| s.Width % (1 << s.Log2MinCbSize) != 0 || s.Height % (1 << s.Log2MinCbSize) != 0)
{
throw new H265Exception("Dimensioni dei blocchi HEVC non valide.");
}
s.MaxTransformHierarchyDepthInter = r.ReadUe(s.Log2CtbSize - s.Log2MinTbSize);
s.MaxTransformHierarchyDepthIntra = r.ReadUe(s.Log2CtbSize - s.Log2MinTbSize);
s.ScalingListEnabled = r.ReadFlag();
if (s.ScalingListEnabled)
{
s.ScalingList = r.ReadFlag() ? ScalingList.Parse(r) : ScalingList.Default();
}
s.AmpEnabled = r.ReadFlag();
s.SaoEnabled = r.ReadFlag();
s.PcmEnabled = r.ReadFlag();
if (s.PcmEnabled)
{
s.PcmBitDepthY = r.ReadInt(4) + 1;
s.PcmBitDepthC = r.ReadInt(4) + 1;
s.Log2MinPcmCbSize = r.ReadUe(2) + 3;
s.Log2MaxPcmCbSize = s.Log2MinPcmCbSize + r.ReadUe(2);
s.PcmLoopFilterDisabled = r.ReadFlag();
if (s.PcmBitDepthY > s.BitDepthY || s.PcmBitDepthC > s.BitDepthC || s.Log2MaxPcmCbSize > Math.Min(s.Log2CtbSize, 5))
{
throw new H265Exception("Parametri PCM non validi.");
}
}
var count = r.ReadUe(64);
for (var i = 0; i < count; i++)
{
s.ShortTermRpsList.Add(ShortTermRps.Parse(r, i, count, s.ShortTermRpsList));
}
s.LongTermRefsPresent = r.ReadFlag();
if (s.LongTermRefsPresent)
{
s.NumLongTermRefPicsSps = r.ReadUe(32);
for (var i = 0; i < s.NumLongTermRefPicsSps; i++)
{
s.LtRefPicPocLsbSps[i] = r.ReadInt(s.Log2MaxPocLsb);
s.UsedByCurrPicLtSps[i] = r.ReadFlag();
}
}
s.TemporalMvpEnabled = r.ReadFlag();
s.StrongIntraSmoothing = r.ReadFlag();
if (r.ReadFlag())
{
Vui.Parse(r, s);
}
if (r.ReadFlag())
{
var range = r.ReadFlag();
r.Skip(7); // sps_multilayer_extension_flag, sps_3d_extension_flag, sps_scc_extension_flag, sps_extension_4bits
if (range)
{
s.TransformSkipRotationEnabled = r.ReadFlag();
s.TransformSkipContextEnabled = r.ReadFlag();
s.ImplicitRdpcmEnabled = r.ReadFlag();
s.ExplicitRdpcmEnabled = r.ReadFlag();
s.ExtendedPrecisionProcessing = r.ReadFlag();
s.IntraSmoothingDisabled = r.ReadFlag();
s.HighPrecisionOffsetsEnabled = r.ReadFlag();
s.PersistentRiceAdaptationEnabled = r.ReadFlag();
s.CabacBypassAlignmentEnabled = r.ReadFlag();
}
// Other extensions (multilayer, 3D, screen content) are not decoded: their data is ignored.
}
return s;
}
}
/// profile_tier_level() (§7.3.3): skipped, except general_profile_idc.
internal static class ProfileTierLevel
{
internal static int Skip(BitReader r, bool profilePresent, int maxSubLayersMinus1)
{
var profileIdc = 0;
if (profilePresent)
{
r.Skip(3); // general_profile_space, general_tier_flag
profileIdc = r.ReadInt(5);
r.Skip(32 + 48); // compatibility flags, constraint flags
}
r.Skip(8); // general_level_idc
Span profile = stackalloc bool[8];
Span level = stackalloc bool[8];
for (var i = 0; i < maxSubLayersMinus1; i++)
{
profile[i] = r.ReadFlag();
level[i] = r.ReadFlag();
}
if (maxSubLayersMinus1 > 0)
{
r.Skip(2 * (8 - maxSubLayersMinus1));
}
for (var i = 0; i < maxSubLayersMinus1; i++)
{
if (profile[i])
{
r.Skip(88);
}
if (level[i])
{
r.Skip(8);
}
}
return profileIdc;
}
}
/// vui_parameters() (Annex E): only the colour description is kept.
internal static class Vui
{
internal static void Parse(BitReader r, Sps s)
{
if (r.ReadFlag() && r.ReadInt(8) == 255)
{
r.Skip(32); // sar_width, sar_height
}
if (r.ReadFlag())
{
r.Skip(1); // overscan_appropriate_flag
}
if (r.ReadFlag())
{
r.Skip(3); // video_format
s.FullRange = r.ReadFlag();
if (r.ReadFlag())
{
r.Skip(16); // colour_primaries, transfer_characteristics
s.MatrixCoefficients = r.ReadInt(8);
}
}
if (r.ReadFlag())
{
r.ReadUe();
r.ReadUe();
}
r.Skip(3); // neutral_chroma_indication_flag, field_seq_flag, frame_field_info_present_flag
if (r.ReadFlag())
{
for (var i = 0; i < 4; i++)
{
r.ReadUe(); // default display window
}
}
if (r.ReadFlag())
{
r.Skip(64); // vui_num_units_in_tick, vui_time_scale
if (r.ReadFlag())
{
r.ReadUe(); // vui_num_ticks_poc_diff_one_minus1
}
if (r.ReadFlag())
{
Hrd(r, true, s.MaxSubLayersMinus1);
}
}
if (r.ReadFlag())
{
r.Skip(3); // tiles_fixed_structure_flag, motion_vectors_over_pic_boundaries_flag, restricted_ref_pic_lists_flag
for (var i = 0; i < 5; i++)
{
r.ReadUe();
}
}
}
/// hrd_parameters() (E.2.2), skipped.
internal static void Hrd(BitReader r, bool commonInfo, int maxSubLayersMinus1)
{
bool nal = false, vcl = false, subPic = false;
if (commonInfo)
{
nal = r.ReadFlag();
vcl = r.ReadFlag();
if (nal || vcl)
{
subPic = r.ReadFlag();
if (subPic)
{
r.Skip(8 + 5 + 1 + 5);
}
r.Skip(8); // bit_rate_scale, cpb_size_scale
if (subPic)
{
r.Skip(4);
}
r.Skip(15);
}
}
for (var i = 0; i <= maxSubLayersMinus1; i++)
{
var fixedGeneral = r.ReadFlag();
var fixedWithinCvs = fixedGeneral || r.ReadFlag();
var lowDelay = false;
if (fixedWithinCvs)
{
r.ReadUe();
}
else
{
lowDelay = r.ReadFlag();
}
var cpbCount = lowDelay ? 1 : r.ReadUe(31) + 1;
for (var k = (nal ? 1 : 0) + (vcl ? 1 : 0); k > 0; k--)
{
for (var j = 0; j < cpbCount; j++)
{
r.ReadUe();
r.ReadUe();
if (subPic)
{
r.ReadUe();
r.ReadUe();
}
r.Skip(1);
}
}
}
}
}
/// A picture parameter set (§7.3.2.3), with what decoding needs.
internal sealed class Pps
{
internal int Id;
internal int SpsId;
internal bool DependentSliceSegmentsEnabled;
internal bool OutputFlagPresent;
internal int NumExtraSliceHeaderBits;
internal bool SignDataHidingEnabled;
internal bool CabacInitPresent;
internal int NumRefIdxL0DefaultActive;
internal int NumRefIdxL1DefaultActive;
internal int InitQp;
internal bool ConstrainedIntraPred;
internal bool TransformSkipEnabled;
internal bool CuQpDeltaEnabled;
internal int DiffCuQpDeltaDepth;
internal int CbQpOffset;
internal int CrQpOffset;
internal bool SliceChromaQpOffsetsPresent;
internal bool WeightedPred;
internal bool WeightedBipred;
internal bool TransquantBypassEnabled;
internal bool TilesEnabled;
internal bool EntropyCodingSyncEnabled;
internal int NumTileColumns = 1;
internal int NumTileRows = 1;
internal bool UniformSpacing = true;
internal int[] ColumnWidths = [];
internal int[] RowHeights = [];
internal bool LoopFilterAcrossTilesEnabled = true;
internal bool LoopFilterAcrossSlicesEnabled;
internal bool DeblockingFilterOverrideEnabled;
internal bool DeblockingFilterDisabled;
internal int BetaOffsetDiv2;
internal int TcOffsetDiv2;
internal ScalingList? ScalingList;
internal bool ListsModificationPresent;
internal int Log2ParallelMergeLevel;
internal bool SliceSegmentHeaderExtensionPresent;
// Range extension (§7.3.2.3.2).
internal int Log2MaxTransformSkipSize = 2;
internal bool CrossComponentPredictionEnabled;
internal bool ChromaQpOffsetListEnabled;
internal int DiffCuChromaQpOffsetDepth;
internal int ChromaQpOffsetListLength;
internal readonly int[] CbQpOffsetList = new int[6];
internal readonly int[] CrQpOffsetList = new int[6];
internal int Log2SaoOffsetScaleLuma;
internal int Log2SaoOffsetScaleChroma;
/// The tile layout of the SPS the arrays below were computed for.
private Sps? layoutSps;
/// CtbAddrRsToTs, CtbAddrTsToRs and TileId (by raster address) of §6.5.1.
internal int[] CtbAddrRsToTs = [];
internal int[] CtbAddrTsToRs = [];
internal int[] TileIdRs = [];
/// colBd and rowBd: the first CTB column and row of each tile, with one more entry for the end.
internal int[] ColBd = [];
internal int[] RowBd = [];
internal static Pps Parse(BitReader r)
{
var p = new Pps
{
Id = r.ReadUe(63),
SpsId = r.ReadUe(15),
DependentSliceSegmentsEnabled = r.ReadFlag(),
OutputFlagPresent = r.ReadFlag(),
NumExtraSliceHeaderBits = r.ReadInt(3),
SignDataHidingEnabled = r.ReadFlag(),
CabacInitPresent = r.ReadFlag(),
NumRefIdxL0DefaultActive = r.ReadUe(14) + 1,
NumRefIdxL1DefaultActive = r.ReadUe(14) + 1,
InitQp = 26 + r.ReadSe(-26 - 36, 25),
ConstrainedIntraPred = r.ReadFlag(),
TransformSkipEnabled = r.ReadFlag(),
CuQpDeltaEnabled = r.ReadFlag(),
};
if (p.CuQpDeltaEnabled)
{
p.DiffCuQpDeltaDepth = r.ReadUe(3);
}
p.CbQpOffset = r.ReadSe(-12, 12);
p.CrQpOffset = r.ReadSe(-12, 12);
p.SliceChromaQpOffsetsPresent = r.ReadFlag();
p.WeightedPred = r.ReadFlag();
p.WeightedBipred = r.ReadFlag();
p.TransquantBypassEnabled = r.ReadFlag();
p.TilesEnabled = r.ReadFlag();
p.EntropyCodingSyncEnabled = r.ReadFlag();
if (p.TilesEnabled)
{
p.NumTileColumns = r.ReadUe(1055) + 1;
p.NumTileRows = r.ReadUe(1055) + 1;
p.UniformSpacing = r.ReadFlag();
if (!p.UniformSpacing)
{
p.ColumnWidths = new int[p.NumTileColumns];
p.RowHeights = new int[p.NumTileRows];
for (var i = 0; i < p.NumTileColumns - 1; i++)
{
p.ColumnWidths[i] = r.ReadUe(1055) + 1;
}
for (var i = 0; i < p.NumTileRows - 1; i++)
{
p.RowHeights[i] = r.ReadUe(1055) + 1;
}
}
p.LoopFilterAcrossTilesEnabled = r.ReadFlag();
}
p.LoopFilterAcrossSlicesEnabled = r.ReadFlag();
if (r.ReadFlag())
{
p.DeblockingFilterOverrideEnabled = r.ReadFlag();
p.DeblockingFilterDisabled = r.ReadFlag();
if (!p.DeblockingFilterDisabled)
{
p.BetaOffsetDiv2 = r.ReadSe(-6, 6);
p.TcOffsetDiv2 = r.ReadSe(-6, 6);
}
}
if (r.ReadFlag())
{
p.ScalingList = ScalingList.Parse(r);
}
p.ListsModificationPresent = r.ReadFlag();
p.Log2ParallelMergeLevel = r.ReadUe(4) + 2;
p.SliceSegmentHeaderExtensionPresent = r.ReadFlag();
if (r.ReadFlag())
{
var range = r.ReadFlag();
r.Skip(7); // pps_multilayer_extension_flag, pps_3d_extension_flag, pps_scc_extension_flag, pps_extension_4bits
if (range)
{
if (p.TransformSkipEnabled)
{
p.Log2MaxTransformSkipSize = r.ReadUe(3) + 2;
}
p.CrossComponentPredictionEnabled = r.ReadFlag();
p.ChromaQpOffsetListEnabled = r.ReadFlag();
if (p.ChromaQpOffsetListEnabled)
{
p.DiffCuChromaQpOffsetDepth = r.ReadUe(3);
p.ChromaQpOffsetListLength = r.ReadUe(5) + 1;
for (var i = 0; i < p.ChromaQpOffsetListLength; i++)
{
p.CbQpOffsetList[i] = r.ReadSe(-12, 12);
p.CrQpOffsetList[i] = r.ReadSe(-12, 12);
}
}
p.Log2SaoOffsetScaleLuma = r.ReadUe(6);
p.Log2SaoOffsetScaleChroma = r.ReadUe(6);
}
}
return p;
}
/// Computes the tile layout and the scan conversions of §6.5.1 for , once.
internal void Activate(Sps sps)
{
if (ReferenceEquals(layoutSps, sps))
{
return;
}
int w = sps.WidthInCtbs, h = sps.HeightInCtbs;
if (NumTileColumns > w || NumTileRows > h)
{
throw new H265Exception("Più tile che CTB.");
}
var colWidth = new int[NumTileColumns];
var rowHeight = new int[NumTileRows];
if (UniformSpacing)
{
for (var i = 0; i < NumTileColumns; i++)
{
colWidth[i] = ((i + 1) * w / NumTileColumns) - (i * w / NumTileColumns);
}
for (var j = 0; j < NumTileRows; j++)
{
rowHeight[j] = ((j + 1) * h / NumTileRows) - (j * h / NumTileRows);
}
}
else
{
var rest = w;
for (var i = 0; i < NumTileColumns - 1; i++)
{
colWidth[i] = ColumnWidths[i];
rest -= colWidth[i];
}
colWidth[NumTileColumns - 1] = rest;
rest = h;
for (var j = 0; j < NumTileRows - 1; j++)
{
rowHeight[j] = RowHeights[j];
rest -= rowHeight[j];
}
rowHeight[NumTileRows - 1] = rest;
if (colWidth[NumTileColumns - 1] <= 0 || rowHeight[NumTileRows - 1] <= 0)
{
throw new H265Exception("Tile più larghe dell'immagine.");
}
}
ColBd = new int[NumTileColumns + 1];
RowBd = new int[NumTileRows + 1];
for (var i = 0; i < NumTileColumns; i++)
{
ColBd[i + 1] = ColBd[i] + colWidth[i];
}
for (var j = 0; j < NumTileRows; j++)
{
RowBd[j + 1] = RowBd[j] + rowHeight[j];
}
var count = w * h;
CtbAddrRsToTs = new int[count];
CtbAddrTsToRs = new int[count];
TileIdRs = new int[count];
for (var rs = 0; rs < count; rs++)
{
int tbX = rs % w, tbY = rs / w;
int tileX = 0, tileY = 0;
for (var i = 0; i < NumTileColumns; i++)
{
if (tbX >= ColBd[i])
{
tileX = i;
}
}
for (var j = 0; j < NumTileRows; j++)
{
if (tbY >= RowBd[j])
{
tileY = j;
}
}
var v = 0;
for (var i = 0; i < tileX; i++)
{
v += rowHeight[tileY] * colWidth[i];
}
for (var j = 0; j < tileY; j++)
{
v += w * rowHeight[j];
}
v += ((tbY - RowBd[tileY]) * colWidth[tileX]) + tbX - ColBd[tileX];
CtbAddrRsToTs[rs] = v;
CtbAddrTsToRs[v] = rs;
TileIdRs[rs] = (tileY * NumTileColumns) + tileX;
}
layoutSps = sps;
}
}