HEVC e HEIF: limiti di memoria contro i file danneggiati e correzioni della revisione (#58)
Un flusso HEVC di pochi byte poteva far allocare gigabyte: ora un SPS il cui buffer supera il MaxDpbSize del livello 6.2 è rifiutato, il buffer non cresce oltre quanto l'SPS dichiara e una sola immagine grigia, riusata, sta per ogni riferimento mancante (il POC viaggia nelle liste). Nei file HEIF ogni immagine deve avere la dimensione del suo ispe, controllata dal decodificatore prima di allocare; i riquadri di una griglia devono coprire l'uscita senza traboccare, i loro byte non superano il file né MaxTotalBytes, e ciò che va storto nei riquadri decodificati in parallelo esce come HeifException. Inoltre: SPS e PPS ripetuti identici dentro un'immagine sono accettati (7.4.2.4.4) e uno cambiato vale dall'immagine dopo; le estensioni SCC sono rifiutate subito; l'intervallo di luma_offset segue l'alta precisione; YCgCo convertito, le altre matrici approssimate e documentate. «Oggetto» e «riquadro» al posto di «elemento» e «tessera» per HEIF (glossario). Righe nuove in decisioni.md: limiti, righe superate, consegne al binario dei documenti, piano per NSIS, Node e tini. Prove nuove su flussi HEVC scritti bit per bit con un codificatore CABAC di prova, su file HEIF costruiti apposta e sulla conversione YCgCo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ac85d1baed
commit
7b10f4ad4c
16 files changed
+1389
-131
No files matched your search
@@ -94,11 +94,11 @@ public sealed partial class H265Decoder
|
||||
{
|
||||
var entry = temp[h.ListModification[list] ? h.ListEntry[list][i] : i];
|
||||
var longTerm = entry >= before + after;
|
||||
var picture = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after];
|
||||
var (picture, refPoc) = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after];
|
||||
h.RefPicList[list][i] = picture;
|
||||
h.RefPoc[list][i] = picture.Poc;
|
||||
h.RefPoc[list][i] = refPoc;
|
||||
h.RefIsLongTerm[list][i] = longTerm;
|
||||
h.NoBackwardPred &= picture.Poc <= cur!.Poc;
|
||||
h.NoBackwardPred &= refPoc <= cur!.Poc;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +307,7 @@ public sealed partial class H265Decoder
|
||||
var motion = cur!.Motion;
|
||||
var target = slice.RefPicList[x][refIdx];
|
||||
var targetLongTerm = slice.RefIsLongTerm[x][refIdx];
|
||||
var targetPoc = slice.RefPoc[x][refIdx];
|
||||
var poc = cur.Poc;
|
||||
|
||||
// A: A0 then A1.
|
||||
@@ -328,7 +329,7 @@ public sealed partial class H265Decoder
|
||||
{
|
||||
if (k == 0 ? availableA0 : availableA1)
|
||||
{
|
||||
flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, target, targetLongTerm, poc, out ax, out ay);
|
||||
flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, targetPoc, targetLongTerm, poc, out ax, out ay);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,7 +362,7 @@ public sealed partial class H265Decoder
|
||||
{
|
||||
if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2)
|
||||
{
|
||||
flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, target, targetLongTerm, poc, out bx, out by);
|
||||
flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, targetPoc, targetLongTerm, poc, out bx, out by);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -434,7 +435,7 @@ public sealed partial class H265Decoder
|
||||
/// The second conditions of §8.5.3.2.7: a neighbour whose reference is long-term exactly when the target is, its
|
||||
/// vector scaled by the POC distances when both are short-term.
|
||||
/// </summary>
|
||||
private bool ScaledCandidate(in MvField n, int x, Picture target, bool targetLongTerm, int poc, out int mx, out int my)
|
||||
private bool ScaledCandidate(in MvField n, int x, int targetPoc, bool targetLongTerm, int poc, out int mx, out int my)
|
||||
{
|
||||
for (var pass = 0; pass < 2; pass++)
|
||||
{
|
||||
@@ -450,7 +451,7 @@ public sealed partial class H265Decoder
|
||||
if (!targetLongTerm)
|
||||
{
|
||||
var td = Math.Clamp(poc - slice.RefPoc[list][refIdx], -128, 127);
|
||||
var tb = Math.Clamp(poc - target.Poc, -128, 127);
|
||||
var tb = Math.Clamp(poc - targetPoc, -128, 127);
|
||||
if (td != 0)
|
||||
{
|
||||
mx = ScaleMv(mx, td, tb);
|
||||
|
||||
@@ -22,8 +22,10 @@ public enum H265AccessPoint
|
||||
/// motion vector prediction, weighted prediction), deblocking and SAO, and the range extension tools (cross-component
|
||||
/// prediction, implicit and explicit RDPCM, transform skip rotation and contexts, persistent Rice adaptation, chroma QP
|
||||
/// offset lists, intra smoothing disabled, high precision offsets). Not handled (an <see cref="H265Exception"/>): extended
|
||||
/// precision processing, the CABAC bypass alignment, separate colour planes, bit depths above 12; the layers above 0 of
|
||||
/// scalable and multiview streams are ignored.
|
||||
/// precision processing, the CABAC bypass alignment, the screen content coding extensions (SCC), separate colour planes,
|
||||
/// bit depths above 12; the layers above 0 of scalable and multiview streams are ignored. Against damaged streams the
|
||||
/// decoded picture buffer is bounded by the SPS (itself bounded by level 6.2) and one generated picture stands for every
|
||||
/// missing reference.
|
||||
/// </summary>
|
||||
public sealed partial class H265Decoder
|
||||
{
|
||||
@@ -53,12 +55,31 @@ public sealed partial class H265Decoder
|
||||
private bool skipping;
|
||||
|
||||
/// <summary>
|
||||
/// The three lists of the reference picture set that the current picture uses (§8.3.2), a generated picture in place
|
||||
/// of "no reference picture" (§8.3.3).
|
||||
/// The three lists of the reference picture set that the current picture uses (§8.3.2), each picture with the POC the
|
||||
/// set gives it; the generated picture <see cref="missing"/> in place of every "no reference picture" (§8.3.3).
|
||||
/// </summary>
|
||||
private readonly List<Picture> refStCurrBefore = [];
|
||||
private readonly List<Picture> refStCurrAfter = [];
|
||||
private readonly List<Picture> refLtCurr = [];
|
||||
private readonly List<(Picture Picture, int Poc)> refStCurrBefore = [];
|
||||
private readonly List<(Picture Picture, int Poc)> refStCurrAfter = [];
|
||||
private readonly List<(Picture Picture, int Poc)> refLtCurr = [];
|
||||
|
||||
/// <summary>
|
||||
/// The picture that stands for every missing reference (§8.3.3.2), made once for a size, chroma format and bit depth
|
||||
/// and shared: a damaged stream that names dozens of missing references costs one picture, not one each.
|
||||
/// </summary>
|
||||
private Picture? missing;
|
||||
|
||||
/// <summary>
|
||||
/// SPS and PPS that came, with an ID the current picture uses and a different content, between its slice segments:
|
||||
/// they apply from the next picture (§7.4.2.4.4), and are installed when the current one is finished.
|
||||
/// </summary>
|
||||
private readonly List<Sps> pendingSps = [];
|
||||
private readonly List<Pps> pendingPps = [];
|
||||
|
||||
/// <summary>
|
||||
/// Pictures the DPB may hold beyond sps_max_dec_pic_buffering_minus1 + 1 before the stream is refused: a conforming
|
||||
/// stream never needs it (C.5.2.2), a damaged one that keeps every picture as a reference cannot grow it further.
|
||||
/// </summary>
|
||||
private const int DpbMargin = 1;
|
||||
|
||||
/// <summary>Raised for each frame in output order (the bumping process of C.5.2.4), cropped.</summary>
|
||||
public event Action<H265Frame>? FrameOutput;
|
||||
@@ -79,6 +100,13 @@ public sealed partial class H265Decoder
|
||||
/// <summary>Coded pictures met so far, also those skipped.</summary>
|
||||
public long PicturesDecoded => codedPictures;
|
||||
|
||||
/// <summary>
|
||||
/// The size every picture must have once cropped (a HEIF image of known <c>ispe</c>), or null for any size the
|
||||
/// levels allow. A picture of another size, or coded much larger than it (a conformance window that throws most of
|
||||
/// it away), is refused with an <see cref="H265Exception"/> before anything of its size is allocated.
|
||||
/// </summary>
|
||||
public (int Width, int Height)? ExpectedFrameSize { get; set; }
|
||||
|
||||
/// <summary>Decodes a whole Annex B byte stream, then outputs every picture left.</summary>
|
||||
public void DecodeAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
@@ -232,18 +260,11 @@ public sealed partial class H265Decoder
|
||||
DecodeSlice(H265NalUnit.Unescape(bytes, ref rbsp));
|
||||
break;
|
||||
case 33:
|
||||
{
|
||||
var sps = Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader());
|
||||
spss[sps.Id] = sps;
|
||||
break;
|
||||
}
|
||||
|
||||
InstallSps(Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader()));
|
||||
break;
|
||||
case 34:
|
||||
{
|
||||
var pps = Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader());
|
||||
ppss[pps.Id] = pps;
|
||||
break;
|
||||
}
|
||||
InstallPps(Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader()));
|
||||
break;
|
||||
|
||||
case 35: // access unit delimiter
|
||||
FinishPicture();
|
||||
@@ -284,7 +305,7 @@ public sealed partial class H265Decoder
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (!ReferenceEquals(s, sps) || !ReferenceEquals(p, pps))
|
||||
else if (!s.SameContent(sps) || !p.SameContent(pps))
|
||||
{
|
||||
throw new H265Exception("Parametri diversi fra le slice di un'immagine.");
|
||||
}
|
||||
@@ -335,6 +356,21 @@ public sealed partial class H265Decoder
|
||||
throw new H265Exception("La precisione estesa e l'allineamento CABAC delle estensioni di formato HEVC non sono gestiti.");
|
||||
}
|
||||
|
||||
if (s.UsesScreenContentCoding || p.SccExtension)
|
||||
{
|
||||
throw new H265Exception("Le estensioni HEVC per i contenuti dello schermo (SCC) non sono gestite.");
|
||||
}
|
||||
|
||||
if (ExpectedFrameSize is { } expected)
|
||||
{
|
||||
// A conformance window crops at most what pads the picture to its coding blocks (at most 63 samples).
|
||||
int width = s.Width - s.ConfLeft - s.ConfRight, height = s.Height - s.ConfTop - s.ConfBottom;
|
||||
if (width != expected.Width || height != expected.Height || s.Width - width > 63 || s.Height - height > 63)
|
||||
{
|
||||
throw new H265Exception("Immagine HEVC di dimensioni diverse da quelle attese.");
|
||||
}
|
||||
}
|
||||
|
||||
p.Activate(s);
|
||||
|
||||
// Picture order count (§8.3.1).
|
||||
@@ -400,6 +436,13 @@ public sealed partial class H265Decoder
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing left to output and still no room: every picture is kept as a reference, which a conforming stream
|
||||
// never does. Without this bound a damaged one would keep up to 48 pictures (16 short-term, 32 long-term).
|
||||
if (dpb.Count > s.MaxDecPicBufferingMinus1[t] + DpbMargin)
|
||||
{
|
||||
throw new H265Exception("Più immagini di riferimento di quante ne tiene il buffer dell'SPS.");
|
||||
}
|
||||
}
|
||||
|
||||
firstPicture = false;
|
||||
@@ -468,7 +511,7 @@ public sealed partial class H265Decoder
|
||||
|
||||
if (h.UsedByCurrPicLt[i])
|
||||
{
|
||||
refLtCurr.Add(found >= 0 ? dpb[found] : MissingReference(s, pocLt));
|
||||
refLtCurr.Add(found >= 0 ? (dpb[found], dpb[found].Poc) : (MissingReference(s), pocLt));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,7 +522,7 @@ public sealed partial class H265Decoder
|
||||
var picture = FindShortTerm(poc + rps.DeltaPocS0[i], keep);
|
||||
if (rps.UsedS0[i])
|
||||
{
|
||||
refStCurrBefore.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS0[i]));
|
||||
refStCurrBefore.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS0[i]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,7 +531,7 @@ public sealed partial class H265Decoder
|
||||
var picture = FindShortTerm(poc + rps.DeltaPocS1[i], keep);
|
||||
if (rps.UsedS1[i])
|
||||
{
|
||||
refStCurrAfter.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS1[i]));
|
||||
refStCurrAfter.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS1[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -504,19 +547,89 @@ public sealed partial class H265Decoder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A picture for a reference that is not in the DPB (§8.3.3.2): every sample at the middle of its range, every block
|
||||
/// intra. It is not put in the DPB and never output; only damaged or cut streams need one.
|
||||
/// The picture for a reference that is not in the DPB (§8.3.3.2): every sample at the middle of its range, every block
|
||||
/// intra. It is not put in the DPB and never output; only damaged or cut streams need one. One picture serves every
|
||||
/// missing reference of the same size and bit depth (its POC travels in the reference lists, not in the picture):
|
||||
/// it is never written, and a stream that names 48 missing references allocates it once.
|
||||
/// </summary>
|
||||
private static Picture MissingReference(Sps s, int poc)
|
||||
private Picture MissingReference(Sps s)
|
||||
{
|
||||
var picture = new Picture(s) { Poc = poc, Generated = true };
|
||||
picture.Planes[0].AsSpan().Fill((ushort)(1 << (s.BitDepthY - 1)));
|
||||
picture.Planes[1].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
|
||||
picture.Planes[2].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
|
||||
picture.Motion.AsSpan().Fill(MvField.Intra);
|
||||
var picture = missing;
|
||||
if (picture is null || !picture.Fits(s) || picture.Sps.BitDepthY != s.BitDepthY || picture.Sps.BitDepthC != s.BitDepthC)
|
||||
{
|
||||
picture = new Picture(s) { Generated = true };
|
||||
picture.Planes[0].AsSpan().Fill((ushort)(1 << (s.BitDepthY - 1)));
|
||||
picture.Planes[1].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
|
||||
picture.Planes[2].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1)));
|
||||
picture.Motion.AsSpan().Fill(MvField.Intra);
|
||||
missing = picture;
|
||||
}
|
||||
|
||||
picture.Sps = s;
|
||||
return picture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes a new SPS. An identical copy of the one in place is dropped, so the active object stays (§7.4.2.4.4 lets a
|
||||
/// stream repeat it anywhere in an access unit); one that carries the ID of the current picture's SPS waits until
|
||||
/// that picture is finished.
|
||||
/// </summary>
|
||||
private void InstallSps(Sps s)
|
||||
{
|
||||
if (cur is not null && s.Id == sps.Id)
|
||||
{
|
||||
if (pendingSps.Count > 0 || !s.SameContent(spss[s.Id]))
|
||||
{
|
||||
pendingSps.RemoveAll(x => x.Id == s.Id);
|
||||
pendingSps.Add(s);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!s.SameContent(spss[s.Id]))
|
||||
{
|
||||
spss[s.Id] = s;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Takes a new PPS, as <see cref="InstallSps"/> does.</summary>
|
||||
private void InstallPps(Pps p)
|
||||
{
|
||||
if (cur is not null && p.Id == pps.Id)
|
||||
{
|
||||
if (pendingPps.Count > 0 || !p.SameContent(ppss[p.Id]))
|
||||
{
|
||||
pendingPps.RemoveAll(x => x.Id == p.Id);
|
||||
pendingPps.Add(p);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!p.SameContent(ppss[p.Id]))
|
||||
{
|
||||
ppss[p.Id] = p;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Installs the parameter sets that waited for the end of the picture.</summary>
|
||||
private void InstallPending()
|
||||
{
|
||||
foreach (var s in pendingSps)
|
||||
{
|
||||
spss[s.Id] = s;
|
||||
}
|
||||
|
||||
foreach (var p in pendingPps)
|
||||
{
|
||||
ppss[p.Id] = p;
|
||||
}
|
||||
|
||||
pendingSps.Clear();
|
||||
pendingPps.Clear();
|
||||
}
|
||||
|
||||
private Picture? FindShortTerm(int poc, Span<bool> keep)
|
||||
{
|
||||
for (var k = 0; k < dpb.Count; k++)
|
||||
@@ -619,6 +732,7 @@ public sealed partial class H265Decoder
|
||||
|
||||
var picture = cur;
|
||||
cur = null;
|
||||
InstallPending();
|
||||
picture.IntraOnly = true;
|
||||
foreach (var header in slices)
|
||||
{
|
||||
|
||||
@@ -298,6 +298,9 @@ internal sealed class Sps
|
||||
/// <summary>Largest width or height of any level: Sqrt(MaxLumaPs × 8).</summary>
|
||||
internal const int MaxDimension = 16_888;
|
||||
|
||||
/// <summary>The RBSP after the NAL unit header, without trailing zero bytes: what "the same content" compares.</summary>
|
||||
internal byte[] Raw = [];
|
||||
|
||||
internal int Id;
|
||||
internal int MaxSubLayersMinus1;
|
||||
internal int ProfileIdc;
|
||||
@@ -372,12 +375,36 @@ internal sealed class Sps
|
||||
|
||||
internal int HighestTid => MaxSubLayersMinus1;
|
||||
|
||||
/// <summary>sps_scc_extension_flag: the screen content coding tools (palette, adaptive colour transform, ...).</summary>
|
||||
internal bool SccExtension;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal bool UsesUnsupportedTools => ExtendedPrecisionProcessing || CabacBypassAlignmentEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// The screen content coding extensions (§7.3.2.2.3; profiles 9, Screen-Extended, and 11, High Throughput
|
||||
/// Screen-Extended, of A.3.7), whose coding units have a syntax the decoder does not read: palette mode, adaptive
|
||||
/// colour transform, the current picture as a reference. The High Throughput 4:4:4 profiles (5) are not refused on
|
||||
/// their own: their tools beyond RExt are those of <see cref="UsesUnsupportedTools"/>.
|
||||
/// </summary>
|
||||
internal bool UsesScreenContentCoding => SccExtension || ProfileIdc is 9 or 11;
|
||||
|
||||
/// <summary>
|
||||
/// MaxDpbSize of A.4.2 for a picture of <paramref name="pictureSize"/> luma samples at level 6.2, the largest of any
|
||||
/// level: 6 pictures of MaxLumaPs, up to 16 of a quarter of it (maxDpbPicBuf is 6).
|
||||
/// </summary>
|
||||
internal static int MaxDpbSize(long pictureSize) =>
|
||||
pictureSize <= MaxLumaPs >> 2 ? 16 : pictureSize <= MaxLumaPs >> 1 ? 12 : pictureSize <= (3L * MaxLumaPs) >> 2 ? 8 : 6;
|
||||
|
||||
/// <summary>Whether <paramref name="other"/> is this SPS or one with the same content.</summary>
|
||||
internal bool SameContent(Sps? other) => other is not null && (ReferenceEquals(this, other) || Raw.AsSpan().SequenceEqual(other.Raw));
|
||||
|
||||
/// <summary>The bytes <see cref="Raw"/> holds, read before parsing starts (the reader is past the NAL unit header).</summary>
|
||||
internal static byte[] RawOf(BitReader r) => r.Data.AsSpan(r.Position >> 3, r.Length - (r.Position >> 3)).TrimEnd((byte)0).ToArray();
|
||||
|
||||
/// <summary>log2 of SubWidthC and SubHeightC (table 6-1).</summary>
|
||||
internal int ChromaShiftX => SubWidthC - 1;
|
||||
|
||||
@@ -385,7 +412,7 @@ internal sealed class Sps
|
||||
|
||||
internal static Sps Parse(BitReader r)
|
||||
{
|
||||
var s = new Sps();
|
||||
var s = new Sps { Raw = RawOf(r) };
|
||||
r.Skip(4); // sps_video_parameter_set_id
|
||||
s.MaxSubLayersMinus1 = r.ReadInt(3);
|
||||
if (s.MaxSubLayersMinus1 > 6)
|
||||
@@ -425,9 +452,17 @@ internal sealed class Sps
|
||||
s.BitDepthC = r.ReadUe(8) + 8;
|
||||
s.Log2MaxPocLsb = r.ReadUe(12) + 4;
|
||||
var orderingInfo = r.ReadFlag();
|
||||
var maxDpbSize = MaxDpbSize((long)s.Width * s.Height);
|
||||
for (var i = orderingInfo ? 0 : s.MaxSubLayersMinus1; i <= s.MaxSubLayersMinus1; i++)
|
||||
{
|
||||
// The pictures the DPB holds must fit in the largest buffer of any level (A.4.2): with 16 pictures of the
|
||||
// largest size a damaged SPS would make the decoder keep gigabytes.
|
||||
s.MaxDecPicBufferingMinus1[i] = r.ReadUe(15);
|
||||
if (s.MaxDecPicBufferingMinus1[i] + 1 > maxDpbSize)
|
||||
{
|
||||
throw new H265Exception("Buffer delle immagini più grande di ogni livello HEVC.");
|
||||
}
|
||||
|
||||
s.MaxNumReorderPics[i] = r.ReadUe(s.MaxDecPicBufferingMinus1[i]);
|
||||
s.MaxLatencyIncreasePlus1[i] = (int)Math.Min(r.ReadUe(), int.MaxValue);
|
||||
}
|
||||
@@ -503,7 +538,9 @@ internal sealed class Sps
|
||||
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
|
||||
r.Skip(2); // sps_multilayer_extension_flag, sps_3d_extension_flag
|
||||
s.SccExtension = r.ReadFlag();
|
||||
r.Skip(4); // sps_extension_4bits
|
||||
if (range)
|
||||
{
|
||||
s.TransformSkipRotationEnabled = r.ReadFlag();
|
||||
@@ -517,7 +554,8 @@ internal sealed class Sps
|
||||
s.CabacBypassAlignmentEnabled = r.ReadFlag();
|
||||
}
|
||||
|
||||
// Other extensions (multilayer, 3D, screen content) are not decoded: their data is ignored.
|
||||
// The multilayer and 3D extensions only matter to layers above 0, which are ignored; their data and that
|
||||
// of screen content coding (refused when the picture starts) are not read.
|
||||
}
|
||||
|
||||
return s;
|
||||
@@ -745,6 +783,15 @@ internal sealed class Pps
|
||||
internal int Log2SaoOffsetScaleLuma;
|
||||
internal int Log2SaoOffsetScaleChroma;
|
||||
|
||||
/// <summary>pps_scc_extension_flag: screen content coding, refused as for the SPS.</summary>
|
||||
internal bool SccExtension;
|
||||
|
||||
/// <summary>The RBSP after the NAL unit header, without trailing zero bytes.</summary>
|
||||
internal byte[] Raw = [];
|
||||
|
||||
/// <summary>Whether <paramref name="other"/> is this PPS or one with the same content.</summary>
|
||||
internal bool SameContent(Pps? other) => other is not null && (ReferenceEquals(this, other) || Raw.AsSpan().SequenceEqual(other.Raw));
|
||||
|
||||
/// <summary>The tile layout of the SPS the arrays below were computed for.</summary>
|
||||
private Sps? layoutSps;
|
||||
|
||||
@@ -763,6 +810,7 @@ internal sealed class Pps
|
||||
{
|
||||
var p = new Pps
|
||||
{
|
||||
Raw = Sps.RawOf(r),
|
||||
Id = r.ReadUe(63),
|
||||
SpsId = r.ReadUe(15),
|
||||
DependentSliceSegmentsEnabled = r.ReadFlag(),
|
||||
@@ -836,7 +884,9 @@ internal sealed class Pps
|
||||
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
|
||||
r.Skip(2); // pps_multilayer_extension_flag, pps_3d_extension_flag
|
||||
p.SccExtension = r.ReadFlag();
|
||||
r.Skip(4); // pps_extension_4bits
|
||||
if (range)
|
||||
{
|
||||
if (p.TransformSkipEnabled)
|
||||
|
||||
@@ -441,6 +441,9 @@ internal sealed class SliceHeader
|
||||
|
||||
var offsetShift = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthY - 8;
|
||||
var offsetShiftC = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthC - 8;
|
||||
// WpOffsetHalfRangeY and WpOffsetHalfRangeC (7-45, 7-46): with high_precision_offsets_enabled_flag the offsets
|
||||
// are in units of the bit depth and range over half of it.
|
||||
var wpOffsetHalfY = 1 << (sps.HighPrecisionOffsetsEnabled ? sps.BitDepthY - 1 : 7);
|
||||
var wpOffsetHalfC = 1 << (sps.HighPrecisionOffsetsEnabled ? sps.BitDepthC - 1 : 7);
|
||||
Span<bool> lumaFlags = stackalloc bool[16];
|
||||
Span<bool> chromaFlags = stackalloc bool[16];
|
||||
@@ -464,7 +467,7 @@ internal sealed class SliceHeader
|
||||
if (lumaFlags[i])
|
||||
{
|
||||
LumaWeight[list][i] += r.ReadSe(-128, 127);
|
||||
LumaOffset[list][i] = r.ReadSe(-128, 127) << offsetShift;
|
||||
LumaOffset[list][i] = r.ReadSe(-wpOffsetHalfY, wpOffsetHalfY - 1) << offsetShift;
|
||||
}
|
||||
|
||||
for (var j = 0; j < 2; j++)
|
||||
|
||||
@@ -97,9 +97,9 @@ public static class HeifDecoder
|
||||
{
|
||||
throw new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.Message);
|
||||
}
|
||||
catch (AggregateException ex) when (ex.InnerException is H265Exception or HeifException)
|
||||
catch (AggregateException ex)
|
||||
{
|
||||
throw ex.InnerException is HeifException heif ? heif : new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.InnerException.Message);
|
||||
throw Unwrap(ex);
|
||||
}
|
||||
catch (Exception ex) when (ex is EndOfStreamException or ArgumentException or IndexOutOfRangeException or OverflowException
|
||||
or InvalidOperationException)
|
||||
@@ -108,6 +108,32 @@ public static class HeifDecoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the tiles decoded in parallel raised, as one <see cref="HeifException"/>: the first of theirs, else the first
|
||||
/// HEVC error, else a damaged file, whatever the exceptions were.
|
||||
/// </summary>
|
||||
private static HeifException Unwrap(AggregateException aggregate)
|
||||
{
|
||||
var inner = aggregate.Flatten().InnerExceptions;
|
||||
foreach (var ex in inner)
|
||||
{
|
||||
if (ex is HeifException heif)
|
||||
{
|
||||
return heif;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var ex in inner)
|
||||
{
|
||||
if (ex is H265Exception hevc)
|
||||
{
|
||||
return new HeifException("Immagine HEVC del file HEIF non decodificabile: " + hevc.Message);
|
||||
}
|
||||
}
|
||||
|
||||
return new HeifException("File HEIF troncato o danneggiato.");
|
||||
}
|
||||
|
||||
private static HeifItem Primary(HeifFile file)
|
||||
{
|
||||
var primary = file.Item(file.PrimaryId) ?? throw new HeifException("Manca l'immagine principale HEIF.");
|
||||
@@ -164,7 +190,7 @@ public static class HeifDecoder
|
||||
|
||||
if (rows * columns > limits.MaxTiles || grid.DerivedFrom.Count != rows * columns)
|
||||
{
|
||||
throw new HeifException("Tessere della griglia HEIF mancanti o in eccesso.");
|
||||
throw new HeifException("Riquadri della griglia HEIF mancanti o in eccesso.");
|
||||
}
|
||||
|
||||
return (rows, columns, width, height);
|
||||
@@ -241,7 +267,7 @@ public static class HeifDecoder
|
||||
hasAlpha = true;
|
||||
}
|
||||
}
|
||||
catch (HeifException)
|
||||
catch (Exception ex) when (ex is HeifException or H265Exception)
|
||||
{
|
||||
// An alpha plane that cannot be decoded: the image stands, opaque.
|
||||
}
|
||||
@@ -273,53 +299,108 @@ public static class HeifDecoder
|
||||
|
||||
/// <summary>
|
||||
/// Decodes a coded image or the tiles of a grid, handing each picture to <paramref name="place"/> with the position
|
||||
/// of its top-left sample in the image. Tiles are decoded on several threads; <paramref name="place"/> writes
|
||||
/// disjoint areas.
|
||||
/// of its top-left sample in the image, inside it. Tiles are decoded on several threads; <paramref name="place"/>
|
||||
/// writes disjoint areas. Every picture must have the size of its <c>ispe</c>, checked by the HEVC decoder before it
|
||||
/// allocates anything: a small <c>ispe</c> cannot hide a picture of the largest size.
|
||||
/// </summary>
|
||||
private static void DecodeImage(Stream stream, HeifFile file, HeifItem item, HeifLimits limits, Action<H265Frame, int, int> place)
|
||||
{
|
||||
if (item.Type == HeifFile.Hvc1)
|
||||
{
|
||||
var frame = DecodeTile(new H265Decoder(), file, item, file.ReadItem(stream, item, limits));
|
||||
var size = Ispe(file, item) ?? throw new HeifException("Manca la dimensione (ispe) dell'immagine HEIF.");
|
||||
var frame = DecodeTile(new H265Decoder(), file, item, size, file.ReadItem(stream, item, limits));
|
||||
place(frame, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
var (_, columns, _, _) = GridOf(stream, file, item, limits);
|
||||
var (rows, columns, width, height) = GridOf(stream, file, item, limits);
|
||||
var tiles = new HeifItem[item.DerivedFrom.Count];
|
||||
var data = new byte[tiles.Length][];
|
||||
(int Width, int Height) tileSize = default;
|
||||
long total = 0;
|
||||
var budget = Math.Min(limits.MaxTotalBytes, file.FileLength);
|
||||
var counted = new HashSet<uint>();
|
||||
for (var i = 0; i < tiles.Length; i++)
|
||||
{
|
||||
tiles[i] = file.Item(item.DerivedFrom[i]) ?? throw new HeifException("Tessera della griglia HEIF mancante.");
|
||||
tiles[i] = file.Item(item.DerivedFrom[i]) ?? throw new HeifException("Riquadro della griglia HEIF mancante.");
|
||||
if (tiles[i].Type != HeifFile.Hvc1)
|
||||
{
|
||||
throw new HeifException("Tessera della griglia HEIF non HEVC.");
|
||||
throw new HeifException("Riquadro della griglia HEIF non HEVC.");
|
||||
}
|
||||
|
||||
CheckDecodable(file, tiles[i]);
|
||||
data[i] = file.ReadItem(stream, tiles[i], limits); // the stream is read here, by one thread only
|
||||
|
||||
// Every tile has the same size (§6.6.2.3.1), the one of its ispe.
|
||||
var size = Ispe(file, tiles[i]) ?? throw new HeifException("Manca la dimensione (ispe) di un riquadro HEIF.");
|
||||
if (i == 0)
|
||||
{
|
||||
tileSize = size;
|
||||
}
|
||||
else if (size != tileSize)
|
||||
{
|
||||
throw new HeifException("Riquadri della griglia HEIF di dimensioni diverse.");
|
||||
}
|
||||
|
||||
// A tile named twice is read once; the bytes of all of them are never more than the file holds, so items
|
||||
// whose extents point at the same bytes cannot make a small file cost much more memory than its size.
|
||||
if (counted.Add(tiles[i].Id))
|
||||
{
|
||||
total += file.ItemLength(tiles[i], limits);
|
||||
if (total > budget)
|
||||
{
|
||||
throw new HeifException("Riquadri HEIF con più dati di quanti ne tiene il file.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every tile has the size of the first (§6.6.2.3.1): its ispe, or the first decoded picture.
|
||||
var first = DecodeTile(new H265Decoder(), file, tiles[0], data[0]);
|
||||
var (tileWidth, tileHeight) = Ispe(file, tiles[0]) ?? (first.Width, first.Height);
|
||||
place(first, 0, 0);
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, limits.MaxParallelism) };
|
||||
Parallel.For(1, tiles.Length, options, () => new H265Decoder(), (i, _, decoder) =>
|
||||
// The tiles cover the image, the last row and column cut by less than a tile, and all of them together are not
|
||||
// larger than the largest image: the output size alone bounds neither.
|
||||
var (tileWidth, tileHeight) = tileSize;
|
||||
if (tileWidth <= 0 || tileHeight <= 0
|
||||
|| (long)tileWidth * columns < width || (long)tileHeight * rows < height
|
||||
|| (long)tileWidth * (columns - 1) >= width || (long)tileHeight * (rows - 1) >= height
|
||||
|| (double)tileWidth * columns * tileHeight * rows > Math.Min(limits.MaxPixels, Array.MaxLength / 4))
|
||||
{
|
||||
var frame = DecodeTile(decoder, file, tiles[i], data[i]);
|
||||
place(frame, i % columns * tileWidth, i / columns * tileHeight);
|
||||
return decoder;
|
||||
}, _ => { });
|
||||
throw new HeifException("Riquadri della griglia HEIF che non corrispondono all'immagine.");
|
||||
}
|
||||
|
||||
var read = new Dictionary<uint, byte[]>();
|
||||
var data = new byte[tiles.Length][];
|
||||
for (var i = 0; i < tiles.Length; i++)
|
||||
{
|
||||
if (!read.TryGetValue(tiles[i].Id, out var bytes))
|
||||
{
|
||||
bytes = file.ReadItem(stream, tiles[i], limits); // the stream is read here, by one thread only
|
||||
read[tiles[i].Id] = bytes;
|
||||
}
|
||||
|
||||
data[i] = bytes;
|
||||
}
|
||||
|
||||
place(DecodeTile(new H265Decoder(), file, tiles[0], tileSize, data[0]), 0, 0);
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, limits.MaxParallelism) };
|
||||
try
|
||||
{
|
||||
Parallel.For(1, tiles.Length, options, () => new H265Decoder(), (i, _, decoder) =>
|
||||
{
|
||||
var frame = DecodeTile(decoder, file, tiles[i], tileSize, data[i]);
|
||||
place(frame, i % columns * tileWidth, i / columns * tileHeight);
|
||||
return decoder;
|
||||
}, _ => { });
|
||||
}
|
||||
catch (AggregateException ex)
|
||||
{
|
||||
throw Unwrap(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One coded picture: its <c>hvcC</c>, then its sample of length-prefixed NAL units.</summary>
|
||||
private static H265Frame DecodeTile(H265Decoder decoder, HeifFile file, HeifItem item, byte[] data)
|
||||
/// <summary>One coded picture of a known size: its <c>hvcC</c>, then its sample of length-prefixed NAL units.</summary>
|
||||
private static H265Frame DecodeTile(H265Decoder decoder, HeifFile file, HeifItem item, (int Width, int Height) size, byte[] data)
|
||||
{
|
||||
var hvcC = file.Property(item, HeifFile.HvcC) ?? throw new HeifException("Manca la configurazione hvcC dell'immagine HEIF.");
|
||||
H265Frame? frame = null;
|
||||
void Take(H265Frame f) => frame ??= f;
|
||||
decoder.FrameDecoded += Take;
|
||||
decoder.ExpectedFrameSize = size;
|
||||
try
|
||||
{
|
||||
var lengthSize = decoder.ConfigureHvcC(file.Body(hvcC));
|
||||
@@ -331,7 +412,7 @@ public static class HeifDecoder
|
||||
decoder.FrameDecoded -= Take;
|
||||
}
|
||||
|
||||
return frame ?? throw new HeifException("Nessuna immagine nei dati HEVC dell'elemento HEIF.");
|
||||
return frame ?? throw new HeifException("Nessuna immagine nei dati HEVC dell'oggetto HEIF.");
|
||||
}
|
||||
|
||||
private static YuvPlanes<ushort> Planes(H265Frame frame)
|
||||
|
||||
@@ -179,7 +179,7 @@ internal sealed class HeifFile
|
||||
{
|
||||
if (items.Count >= MaxItems)
|
||||
{
|
||||
throw new HeifException("Troppi elementi HEIF.");
|
||||
throw new HeifException("Troppi oggetti HEIF.");
|
||||
}
|
||||
|
||||
item = new HeifItem(id);
|
||||
@@ -299,7 +299,7 @@ internal sealed class HeifFile
|
||||
|
||||
if (count > MaxItems)
|
||||
{
|
||||
throw new HeifException("Troppi elementi HEIF.");
|
||||
throw new HeifException("Troppi oggetti HEIF.");
|
||||
}
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
@@ -488,53 +488,7 @@ internal sealed class HeifFile
|
||||
/// <summary>The bytes of an item, its extents one after the other.</summary>
|
||||
internal byte[] ReadItem(Stream stream, HeifItem item, HeifLimits limits)
|
||||
{
|
||||
if (!item.Located || item.Extents.Count == 0)
|
||||
{
|
||||
throw new HeifException("Elemento HEIF senza dati.");
|
||||
}
|
||||
|
||||
long total = 0;
|
||||
var spans = new (long Offset, long Length)[item.Extents.Count];
|
||||
for (var i = 0; i < spans.Length; i++)
|
||||
{
|
||||
var (offset, length) = item.Extents[i];
|
||||
long available;
|
||||
switch (item.ConstructionMethod)
|
||||
{
|
||||
case 0:
|
||||
available = FileLength - offset;
|
||||
break;
|
||||
case 1:
|
||||
if (Idat.Length < 0)
|
||||
{
|
||||
throw new HeifException("Manca il box idat HEIF.");
|
||||
}
|
||||
|
||||
available = Idat.Length - offset;
|
||||
break;
|
||||
default:
|
||||
throw new HeifException("Costruzione di elemento HEIF non gestita.");
|
||||
}
|
||||
|
||||
if (offset < 0 || available < 0)
|
||||
{
|
||||
throw new HeifException("Elemento HEIF fuori dal file.");
|
||||
}
|
||||
|
||||
length = length == 0 ? available : length;
|
||||
if (length > available)
|
||||
{
|
||||
throw new HeifException("Elemento HEIF fuori dal file.");
|
||||
}
|
||||
|
||||
spans[i] = (offset, length);
|
||||
total += length;
|
||||
if (total > limits.MaxItemBytes)
|
||||
{
|
||||
throw new HeifException("Elemento HEIF troppo grande.");
|
||||
}
|
||||
}
|
||||
|
||||
var spans = Locate(item, limits, out var total);
|
||||
var data = new byte[total];
|
||||
var position = 0;
|
||||
foreach (var (offset, length) in spans)
|
||||
@@ -554,4 +508,64 @@ internal sealed class HeifFile
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>How many bytes <see cref="ReadItem"/> would read for an item, checked as it checks them, without reading.</summary>
|
||||
internal long ItemLength(HeifItem item, HeifLimits limits)
|
||||
{
|
||||
Locate(item, limits, out var total);
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>The extents of an item, each checked against the file (or <c>idat</c>), and their total.</summary>
|
||||
private (long Offset, long Length)[] Locate(HeifItem item, HeifLimits limits, out long total)
|
||||
{
|
||||
if (!item.Located || item.Extents.Count == 0)
|
||||
{
|
||||
throw new HeifException("Oggetto HEIF senza dati.");
|
||||
}
|
||||
|
||||
total = 0;
|
||||
var spans = new (long Offset, long Length)[item.Extents.Count];
|
||||
for (var i = 0; i < spans.Length; i++)
|
||||
{
|
||||
var (offset, length) = item.Extents[i];
|
||||
long available;
|
||||
switch (item.ConstructionMethod)
|
||||
{
|
||||
case 0:
|
||||
available = FileLength - offset;
|
||||
break;
|
||||
case 1:
|
||||
if (Idat.Length < 0)
|
||||
{
|
||||
throw new HeifException("Manca il box idat HEIF.");
|
||||
}
|
||||
|
||||
available = Idat.Length - offset;
|
||||
break;
|
||||
default:
|
||||
throw new HeifException("Costruzione di oggetto HEIF non gestita.");
|
||||
}
|
||||
|
||||
if (offset < 0 || available < 0)
|
||||
{
|
||||
throw new HeifException("Oggetto HEIF fuori dal file.");
|
||||
}
|
||||
|
||||
length = length == 0 ? available : length;
|
||||
if (length > available)
|
||||
{
|
||||
throw new HeifException("Oggetto HEIF fuori dal file.");
|
||||
}
|
||||
|
||||
spans[i] = (offset, length);
|
||||
total += length;
|
||||
if (total > limits.MaxItemBytes)
|
||||
{
|
||||
throw new HeifException("Oggetto HEIF troppo grande.");
|
||||
}
|
||||
}
|
||||
|
||||
return spans;
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,12 @@ public sealed record HeifLimits
|
||||
/// <summary>Bytes of one item at most.</summary>
|
||||
public int MaxItemBytes { get; init; } = 128 * 1024 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// Bytes of all the coded pictures of one image (the tiles of a grid) at most. They are also never more than the
|
||||
/// file: items whose extents point at the same bytes cannot make the decoder read a small file many times over.
|
||||
/// </summary>
|
||||
public long MaxTotalBytes { get; init; } = 512L * 1024 * 1024;
|
||||
|
||||
/// <summary>Tiles of a grid at most (256 × 256).</summary>
|
||||
public int MaxTiles { get; init; } = 65_536;
|
||||
|
||||
|
||||
@@ -38,9 +38,16 @@ internal readonly struct YuvPlanes<T>(
|
||||
|
||||
/// <summary>
|
||||
/// Conversion of Y′CbCr samples to 8-bit RGB (ITU-T H.273 for the meaning of matrix_coeffs and video_full_range_flag):
|
||||
/// BT.709, BT.601, FCC, SMPTE 240M or BT.2020 (non-constant luminance) coefficients, the identity matrix (G, B and R
|
||||
/// coded as Y, Cb and Cr), limited or full range, any bit depth; chroma taken at the nearest sample. Integer arithmetic
|
||||
/// with 16 fractional bits, so every caller gets the same pixels.
|
||||
/// BT.709 (1), FCC (4), BT.601 (5, 6), SMPTE 240M (7) or BT.2020 non-constant luminance (9) coefficients, the identity
|
||||
/// matrix (0: G, B and R coded as Y, Cb and Cr), YCgCo (8: Y, Cg and Co in place of Y, Cb and Cr, the inverse of the
|
||||
/// equations of H.273 for MatrixCoefficients 8), limited or full range, any bit depth; chroma taken at the nearest
|
||||
/// sample. Integer arithmetic with 16 fractional bits, so every caller gets the same pixels.
|
||||
/// <para>
|
||||
/// Approximated: BT.2020 constant luminance (10) is converted with the non-constant luminance coefficients of 9, without
|
||||
/// its transfer to linear light; the chromaticity-derived matrices (12, 13), which need the colour primaries,
|
||||
/// SMPTE ST 2085 (11) and ICtCp (14), as every unspecified or unknown value, take BT.709 from 720 lines up and BT.601
|
||||
/// below. None of them comes from the phones and services Febe meets.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal static class YuvToRgb
|
||||
{
|
||||
@@ -53,6 +60,11 @@ internal static class YuvToRgb
|
||||
{
|
||||
internal bool Identity { get; init; }
|
||||
|
||||
/// <summary>YCgCo (matrix 8): G = Y + Cg, R = Y − Cg + Co, B = Y − Cg − Co, Cg and Co scaled by <see cref="ChromaScale"/>.</summary>
|
||||
internal bool YCgCo { get; init; }
|
||||
|
||||
internal int ChromaScale { get; init; }
|
||||
|
||||
internal int LumaScale { get; init; }
|
||||
|
||||
internal int LumaOffset { get; init; }
|
||||
@@ -74,8 +86,8 @@ internal static class YuvToRgb
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The coefficients for <paramref name="matrix"/> (matrix_coeffs; unspecified or unknown: BT.709 from 720 lines up,
|
||||
/// BT.601 below), <paramref name="fullRange"/> and the bit depths of the samples.
|
||||
/// The coefficients for <paramref name="matrix"/> (matrix_coeffs; unspecified, unknown or approximated as the class
|
||||
/// says: BT.709 from 720 lines up, BT.601 below), <paramref name="fullRange"/> and the bit depths of the samples.
|
||||
/// </summary>
|
||||
internal static Coefficients For(int matrix, bool fullRange, int bitDepthY, int bitDepthC, int height)
|
||||
{
|
||||
@@ -84,6 +96,19 @@ internal static class YuvToRgb
|
||||
return new Coefficients { Identity = true, IdentityShiftY = Math.Max(0, bitDepthY - 8), IdentityShiftC = Math.Max(0, bitDepthC - 8) };
|
||||
}
|
||||
|
||||
if (matrix == 8)
|
||||
{
|
||||
// Cg and Co are quantised as Cb and Cr are, with the same ranges (H.273, MatrixCoefficients 8).
|
||||
return new Coefficients
|
||||
{
|
||||
YCgCo = true,
|
||||
LumaScale = (int)Math.Round((fullRange ? 1.0 : 255.0 / 219.0) / (1 << Math.Max(0, bitDepthY - 8)) * One),
|
||||
LumaOffset = fullRange ? 0 : 16 << Math.Max(0, bitDepthY - 8),
|
||||
ChromaMiddle = 1 << (bitDepthC - 1),
|
||||
ChromaScale = (int)Math.Round((fullRange ? 1.0 : 255.0 / 224.0) / (1 << Math.Max(0, bitDepthC - 8)) * One),
|
||||
};
|
||||
}
|
||||
|
||||
var (kr, kb) = matrix switch
|
||||
{
|
||||
1 => (0.2126, 0.0722),
|
||||
@@ -161,6 +186,17 @@ internal static class YuvToRgb
|
||||
var l = (luma - k.LumaOffset) * k.LumaScale;
|
||||
u -= k.ChromaMiddle;
|
||||
v -= k.ChromaMiddle;
|
||||
if (k.YCgCo)
|
||||
{
|
||||
var cg = u * k.ChromaScale;
|
||||
var co = v * k.ChromaScale;
|
||||
var t = l - cg;
|
||||
r += Clip((t + co + Half) >> Shift);
|
||||
g += Clip((l + cg + Half) >> Shift);
|
||||
b += Clip((t - co + Half) >> Shift);
|
||||
continue;
|
||||
}
|
||||
|
||||
r += Clip((l + (k.CrToR * v) + Half) >> Shift);
|
||||
g += Clip((l - (k.CbToG * u) - (k.CrToG * v) + Half) >> Shift);
|
||||
b += Clip((l + (k.CbToB * u) + Half) >> Shift);
|
||||
|
||||
@@ -160,9 +160,9 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per
|
||||
## Limiti noti
|
||||
|
||||
- HEIC/HEIF: dimensioni, impronta e miniatura vengono dal decodificatore scritto in casa (`Febe.Core.Codecs.Heif`, sul
|
||||
decodificatore HEVC): immagine singola o griglia di tessere, `clap`, `irot`/`imir`, trasparenza. La data di scatto
|
||||
si legge dall'elemento `Exif` solo se sta nei primi 512 KB del file. Restano senza miniatura gli HEIF che non sono
|
||||
HEVC (AVIF, JPEG), le immagini derivate diverse dalle griglie e le sequenze di immagini.
|
||||
decodificatore HEVC): immagine singola o griglia di riquadri, `clap`, `irot`/`imir`, trasparenza. La data di scatto
|
||||
si legge dall'oggetto `Exif` del box `meta` solo se sta nei primi 512 KB del file. Restano senza miniatura gli HEIF
|
||||
che non sono HEVC (AVIF, JPEG), le immagini derivate diverse dalle griglie e le sequenze di immagini.
|
||||
- La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella
|
||||
scrivibile per il sistema ma non per Febe non si riconosce; lì «Sposta» lascia l'originale e lo dice.
|
||||
- La data `mvhd` si legge come UTC, come vuole il formato; alcune fotocamere vi scrivono l'ora locale.
|
||||
|
||||
Reference in new issue
Block a user