refactor(core): keep a single thumbs.pack format
The decode workstream added a second pack writer and proxy builder that wrote TTPK files with a different layout to the same path as the archive's ThumbPack. The archive implementation is the one wired into ingest, maintenance and the thumbnail jobs; the unused duplicates are removed. The LRU ThumbnailCache stays for the UI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
3 files changed
+7
-784
No files matched your search
@@ -1,64 +0,0 @@
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Metadata;
|
||||
|
||||
namespace Titano.Core.Imaging.Thumbnails;
|
||||
|
||||
/// <summary>Proxy long-edge policy (BRIEF §8.5).</summary>
|
||||
public enum ProxySize
|
||||
{
|
||||
/// <summary>Source resolution.</summary>
|
||||
Full = 0,
|
||||
Edge1280 = 1280,
|
||||
Edge1920 = 1920,
|
||||
Edge2560 = 2560,
|
||||
}
|
||||
|
||||
/// <summary>A built proxy and how its pixels were obtained.</summary>
|
||||
/// <param name="Jpeg">JPEG file bytes with an Exif block.</param>
|
||||
/// <param name="Width">Proxy width (oriented).</param>
|
||||
/// <param name="Height">Proxy height (oriented).</param>
|
||||
/// <param name="Tier">Decode tier of the source (an embedded preview caps the proxy at the preview's size).</param>
|
||||
public sealed record ProxyResult(byte[] Jpeg, int Width, int Height, DecodeTier Tier);
|
||||
|
||||
/// <summary>
|
||||
/// Builds proxies (BRIEF §8.5): the source decoded at the policy long edge (1280/1920/2560 or full) with its orientation
|
||||
/// applied, encoded as JPEG q92, carrying an Exif block written by <see cref="ExifWriter.BuildJpegApp1"/> from the
|
||||
/// source metadata (capture time, camera, exposure, GPS) with orientation reset to 1 because the pixels are upright.
|
||||
/// </summary>
|
||||
public static class ProxyBuilder
|
||||
{
|
||||
public const int Quality = 92;
|
||||
|
||||
/// <summary>Default policy.</summary>
|
||||
public const ProxySize DefaultSize = ProxySize.Edge1920;
|
||||
|
||||
/// <summary>Decodes and encodes the proxy of <paramref name="sourcePath"/>; null when no tier can decode it.</summary>
|
||||
/// <param name="metadata">Source metadata; read from the file when null.</param>
|
||||
public static ProxyResult? Build(ImageDecoder decoder, string sourcePath, ProxySize size = DefaultSize, FrameMetadata? metadata = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
using var decoded = decoder.Decode(new DecodeRequest(sourcePath, (int)size, DecodePurpose.Proxy), cancellationToken);
|
||||
if (decoded is null) return null;
|
||||
metadata ??= MetadataReader.Read(sourcePath, cancellationToken);
|
||||
return new ProxyResult(Encode(decoded.Pixels, metadata), decoded.Pixels.Width, decoded.Pixels.Height, decoded.Tier);
|
||||
}
|
||||
|
||||
/// <summary>Builds the proxy and writes it crash-safely to <paramref name="proxyPath"/>.</summary>
|
||||
public static ProxyResult? Write(ImageDecoder decoder, string sourcePath, string proxyPath, ProxySize size = DefaultSize, FrameMetadata? metadata = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = Build(decoder, sourcePath, size, metadata, cancellationToken);
|
||||
if (result is not null) AtomicFile.WriteAllBytes(proxyPath, result.Jpeg);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Encodes upright linear-light pixels as a proxy JPEG with the source's Exif (orientation 1).</summary>
|
||||
public static byte[] Encode(ImageBuffer image, FrameMetadata metadata)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
ArgumentNullException.ThrowIfNull(metadata);
|
||||
var segment = ExifWriter.BuildJpegApp1(metadata with { Orientation = 1, Width = image.Width, Height = image.Height });
|
||||
// The encoder takes APP1 payloads: drop the marker and length that BuildJpegApp1 puts in front.
|
||||
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = Quality, App1Segments = [segment[4..]], OptimizeHuffman = true });
|
||||
}
|
||||
}
|
||||
@@ -1,497 +0,0 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Concurrent;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Hashing;
|
||||
using Titano.Core.IO;
|
||||
|
||||
namespace Titano.Core.Imaging.Thumbnails;
|
||||
|
||||
/// <summary>Index entry of one thumbnail in a <see cref="ThumbnailPack"/>.</summary>
|
||||
/// <param name="FrameId">Frame the thumbnail belongs to.</param>
|
||||
/// <param name="Offset">File offset of the entry record.</param>
|
||||
/// <param name="Length">JPEG length in bytes.</param>
|
||||
/// <param name="Width">Thumbnail width in pixels.</param>
|
||||
/// <param name="Height">Thumbnail height in pixels.</param>
|
||||
/// <param name="Crc">CRC-32 of the JPEG bytes.</param>
|
||||
public readonly record struct ThumbnailEntry(Guid FrameId, long Offset, int Length, int Width, int Height, uint Crc);
|
||||
|
||||
/// <summary>
|
||||
/// The per-sequence thumbnail file <c>thumbs.pack</c> (BRIEF §8.5): 320-pixel JPEG (q80) thumbnails appended to one file.
|
||||
/// <para>Layout (little-endian): two 64-byte header slots at 0 and 64 (magic "TTPK", version, generation, offset/length/
|
||||
/// count of the current index record, the file length it covers, CRC-32); from 128, self-describing records — entries
|
||||
/// ("TENT": frame id, size, JPEG length and CRC, then the JPEG) and index tables ("TIDX": count, then frame id → offset,
|
||||
/// length, size, CRC per entry, then the record's CRC).</para>
|
||||
/// <para>Writes only append. Every <see cref="IndexInterval"/> appends (and on <see cref="Flush"/>/<see cref="Dispose"/>)
|
||||
/// a new index record is appended and flushed, then the header slot not holding the newest generation is overwritten and
|
||||
/// flushed: a crash leaves the previous slot valid. Opening takes the newest valid slot, then recovers entries appended
|
||||
/// after its index by scanning forward until the first damaged record, so truncated or partially written files lose
|
||||
/// only their damaged tail. <see cref="Compact"/> rewrites live entries into a fresh file committed with
|
||||
/// <see cref="AtomicFile"/>. Reads use positional I/O and run concurrently with one writer.</para>
|
||||
/// </summary>
|
||||
public sealed class ThumbnailPack : IDisposable
|
||||
{
|
||||
public const int LongEdge = 320;
|
||||
public const int Quality = 80;
|
||||
public const int IndexInterval = 64;
|
||||
|
||||
private const uint HeaderMagic = 0x4B505454; // "TTPK"
|
||||
private const uint EntryMagic = 0x544E4554; // "TENT"
|
||||
private const uint IndexMagic = 0x58444954; // "TIDX"
|
||||
private const ushort Version = 1;
|
||||
private const int SlotSize = 64;
|
||||
private const int DataStart = 2 * SlotSize;
|
||||
private const int EntryHeaderSize = 32;
|
||||
private const int IndexEntrySize = 36;
|
||||
private const int MaxJpegBytes = 16 << 20;
|
||||
|
||||
private readonly ReaderWriterLockSlim _handleLock = new(LockRecursionPolicy.NoRecursion);
|
||||
private readonly Lock _writeLock = new();
|
||||
private readonly List<string> _warnings = [];
|
||||
private ConcurrentDictionary<Guid, ThumbnailEntry> _index = new();
|
||||
private SafeFileHandle _handle;
|
||||
private long _tail;
|
||||
private ulong _generation;
|
||||
private int _activeSlot;
|
||||
private int _unindexed;
|
||||
private long _liveBytes;
|
||||
private bool _disposed;
|
||||
|
||||
private ThumbnailPack(string path, bool writable, SafeFileHandle handle)
|
||||
{
|
||||
Path = path;
|
||||
Writable = writable;
|
||||
_handle = handle;
|
||||
Load();
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
public bool Writable { get; }
|
||||
|
||||
/// <summary>Problems met while opening or refreshing (damaged slots, records dropped from the tail).</summary>
|
||||
public IReadOnlyList<string> Warnings
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_warnings) return [.. _warnings];
|
||||
}
|
||||
}
|
||||
|
||||
public int Count => Volatile.Read(ref _index).Count;
|
||||
|
||||
/// <summary>Snapshot of the frames with a thumbnail.</summary>
|
||||
public IReadOnlyCollection<Guid> FrameIds => [.. Volatile.Read(ref _index).Keys];
|
||||
|
||||
/// <summary>Bytes held by superseded or removed entries (reclaimed by <see cref="Compact"/>).</summary>
|
||||
public long WastedBytes => long.Max(0, _tail - DataStart - Volatile.Read(ref _liveBytes));
|
||||
|
||||
/// <summary>Opens (creating when writable and missing) a pack.</summary>
|
||||
public static ThumbnailPack Open(string path, bool writable = true)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||
if (writable && !File.Exists(path)) AtomicFile.WriteAllBytes(path, EmptyFile());
|
||||
var handle = File.OpenHandle(path, FileMode.Open, writable ? FileAccess.ReadWrite : FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess);
|
||||
return new ThumbnailPack(path, writable, handle);
|
||||
}
|
||||
|
||||
/// <summary>Downscales a linear-light image to the thumbnail long edge and encodes it (JPEG q80).</summary>
|
||||
public static (byte[] Jpeg, int Width, int Height) Encode(ImageBuffer image)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
using var small = Resampler.Thumbnail(image, LongEdge);
|
||||
return (JpegEncoder.Encode(small, new JpegEncodeOptions { Quality = Quality }), small.Width, small.Height);
|
||||
}
|
||||
|
||||
public bool TryGetEntry(Guid frameId, out ThumbnailEntry entry) => Volatile.Read(ref _index).TryGetValue(frameId, out entry);
|
||||
|
||||
/// <summary>The JPEG bytes of a frame's thumbnail; null when absent or damaged (CRC mismatch).</summary>
|
||||
public byte[]? ReadJpeg(Guid frameId)
|
||||
{
|
||||
if (!TryGetEntry(frameId, out var e)) return null;
|
||||
var data = new byte[e.Length];
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (RandomAccess.Read(_handle, data, e.Offset + EntryHeaderSize) != data.Length) return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
return Crc32.Compute(data) == e.Crc ? data : null;
|
||||
}
|
||||
|
||||
/// <summary>Encodes and appends the thumbnail of <paramref name="image"/>, replacing any previous one for the frame.</summary>
|
||||
public ThumbnailEntry Add(Guid frameId, ImageBuffer image)
|
||||
{
|
||||
var (jpeg, w, h) = Encode(image);
|
||||
return AddJpeg(frameId, jpeg, w, h);
|
||||
}
|
||||
|
||||
/// <summary>Appends an encoded thumbnail, replacing any previous one for the frame.</summary>
|
||||
public ThumbnailEntry AddJpeg(Guid frameId, ReadOnlySpan<byte> jpeg, int width, int height)
|
||||
{
|
||||
if (!Writable) throw new InvalidOperationException("The pack is open read-only.");
|
||||
if (jpeg.Length is 0 or > MaxJpegBytes) throw new ArgumentOutOfRangeException(nameof(jpeg));
|
||||
if (width is < 1 or > ushort.MaxValue || height is < 1 or > ushort.MaxValue) throw new ArgumentOutOfRangeException(nameof(width));
|
||||
lock (_writeLock)
|
||||
{
|
||||
var record = new byte[EntryHeaderSize + jpeg.Length];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record, EntryMagic);
|
||||
frameId.TryWriteBytes(record.AsSpan(4));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(20), (ushort)width);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(record.AsSpan(22), (ushort)height);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(record.AsSpan(24), jpeg.Length);
|
||||
var crc = Crc32.Compute(jpeg);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(28), crc);
|
||||
jpeg.CopyTo(record.AsSpan(EntryHeaderSize));
|
||||
var entry = new ThumbnailEntry(frameId, _tail, jpeg.Length, width, height, crc);
|
||||
WriteAt(record, _tail);
|
||||
_tail += record.Length;
|
||||
if (_index.TryGetValue(frameId, out var old)) Interlocked.Add(ref _liveBytes, -(EntryHeaderSize + old.Length));
|
||||
_index[frameId] = entry;
|
||||
Interlocked.Add(ref _liveBytes, record.Length);
|
||||
if (++_unindexed >= IndexInterval) WriteIndex();
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops a frame's thumbnail from the index (its bytes stay until <see cref="Compact"/>).</summary>
|
||||
public bool Remove(Guid frameId)
|
||||
{
|
||||
if (!Writable) throw new InvalidOperationException("The pack is open read-only.");
|
||||
lock (_writeLock)
|
||||
{
|
||||
if (!_index.TryRemove(frameId, out var old)) return false;
|
||||
Interlocked.Add(ref _liveBytes, -(EntryHeaderSize + old.Length));
|
||||
_unindexed++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes the index now (appended record, then the alternate header slot).</summary>
|
||||
public void Flush()
|
||||
{
|
||||
if (!Writable) return;
|
||||
lock (_writeLock)
|
||||
{
|
||||
if (_unindexed > 0) WriteIndex();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rewrites the live entries into a new file and atomically replaces this one.</summary>
|
||||
public void Compact()
|
||||
{
|
||||
if (!Writable) throw new InvalidOperationException("The pack is open read-only.");
|
||||
lock (_writeLock)
|
||||
{
|
||||
var temp = AtomicFile.TempPathFor(Path);
|
||||
var entries = Volatile.Read(ref _index).Values.OrderBy(e => e.Offset).ToList();
|
||||
var moved = new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
using (var output = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16))
|
||||
{
|
||||
output.Write(new byte[DataStart]);
|
||||
var buffer = new byte[EntryHeaderSize + MaxJpegBytes / 16];
|
||||
foreach (var e in entries)
|
||||
{
|
||||
var size = EntryHeaderSize + e.Length;
|
||||
if (buffer.Length < size) buffer = new byte[size];
|
||||
_handleLock.EnterReadLock();
|
||||
int read;
|
||||
try
|
||||
{
|
||||
read = RandomAccess.Read(_handle, buffer.AsSpan(0, size), e.Offset);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
if (read != size || Crc32.Compute(buffer.AsSpan(EntryHeaderSize, e.Length)) != e.Crc)
|
||||
{
|
||||
Warn($"Thumbnail of {e.FrameId} damaged; dropped during compaction");
|
||||
continue;
|
||||
}
|
||||
moved[e.FrameId] = e with { Offset = output.Position };
|
||||
output.Write(buffer, 0, size);
|
||||
}
|
||||
var indexOffset = output.Position;
|
||||
var index = IndexRecord(moved.Values);
|
||||
output.Write(index);
|
||||
output.Position = 0;
|
||||
output.Write(HeaderSlot(_generation + 1, indexOffset, index.Length, moved.Count, indexOffset + index.Length));
|
||||
}
|
||||
_handleLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_handle.Dispose();
|
||||
AtomicFile.Commit(temp, Path);
|
||||
_handle = File.OpenHandle(Path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess);
|
||||
_index = moved;
|
||||
_generation++;
|
||||
_activeSlot = 0;
|
||||
_tail = RandomAccess.GetLength(_handle);
|
||||
_liveBytes = moved.Values.Sum(e => (long)EntryHeaderSize + e.Length);
|
||||
_unindexed = 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the file (read-only instances use it to see entries written by another instance).</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
if (Writable) return;
|
||||
_handleLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
_handle.Dispose();
|
||||
_handle = File.OpenHandle(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitWriteLock();
|
||||
}
|
||||
Load();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
if (Writable)
|
||||
{
|
||||
try
|
||||
{
|
||||
Flush();
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
Warn("Index not written on close: " + ex.Message);
|
||||
}
|
||||
}
|
||||
_handleLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_disposed = true;
|
||||
_handle.Dispose();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitWriteLock();
|
||||
}
|
||||
_handleLock.Dispose();
|
||||
}
|
||||
|
||||
private static byte[] EmptyFile()
|
||||
{
|
||||
var file = new byte[DataStart];
|
||||
HeaderSlot(1, 0, 0, 0, DataStart).CopyTo(file, 0);
|
||||
return file;
|
||||
}
|
||||
|
||||
private static byte[] HeaderSlot(ulong generation, long indexOffset, int indexLength, int count, long dataEnd)
|
||||
{
|
||||
var slot = new byte[SlotSize];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(slot, HeaderMagic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(slot.AsSpan(4), Version);
|
||||
BinaryPrimitives.WriteUInt64LittleEndian(slot.AsSpan(8), generation);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(slot.AsSpan(16), indexOffset);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(slot.AsSpan(24), indexLength);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(slot.AsSpan(28), count);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(slot.AsSpan(32), dataEnd);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(slot.AsSpan(SlotSize - 4), Crc32.Compute(slot.AsSpan(0, SlotSize - 4)));
|
||||
return slot;
|
||||
}
|
||||
|
||||
private static byte[] IndexRecord(IEnumerable<ThumbnailEntry> entries)
|
||||
{
|
||||
var list = entries.ToList();
|
||||
var record = new byte[8 + list.Count * IndexEntrySize + 4];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record, IndexMagic);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(record.AsSpan(4), list.Count);
|
||||
for (var i = 0; i < list.Count; i++)
|
||||
{
|
||||
var s = record.AsSpan(8 + i * IndexEntrySize, IndexEntrySize);
|
||||
var e = list[i];
|
||||
e.FrameId.TryWriteBytes(s);
|
||||
BinaryPrimitives.WriteInt64LittleEndian(s[16..], e.Offset);
|
||||
BinaryPrimitives.WriteInt32LittleEndian(s[24..], e.Length);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(s[28..], (ushort)e.Width);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(s[30..], (ushort)e.Height);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(s[32..], e.Crc);
|
||||
}
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(record.AsSpan(record.Length - 4), Crc32.Compute(record.AsSpan(0, record.Length - 4)));
|
||||
return record;
|
||||
}
|
||||
|
||||
/// <summary>Appends an index record, flushes, then commits it through the header slot not holding the newest generation.</summary>
|
||||
private void WriteIndex()
|
||||
{
|
||||
var index = Volatile.Read(ref _index);
|
||||
var record = IndexRecord(index.Values);
|
||||
var offset = _tail;
|
||||
WriteAt(record, offset);
|
||||
_tail += record.Length;
|
||||
RandomAccess.FlushToDisk(_handle);
|
||||
var slot = 1 - _activeSlot;
|
||||
WriteAt(HeaderSlot(_generation + 1, offset, record.Length, index.Count, _tail), slot * SlotSize);
|
||||
RandomAccess.FlushToDisk(_handle);
|
||||
_generation++;
|
||||
_activeSlot = slot;
|
||||
_unindexed = 0;
|
||||
}
|
||||
|
||||
private void WriteAt(ReadOnlySpan<byte> data, long offset)
|
||||
{
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
RandomAccess.Write(_handle, data, offset);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
private void Warn(string message)
|
||||
{
|
||||
lock (_warnings)
|
||||
{
|
||||
if (_warnings.Count < 32) _warnings.Add(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the newest valid header slot and its index, then recovers entries appended after it.</summary>
|
||||
private void Load()
|
||||
{
|
||||
long length;
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
length = RandomAccess.GetLength(_handle);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
var index = new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
long scanFrom = DataStart;
|
||||
(_generation, _activeSlot) = (0, 1);
|
||||
var slots = new byte[DataStart];
|
||||
var slotBytes = ReadAt(slots, 0);
|
||||
for (var s = 0; s < 2; s++)
|
||||
{
|
||||
if (slotBytes < (s + 1) * SlotSize || ParseSlot(slots.AsSpan(s * SlotSize, SlotSize)) is not { } h)
|
||||
{
|
||||
if (slotBytes >= (s + 1) * SlotSize && slots.AsSpan(s * SlotSize, SlotSize).ContainsAnyExcept((byte)0)) Warn($"Header slot {s} damaged");
|
||||
continue;
|
||||
}
|
||||
if (h.Generation <= _generation) continue;
|
||||
var loaded = h.IndexLength > 0 ? ReadIndex(h.IndexOffset, h.IndexLength, length) : new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
if (loaded is null)
|
||||
{
|
||||
Warn($"Index of header slot {s} damaged");
|
||||
continue;
|
||||
}
|
||||
(_generation, _activeSlot) = (h.Generation, s);
|
||||
index = loaded;
|
||||
scanFrom = h.DataEnd;
|
||||
}
|
||||
if (_generation == 0) Warn("No valid header; entries recovered by scanning");
|
||||
_tail = length <= DataStart ? DataStart : Recover(index, long.Clamp(scanFrom, DataStart, length), length);
|
||||
_index = index;
|
||||
_liveBytes = index.Values.Sum(e => (long)EntryHeaderSize + e.Length);
|
||||
_unindexed = 0;
|
||||
}
|
||||
|
||||
private readonly record struct Slot(ulong Generation, long IndexOffset, int IndexLength, long DataEnd);
|
||||
|
||||
private static Slot? ParseSlot(ReadOnlySpan<byte> s)
|
||||
{
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(s) != HeaderMagic || BinaryPrimitives.ReadUInt16LittleEndian(s[4..]) != Version) return null;
|
||||
if (Crc32.Compute(s[..(SlotSize - 4)]) != BinaryPrimitives.ReadUInt32LittleEndian(s[(SlotSize - 4)..])) return null;
|
||||
return new Slot(BinaryPrimitives.ReadUInt64LittleEndian(s[8..]), BinaryPrimitives.ReadInt64LittleEndian(s[16..]),
|
||||
BinaryPrimitives.ReadInt32LittleEndian(s[24..]), BinaryPrimitives.ReadInt64LittleEndian(s[32..]));
|
||||
}
|
||||
|
||||
private ConcurrentDictionary<Guid, ThumbnailEntry>? ReadIndex(long offset, int length, long fileLength)
|
||||
{
|
||||
if (offset < DataStart || length < 12 || offset > fileLength - length || (length - 12) % IndexEntrySize != 0) return null;
|
||||
var record = new byte[length];
|
||||
if (ReadAt(record, offset) != length) return null;
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(record) != IndexMagic
|
||||
|| Crc32.Compute(record.AsSpan(0, length - 4)) != BinaryPrimitives.ReadUInt32LittleEndian(record.AsSpan(length - 4))) return null;
|
||||
var count = BinaryPrimitives.ReadInt32LittleEndian(record.AsSpan(4));
|
||||
if (count != (length - 12) / IndexEntrySize) return null;
|
||||
var index = new ConcurrentDictionary<Guid, ThumbnailEntry>();
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var s = record.AsSpan(8 + i * IndexEntrySize, IndexEntrySize);
|
||||
var e = new ThumbnailEntry(new Guid(s[..16]), BinaryPrimitives.ReadInt64LittleEndian(s[16..]), BinaryPrimitives.ReadInt32LittleEndian(s[24..]),
|
||||
BinaryPrimitives.ReadUInt16LittleEndian(s[28..]), BinaryPrimitives.ReadUInt16LittleEndian(s[30..]), BinaryPrimitives.ReadUInt32LittleEndian(s[32..]));
|
||||
if (e.Offset >= DataStart && e.Length is > 0 and <= MaxJpegBytes && e.Offset <= fileLength - EntryHeaderSize - e.Length) index[e.FrameId] = e;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>Walks records from <paramref name="position"/>, adding valid entries (later ones win) and skipping index
|
||||
/// records; stops at the first damaged or truncated record. Returns the end of the last good record.</summary>
|
||||
private long Recover(ConcurrentDictionary<Guid, ThumbnailEntry> index, long position, long length)
|
||||
{
|
||||
var head = new byte[EntryHeaderSize];
|
||||
var recovered = 0;
|
||||
while (position + 12 <= length)
|
||||
{
|
||||
var n = ReadAt(head.AsSpan(0, (int)long.Min(EntryHeaderSize, length - position)), position);
|
||||
var magic = BinaryPrimitives.ReadUInt32LittleEndian(head);
|
||||
if (magic == IndexMagic && n >= 8)
|
||||
{
|
||||
var count = BinaryPrimitives.ReadInt32LittleEndian(head.AsSpan(4));
|
||||
var size = 12L + (long)count * IndexEntrySize;
|
||||
if (count < 0 || position + size > length || ReadIndex(position, (int)long.Min(size, int.MaxValue), length) is null) break;
|
||||
position += size;
|
||||
continue;
|
||||
}
|
||||
if (magic != EntryMagic || n < EntryHeaderSize) break;
|
||||
var jpegLength = BinaryPrimitives.ReadInt32LittleEndian(head.AsSpan(24));
|
||||
if (jpegLength is <= 0 or > MaxJpegBytes || position + EntryHeaderSize + jpegLength > length) break;
|
||||
var jpeg = new byte[jpegLength];
|
||||
if (ReadAt(jpeg, position + EntryHeaderSize) != jpegLength) break;
|
||||
var crc = BinaryPrimitives.ReadUInt32LittleEndian(head.AsSpan(28));
|
||||
if (Crc32.Compute(jpeg) != crc) break;
|
||||
var id = new Guid(head.AsSpan(4, 16));
|
||||
index[id] = new ThumbnailEntry(id, position, jpegLength, BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(20)), BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(22)), crc);
|
||||
position += EntryHeaderSize + jpegLength;
|
||||
recovered++;
|
||||
}
|
||||
if (position < length) Warn($"Ignored {length - position} damaged bytes at the end of the pack");
|
||||
if (recovered > 0) Warn($"Recovered {recovered} thumbnail(s) appended after the last index");
|
||||
return position;
|
||||
}
|
||||
|
||||
private int ReadAt(Span<byte> buffer, long offset)
|
||||
{
|
||||
_handleLock.EnterReadLock();
|
||||
try
|
||||
{
|
||||
var total = 0;
|
||||
while (total < buffer.Length)
|
||||
{
|
||||
var n = RandomAccess.Read(_handle, buffer[total..], offset + total);
|
||||
if (n == 0) break;
|
||||
total += n;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_handleLock.ExitReadLock();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user