| | | 1 | | using System.Buffers.Binary; |
| | | 2 | | |
| | | 3 | | namespace Anichron.Worker.Ingestion.Proxy; |
| | | 4 | | |
| | | 5 | | internal static class ImageCompleteness |
| | | 6 | | { |
| | | 7 | | private const byte markerPrefix = 0xFF; |
| | | 8 | | private const byte endOfImage = 0xD9; |
| | | 9 | | |
| | | 10 | | public static void EnsureHeif(ReadOnlySpan<byte> heif) |
| | 23 | 11 | | { |
| | 71 | 12 | | while (!heif.IsEmpty) |
| | 59 | 13 | | { |
| | 59 | 14 | | if (!BinaryPrimitives.TryReadUInt32BigEndian(heif, out var compactSize)) |
| | 1 | 15 | | throw HeifEndsEarly(); |
| | | 16 | | |
| | 58 | 17 | | var size = compactSize == 1 ? LargeSize(heif) : compactSize; |
| | 56 | 18 | | if (size == 0) |
| | 1 | 19 | | return; |
| | 55 | 20 | | if (size > (ulong)heif.Length) |
| | 7 | 21 | | throw HeifEndsEarly(); |
| | | 22 | | |
| | 48 | 23 | | heif = heif[(int)size..]; |
| | 48 | 24 | | } |
| | 13 | 25 | | } |
| | | 26 | | |
| | | 27 | | private static ulong LargeSize(ReadOnlySpan<byte> box) |
| | 17 | 28 | | => box.Length >= 16 ? BinaryPrimitives.ReadUInt64BigEndian(box[8..]) : throw HeifEndsEarly(); |
| | | 29 | | |
| | | 30 | | public static void EnsureJpeg(ReadOnlySpan<byte> jpeg) |
| | 50 | 31 | | { |
| | 50 | 32 | | var rest = jpeg[2..]; |
| | 1570 | 33 | | while (true) |
| | 1570 | 34 | | { |
| | 1570 | 35 | | var prefix = rest.IndexOf(markerPrefix); |
| | 1570 | 36 | | if (prefix < 0) |
| | 13 | 37 | | throw JpegEndsEarly(); |
| | | 38 | | |
| | 1557 | 39 | | rest = rest[(prefix + 1)..]; |
| | 1557 | 40 | | var code = rest.IndexOfAnyExcept(markerPrefix); |
| | 1557 | 41 | | if (code < 0) |
| | 2 | 42 | | throw JpegEndsEarly(); |
| | | 43 | | |
| | 1555 | 44 | | var marker = rest[code]; |
| | 1555 | 45 | | rest = rest[(code + 1)..]; |
| | 1555 | 46 | | if (marker == endOfImage) |
| | 35 | 47 | | return; |
| | 1520 | 48 | | if (marker is 0x00 or 0x01 or (>= 0xD0 and <= 0xD7)) |
| | 1275 | 49 | | continue; |
| | | 50 | | |
| | 245 | 51 | | rest = rest[Math.Min(SegmentLength(rest), rest.Length)..]; |
| | 245 | 52 | | } |
| | 35 | 53 | | } |
| | | 54 | | |
| | | 55 | | private static ushort SegmentLength(ReadOnlySpan<byte> segment) |
| | 245 | 56 | | => BinaryPrimitives.TryReadUInt16BigEndian(segment, out var length) ? length : (ushort)0; |
| | | 57 | | |
| | | 58 | | private static IncompleteImageException HeifEndsEarly() |
| | 10 | 59 | | => new("The image data is incomplete: the file ends inside a HEIF box."); |
| | | 60 | | |
| | | 61 | | private static IncompleteImageException JpegEndsEarly() |
| | 15 | 62 | | => new("The image data is incomplete: the file ends before the JPEG's end-of-image marker."); |
| | | 63 | | } |