namespace Febe.Core.Codecs.H265; /// /// What the sequence parameter set of an HEVC stream says without decoding it: the size of the pictures shown, after /// the conformance window (ยง7.4.3.2.1). Used by the container readers whose headers do not carry the size (MPEG program /// streams), as H264StreamInfo is for H.264. /// public static class H265StreamInfo { /// nal_unit_type of a sequence parameter set (table 7-1). private const int SpsType = 33; /// The picture size of an SPS NAL unit (two-byte header included); false when it is not an SPS or is damaged. public static bool TryPictureSize(ReadOnlySpan nal, out int width, out int height) { width = height = 0; if (nal.Length < 4 || (nal[0] & 0x80) != 0 || ((nal[0] >> 1) & 63) != SpsType) { return false; // forbidden_zero_bit set, or not an SPS } try { byte[]? buffer = null; var sps = Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader()); var w = sps.Width - sps.ConfLeft - sps.ConfRight; var h = sps.Height - sps.ConfTop - sps.ConfBottom; if (w <= 0 || h <= 0) { return false; } (width, height) = (w, h); return true; } catch (Exception ex) when (ex is H265Exception or IndexOutOfRangeException or ArgumentException or OverflowException) { return false; } } /// /// The picture size of the first whole SPS of an Annex B byte stream; an SPS that the end of /// cuts counts only when says nothing follows. /// public static bool TryPictureSizeFromAnnexB(ReadOnlySpan stream, bool complete, out int width, out int height) { width = height = 0; ReadOnlySpan startCode = [0, 0, 1]; var found = stream.IndexOf(startCode); while (found >= 0) { var start = found + 3; var next = stream[start..].IndexOf(startCode); if (next < 0 && !complete) { return false; // the last unit may be cut short } var end = next < 0 ? stream.Length : start + next; var nal = stream[start..end]; while (nal.Length > 0 && nal[^1] == 0) { nal = nal[..^1]; // the zero byte of a four-byte start code belongs to the next unit } if (TryPictureSize(nal, out width, out height)) { return true; } found = next < 0 ? -1 : end; } return false; } }