Phase 4b review, codec findings. A Replace makes the converted file the photo, so a conversion must not lose what the original held, and the dry run must promise only what the job will do. - Linear DNG from a conversion is scene-referred: the pixels are stored in linear ProPhoto primaries (colours outside sRGB stay positive) and divided by the power of two that brings their peak under the white level (at most 4 stops), with BaselineExposure giving it back and ColorMatrix1/ForwardMatrix1 describing that space. Highlights a RAW develops above 1 and its wide-gamut colours now read back as written. Exports keep the clipped linear-sRGB DNG. - A conversion reads with the managed decoders first for every format they read natively (RAWs developed at float precision, as on the server) and with WIC only for what they cannot. A RAW only WIC's Raw Image Extension develops (8 bits) is refused for TIFF-16 and linear DNG and planned out as "eight_bit"; JPEG still converts it. Providers say so through IImageDecoderProvider.DevelopsRawAt8Bits. - The original's colour space is kept: a JPEG (APP2) or TIFF (tag 34675) carries its ICC profile, with the values unchanged; a linear DNG gets the values converted through a matrix/TRC profile; a gray profile converts to sRGB. Exif Adobe RGB (uncalibrated + R03) and HEIF nclx P3 get an in-house profile. A space nothing here can keep (CMYK, a lookup-table profile into a DNG, uncalibrated without R03, HDR nclx) is planned out as "color_profile". New in-house ICC parser/writer and header reader for JPEG, PNG, TIFF, HEIF/AVIF and WebP. - The planner asks every file, whatever tier was recorded (unknown before the light analysis, or by another host), with the conversion's decoders, headers only and eight at a time; a RAW the server cannot develop is "convert_on_pc" in the plan instead of failing its sequence. Photos a target cannot hold (a JPEG side above 65535, more samples than one buffer) are planned out as "too_large", and an overflow fails its photo rather than the job. - A photo that fails reads in the job log as one catalog sentence by cause (Archive.Convert.Failed.*), the file named once; the exception's English text goes to the diagnostics log only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 0ca1e91ea09946d7a55f45695ee58e1a0ff5f779)
279 lines
12 KiB
C#
279 lines
12 KiB
C#
using System.Buffers.Binary;
|
|
using System.Text;
|
|
using Chronos.Core.Metadata.Tiff;
|
|
using Chronos.Core.Metadata.Xmp;
|
|
|
|
namespace Chronos.Core.Metadata.Jpeg;
|
|
|
|
/// <summary>Frame header (SOFn) of a JPEG.</summary>
|
|
internal readonly record struct JpegFrame(int Width, int Height, int Precision, bool Lossless);
|
|
|
|
/// <summary>
|
|
/// JPEG marker scan: APP1 Exif, APP1 XMP and extended XMP (reassembled by GUID/offset), APP2 MPF large-thumbnail
|
|
/// entries, SOFn. Reads only segment headers and the payloads it parses, stops at SOS, and tolerates fill bytes and
|
|
/// garbage between segments.
|
|
/// </summary>
|
|
internal static class JpegParser
|
|
{
|
|
/// <summary>Most bytes read while looking for an embedded JPEG's frame header.</summary>
|
|
public const int MaxFrameScanBytes = 64 * 1024;
|
|
|
|
private const int MaxSegments = 1024;
|
|
private const int MaxGarbageBytes = 64 * 1024;
|
|
private const int MaxMpEntries = 64;
|
|
private const ushort MpEntryTag = 0xB002;
|
|
private const uint MpLargeThumbnailVga = 0x010001;
|
|
private const uint MpLargeThumbnailFullHd = 0x010002;
|
|
private const int ExtendedHeaderLength = 75;
|
|
|
|
private static ReadOnlySpan<byte> ExifSignature => "Exif\0"u8;
|
|
private static ReadOnlySpan<byte> XmpSignature => "http://ns.adobe.com/xap/1.0/\0"u8;
|
|
private static ReadOnlySpan<byte> ExtendedXmpSignature => "http://ns.adobe.com/xmp/extension/\0"u8;
|
|
private static ReadOnlySpan<byte> MpfSignature => "MPF\0"u8;
|
|
|
|
/// <summary>Scans the JPEG at [<paramref name="start"/>, <paramref name="end"/>). A primary JPEG defines the main image
|
|
/// size; an embedded one (RAF, RW2 JpgFromRaw) contributes its Exif/XMP and is recorded as a preview.</summary>
|
|
public static void Parse(MetadataBuilder m, long start, long end, bool primary)
|
|
{
|
|
var scanner = new SegmentScanner(m.Stream, start, Math.Min(end, m.Length), long.MaxValue);
|
|
if (!scanner.StartsWithSoi())
|
|
{
|
|
m.Warn("JPEG start-of-image marker not found");
|
|
return;
|
|
}
|
|
JpegFrame? frame = null;
|
|
var exifSeen = false;
|
|
List<ExtendedXmpChunk>? extended = null;
|
|
while (scanner.Next(out var segment))
|
|
{
|
|
m.ThrowIfCancelled();
|
|
if (segment.Marker is 0xDA or 0xD9) break;
|
|
if (segment.Marker == 0xE1) ReadApp1(m, segment, ref exifSeen, ref extended);
|
|
else if (segment.Marker == 0xE2) ReadMpf(m, segment);
|
|
else if (frame is null && IsFrameMarker(segment.Marker)) frame = ReadFrameHeader(m.Stream, segment);
|
|
}
|
|
if (scanner.Garbage) m.Warn("JPEG: garbage between segments skipped");
|
|
if (scanner.Truncated) m.Warn("JPEG: truncated segment");
|
|
if (frame is { } f)
|
|
{
|
|
if (primary) m.SetContainerSize(f.Width, f.Height, f.Precision);
|
|
else if (!f.Lossless && end <= m.Length) m.AddPreview(start, end - start, f.Width, f.Height);
|
|
}
|
|
else if (primary)
|
|
{
|
|
m.Warn("JPEG frame header not found");
|
|
}
|
|
if (extended is not null) AssembleExtendedXmp(m, extended);
|
|
}
|
|
|
|
/// <summary>Frame header of an embedded JPEG reading at most <see cref="MaxFrameScanBytes"/>; null when the bytes are
|
|
/// not a JPEG or no SOFn precedes the scan data.</summary>
|
|
public static JpegFrame? ReadFrame(Stream stream, long offset, long length)
|
|
{
|
|
if (offset < 0 || length < 4 || offset > stream.Length - length) return null;
|
|
var scanner = new SegmentScanner(stream, offset, offset + length, MaxFrameScanBytes);
|
|
if (!scanner.StartsWithSoi()) return null;
|
|
while (scanner.Next(out var segment))
|
|
{
|
|
if (segment.Marker is 0xDA or 0xD9) return null;
|
|
if (IsFrameMarker(segment.Marker)) return ReadFrameHeader(stream, segment);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>Validates an embedded JPEG and records it as a preview unless it is lossless (raw data).</summary>
|
|
/// <returns>The frame header, or null when the range holds no readable JPEG.</returns>
|
|
public static JpegFrame? AddPreview(MetadataBuilder m, long offset, long length, PreviewKind? kind = null)
|
|
{
|
|
if (offset < 0 || length <= 0 || offset > m.Length - length)
|
|
{
|
|
m.Warn("Embedded JPEG outside the file");
|
|
return null;
|
|
}
|
|
var frame = ReadFrame(m.Stream, offset, length);
|
|
if (frame is { Lossless: false } f) m.AddPreview(offset, length, f.Width, f.Height, kind);
|
|
return frame;
|
|
}
|
|
|
|
private static bool IsFrameMarker(byte marker) => marker is >= 0xC0 and <= 0xCF and not (0xC4 or 0xC8 or 0xCC);
|
|
|
|
private static JpegFrame? ReadFrameHeader(Stream stream, Segment segment)
|
|
{
|
|
Span<byte> sof = stackalloc byte[6];
|
|
if (segment.Length < 6 || !stream.TryReadAt(segment.Payload, sof)) return null;
|
|
var lossless = segment.Marker is 0xC3 or 0xC7 or 0xCB or 0xCF;
|
|
return new JpegFrame(BinaryPrimitives.ReadUInt16BigEndian(sof[3..]), BinaryPrimitives.ReadUInt16BigEndian(sof[1..]), sof[0], lossless);
|
|
}
|
|
|
|
private static void ReadApp1(MetadataBuilder m, Segment segment, ref bool exifSeen, ref List<ExtendedXmpChunk>? extended)
|
|
{
|
|
Span<byte> head = stackalloc byte[ExtendedHeaderLength];
|
|
var n = m.Stream.ReadUpTo(segment.Payload, head[..Math.Min(head.Length, segment.Length)]);
|
|
var h = head[..n];
|
|
if (h.StartsWith(ExifSignature) && segment.Length > 6)
|
|
{
|
|
if (!exifSeen) ExifParser.ParseEmbedded(m, segment.Payload + 6);
|
|
exifSeen = true;
|
|
}
|
|
else if (h.StartsWith(XmpSignature))
|
|
{
|
|
m.AddXmp(m.Stream.ReadAt(segment.Payload + XmpSignature.Length, segment.Length - XmpSignature.Length, XmpParser.MaxPacketBytes));
|
|
}
|
|
else if (h.StartsWith(ExtendedXmpSignature) && n == ExtendedHeaderLength)
|
|
{
|
|
var guid = Encoding.ASCII.GetString(h.Slice(ExtendedXmpSignature.Length, 32));
|
|
var full = BinaryPrimitives.ReadUInt32BigEndian(h[67..]);
|
|
var offset = BinaryPrimitives.ReadUInt32BigEndian(h[71..]);
|
|
(extended ??= []).Add(new ExtendedXmpChunk(guid, full, offset, segment.Payload + ExtendedHeaderLength, segment.Length - ExtendedHeaderLength));
|
|
}
|
|
}
|
|
|
|
/// <summary>APP2 Multi-Picture Format: secondary large thumbnails (type 0x010001/0x010002) become previews. Offsets are
|
|
/// relative to the MP header; other secondary types (disparity, gain maps…) are not previews.</summary>
|
|
private static void ReadMpf(MetadataBuilder m, Segment segment)
|
|
{
|
|
Span<byte> head = stackalloc byte[4];
|
|
if (segment.Length < 16 || !m.Stream.TryReadAt(segment.Payload, head) || !head.SequenceEqual(MpfSignature)) return;
|
|
var mpBase = segment.Payload + 4;
|
|
var r = TiffReader.Open(m.Stream, mpBase);
|
|
if (r?.ReadIfd(r.FirstIfdOffset) is not { } index || !index.Entries.TryGetValue(MpEntryTag, out var entry)) return;
|
|
if (entry.Count % 16 != 0 || entry.Count > 16 * MaxMpEntries || r.ReadBytes(entry) is not { } entries)
|
|
{
|
|
m.Warn("MPF entry table malformed");
|
|
return;
|
|
}
|
|
for (var i = 16; i + 16 <= entries.Length; i += 16)
|
|
{
|
|
var e = entries.AsSpan(i, 16);
|
|
var type = r.U32(e) & 0xFFFFFF;
|
|
var size = r.U32(e[4..]);
|
|
var offset = r.U32(e[8..]);
|
|
if (type is MpLargeThumbnailVga or MpLargeThumbnailFullHd && offset > 0 && size > 0) AddPreview(m, mpBase + offset, size);
|
|
}
|
|
m.AddWarnings(r.Warnings);
|
|
}
|
|
|
|
private static void AssembleExtendedXmp(MetadataBuilder m, List<ExtendedXmpChunk> chunks)
|
|
{
|
|
var guid = m.Xmp.ExtendedXmpGuid;
|
|
if (guid is null)
|
|
{
|
|
m.Warn("Extended XMP present but not referenced by the main packet");
|
|
return;
|
|
}
|
|
uint full = 0;
|
|
long covered = 0;
|
|
foreach (var c in chunks)
|
|
{
|
|
if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase)) continue;
|
|
if (full == 0) full = c.FullLength;
|
|
if (c.FullLength == full) covered += c.Length;
|
|
}
|
|
if (full == 0 || full > XmpParser.MaxPacketBytes || covered < full)
|
|
{
|
|
m.Warn("Extended XMP incomplete");
|
|
return;
|
|
}
|
|
var buffer = new byte[full];
|
|
foreach (var c in chunks)
|
|
{
|
|
if (!string.Equals(c.Guid, guid, StringComparison.OrdinalIgnoreCase) || c.FullLength != full || (long)c.Offset + c.Length > full) continue;
|
|
if (!m.Stream.TryReadAt(c.Position, buffer.AsSpan((int)c.Offset, c.Length)))
|
|
{
|
|
m.Warn("Extended XMP chunk unreadable");
|
|
return;
|
|
}
|
|
}
|
|
m.AddXmp(buffer);
|
|
}
|
|
|
|
/// <summary>A marker segment: its marker, where its payload starts, and the payload bytes present (0 for markers without one).</summary>
|
|
internal readonly record struct Segment(byte Marker, long Payload, int Length);
|
|
|
|
private readonly record struct ExtendedXmpChunk(string Guid, uint FullLength, uint Offset, long Position, int Length);
|
|
|
|
/// <summary>Walks marker segments of one JPEG, reading only marker and length bytes within a read budget.</summary>
|
|
internal sealed class SegmentScanner(Stream stream, long start, long end, long readBudget)
|
|
{
|
|
private readonly byte[] _buffer = new byte[16];
|
|
private long _position = start + 2;
|
|
private long _budget = readBudget;
|
|
private int _count;
|
|
|
|
public bool Garbage { get; private set; }
|
|
|
|
public bool Truncated { get; private set; }
|
|
|
|
public bool StartsWithSoi() => Read(start, 2) == 2 && _buffer[0] == 0xFF && _buffer[1] == 0xD8;
|
|
|
|
public bool Next(out Segment segment)
|
|
{
|
|
segment = default;
|
|
if (++_count > MaxSegments) return false;
|
|
long skipped = 0;
|
|
while (true)
|
|
{
|
|
var n = Read(_position, _buffer.Length);
|
|
if (n < 2)
|
|
{
|
|
if (_position < end) Truncated = true;
|
|
return false;
|
|
}
|
|
var i = 0;
|
|
while (i < n - 1 && !(_buffer[i] == 0xFF && _buffer[i + 1] is not (0xFF or 0x00))) i++;
|
|
if (i == n - 1)
|
|
{
|
|
Garbage |= _buffer.AsSpan(0, n - 1).ContainsAnyExcept((byte)0xFF);
|
|
_position += n - 1;
|
|
skipped += n - 1;
|
|
if (skipped > MaxGarbageBytes) return false;
|
|
continue;
|
|
}
|
|
Garbage |= _buffer.AsSpan(0, i).ContainsAnyExcept((byte)0xFF);
|
|
var marker = _buffer[i + 1];
|
|
var markerPosition = _position + i + 1;
|
|
if (marker is 0xD8 or 0xD9 or 0x01 or (>= 0xD0 and <= 0xD7))
|
|
{
|
|
_position = markerPosition + 1;
|
|
segment = new Segment(marker, _position, 0);
|
|
return true;
|
|
}
|
|
int length;
|
|
if (i + 3 < n)
|
|
{
|
|
length = _buffer[i + 2] << 8 | _buffer[i + 3];
|
|
}
|
|
else if (Read(markerPosition + 1, 2) == 2)
|
|
{
|
|
length = _buffer[0] << 8 | _buffer[1];
|
|
}
|
|
else
|
|
{
|
|
Truncated = true;
|
|
return false;
|
|
}
|
|
if (length < 2)
|
|
{
|
|
Garbage = true;
|
|
return false;
|
|
}
|
|
var payload = markerPosition + 3;
|
|
var available = (int)Math.Clamp(end - payload, 0, length - 2);
|
|
Truncated |= available < length - 2;
|
|
segment = new Segment(marker, payload, available);
|
|
_position = payload + length - 2;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
private int Read(long position, int count)
|
|
{
|
|
if (position >= end || _budget <= 0) return 0;
|
|
var n = (int)Math.Min(Math.Min(count, end - position), _budget);
|
|
n = stream.ReadUpTo(position, _buffer.AsSpan(0, n));
|
|
_budget -= n;
|
|
return n;
|
|
}
|
|
}
|
|
}
|