From 3b0c74f9851c2cdd268d2fac96d6780ddc550a42 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Mon, 16 Nov 2026 05:13:14 +0300 Subject: [PATCH 1/3] Map preview image offsets through page file offsets and wrap bare bitmaps AcDb:Preview directory entries store absolute file offsets. ReadSection now reports each page's section position and payload file offset, and PreviewParser converts directory offsets to section positions through that layout, range-checking every candidate. Bitmap previews are stored as a bare DIB, so a 14-byte BMP file header with a computed pixel offset is added. ImageKind is derived from the bytes actually found instead of the directory slot, and invalid bytes no longer produce a Bmp preview. --- src/DwgIO/DwgDocument.cs | 23 +- .../Internal/Container/R2004Container.cs | 19 +- src/DwgIO/Internal/Parsing/PreviewParser.cs | 211 +++++++++++++++--- tests/DwgIO.Tests/DwgFixtureTests.cs | 5 +- tests/DwgIO.Tests/MetadataParserTests.cs | 112 ++++++++++ 5 files changed, 331 insertions(+), 39 deletions(-) diff --git a/src/DwgIO/DwgDocument.cs b/src/DwgIO/DwgDocument.cs index 3c3c448..ebf0955 100644 --- a/src/DwgIO/DwgDocument.cs +++ b/src/DwgIO/DwgDocument.cs @@ -35,7 +35,7 @@ private DwgDocument(string path, byte[] fileBytes, DwgFileHeader fileHeader, R20 { AppInfo = TryReadMetadata("AcDb:AppInfo", b => AppInfoParser.Parse(b, fileHeader.Codepage)); FileDepList = TryReadMetadata("AcDb:FileDepList", b => FileDepListParser.Parse(b, fileHeader.Codepage)); - Preview = TryReadMetadata("AcDb:Preview", PreviewParser.Parse); + Preview = ReadOptionalPreview(); } if (options.ReadObjects) @@ -241,6 +241,27 @@ private List ReadOptionalEntities() return entities; } + private DwgPreview? ReadOptionalPreview() + { + var entry = _container!.SectionMap.FindByName("AcDb:Preview"); + if (entry is null || entry.Encryption == 1) + { + return null; + } + + try + { + var pageLayout = new List(); + var bytes = _container.ReadSection(_fileBytes, entry, _verifyChecksums, pageLayout); + return PreviewParser.Parse(bytes, pageLayout); + } + catch (Exception ex) when (IsParseFailure(ex)) + { + _diagnostics.Add($"AcDb:Preview: {ex.Message}"); + return null; + } + } + private T? TryReadMetadata(string sectionName, Func parse) where T : class { diff --git a/src/DwgIO/Internal/Container/R2004Container.cs b/src/DwgIO/Internal/Container/R2004Container.cs index aa63553..4ebb330 100644 --- a/src/DwgIO/Internal/Container/R2004Container.cs +++ b/src/DwgIO/Internal/Container/R2004Container.cs @@ -2,6 +2,17 @@ namespace DwgIO.Internal.Container; +/// +/// One decompressed page of a section: where it starts in the section and where its +/// payload starts in the file. Absolute file offsets stored inside a section only map +/// linearly back to section positions when the page is stored uncompressed. +/// +internal readonly record struct SectionPageLayout( + int SectionOffset, + int Length, + long FileOffset, + bool IsStoredUncompressed); + /// /// The parsed R2004-family container: decrypted file header, /// page map and section map. Assembles named sections from their pages. @@ -49,8 +60,13 @@ public static R2004Container Parse(byte[] fileBytes) /// Pages starting past the section end are zero pages and skipped; /// gaps between page start offsets are filled with zeroes. /// When is set, a page checksum mismatch throws. + /// When is passed, it receives each page's section and file placement. /// - public byte[] ReadSection(byte[] fileBytes, SectionEntry entry, bool verifyChecksums = false) + public byte[] ReadSection( + byte[] fileBytes, + SectionEntry entry, + bool verifyChecksums = false, + List? pageLayout = null) { if (entry.Encryption == 1) { @@ -122,6 +138,7 @@ public byte[] ReadSection(byte[] fileBytes, SectionEntry entry, bool verifyCheck int start = (int)pageRef.StartOffset; int take = Math.Min(decompressed.Length, totalSize - start); Buffer.BlockCopy(decompressed, 0, result, start, take); + pageLayout?.Add(new SectionPageLayout(start, take, payloadStart, entry.Compression == 1)); } return result; diff --git a/src/DwgIO/Internal/Parsing/PreviewParser.cs b/src/DwgIO/Internal/Parsing/PreviewParser.cs index 0ce31ab..6503f70 100644 --- a/src/DwgIO/Internal/Parsing/PreviewParser.cs +++ b/src/DwgIO/Internal/Parsing/PreviewParser.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using DwgIO.Internal.Container; using DwgIO.Model; namespace DwgIO.Internal.Parsing; @@ -6,7 +7,9 @@ namespace DwgIO.Internal.Parsing; /// /// Parses the decompressed AcDb:Preview payload and extracts /// the thumbnail image (BMP code 2, WMF code 3, PNG code 6 — AutoCAD 2013+). -/// Falls back to carving image magic bytes out of the payload. +/// The directory stores absolute file offsets; they are mapped through the +/// section page layout when one is supplied. Falls back to carving image magic +/// bytes out of the payload. /// internal static class PreviewParser { @@ -18,8 +21,16 @@ internal static class PreviewParser private static readonly byte[] PngMagic = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + private static readonly byte[] WmfPlaceableMagic = [0xD7, 0xCD, 0xC6, 0x9A]; + + private static readonly uint[] DibHeaderSizes = [12, 16, 40, 52, 56, 64, 108, 124]; + /// Parses a Preview payload and returns its thumbnail image. - public static DwgPreview Parse(byte[] data) + public static DwgPreview Parse(byte[] data) => Parse(data, null); + + /// Parses a Preview payload, mapping absolute directory offsets through + /// the section's page layout when it is supplied. + public static DwgPreview Parse(byte[] data, IReadOnlyList? pages) { if (data.Length < 20 || !data.AsSpan(0, 16).SequenceEqual(StartSentinel)) { @@ -31,68 +42,200 @@ public static DwgPreview Parse(byte[] data) uint overallSize = cursor.ReadU32(); byte imagesPresent = cursor.ReadU8(); - (int start, int size)? headerData = null; - (int start, int size)? bmp = null; - (int start, int size)? wmf = null; - (int start, int size)? png = null; + (uint start, uint size)? bmp = null; + (uint start, uint size)? wmf = null; + (uint start, uint size)? png = null; for (int i = 0; i < imagesPresent; i++) { byte code = cursor.ReadU8(); uint start = cursor.ReadU32(); uint size = cursor.ReadU32(); - var range = (start: (int)start, size: (int)size); switch (code) { - case 1: headerData = range; break; - case 2: bmp = range; break; - case 3: wmf = range; break; - case 6: png = range; break; + case 2: bmp = (start, size); break; + case 3: wmf = (start, size); break; + case 6: png = (start, size); break; } } - // PNG previews masquerade as the bitmap slot on modern files. - var image = Extract(data, bmp) ?? Extract(data, png); - var kind = bmp is not null || image is not null ? DwgPreviewImageKind.Bmp : DwgPreviewImageKind.None; - if (IsPng(image)) + // Prefer the slot each format belongs to, but keep looking when a slot + // carries bytes that are not a valid image of that format. + var image = FindImage(data, bmp, pages, out var kind) + ?? FindImage(data, png, pages, out kind) + ?? FindImage(data, wmf, pages, out kind) + ?? CarveImageMagic(data); + + kind = image is null ? DwgPreviewImageKind.None : DetectKind(image); + if (kind == DwgPreviewImageKind.None) + { + image = null; + } + + return new DwgPreview + { + OverallSize = overallSize, + ImageKind = kind, + ImageBytes = image ?? [], + }; + } + + private static byte[]? FindImage( + byte[] data, + (uint start, uint size)? range, + IReadOnlyList? pages, + out DwgPreviewImageKind kind) + { + kind = DwgPreviewImageKind.None; + var bytes = Extract(data, range, pages); + if (bytes is null) + { + return null; + } + + if (IsPng(bytes)) { kind = DwgPreviewImageKind.Png; + return bytes; } - var wmfBytes = Extract(data, wmf); - if (image is null && wmfBytes is not null) + if (TryWrapBmp(bytes, out var bmpBytes)) + { + kind = DwgPreviewImageKind.Bmp; + return bmpBytes; + } + + if (IsWmf(bytes)) { - image = wmfBytes; kind = DwgPreviewImageKind.Wmf; + return bytes; } - if (image is null) + return null; + } + + private static DwgPreviewImageKind DetectKind(byte[] bytes) => + IsPng(bytes) ? DwgPreviewImageKind.Png + : bytes.Length >= 2 && bytes[0] == (byte)'B' && bytes[1] == (byte)'M' ? DwgPreviewImageKind.Bmp + : DwgPreviewImageKind.None; + + private static bool IsPng(byte[] bytes) => + bytes.Length >= PngMagic.Length && bytes.AsSpan(0, PngMagic.Length).SequenceEqual(PngMagic); + + private static bool IsWmf(byte[] bytes) => + bytes.Length >= WmfPlaceableMagic.Length && bytes.AsSpan(0, WmfPlaceableMagic.Length).SequenceEqual(WmfPlaceableMagic) + || bytes.Length >= 18 + && BinaryPrimitives.ReadUInt16LittleEndian(bytes) is 1 or 2 + && BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(2)) == 9; + + /// Adds the 14-byte BMP file header when the bytes are a bare DIB. + /// A bitmap directory entry stores the bitmap info header and pixels without "BM". + private static bool TryWrapBmp(byte[] bytes, out byte[] bmpBytes) + { + bmpBytes = bytes; + if (bytes.Length >= 14 && bytes[0] == (byte)'B' && bytes[1] == (byte)'M') { - image = CarveImageMagic(data); - kind = image is null ? DwgPreviewImageKind.None - : IsPng(image) ? DwgPreviewImageKind.Png - : DwgPreviewImageKind.Bmp; + return true; } - return new DwgPreview + if (!TryReadDibHeader(bytes, out int offBits)) { - OverallSize = overallSize, - ImageKind = kind, - ImageBytes = image ?? [], - }; + return false; + } + + var wrapped = new byte[14 + bytes.Length]; + wrapped[0] = (byte)'B'; + wrapped[1] = (byte)'M'; + BinaryPrimitives.WriteUInt32LittleEndian(wrapped.AsSpan(2), (uint)wrapped.Length); + BinaryPrimitives.WriteUInt32LittleEndian(wrapped.AsSpan(10), (uint)offBits); + Buffer.BlockCopy(bytes, 0, wrapped, 14, bytes.Length); + bmpBytes = wrapped; + return true; } - private static bool IsPng(byte[]? bytes) => - bytes is not null && bytes.Length >= PngMagic.Length && bytes.AsSpan(0, PngMagic.Length).SequenceEqual(PngMagic); + private static bool TryReadDibHeader(byte[] bytes, out int offBits) + { + offBits = 0; + if (bytes.Length < 12) + { + return false; + } + + uint headerSize = BinaryPrimitives.ReadUInt32LittleEndian(bytes); + if (!DibHeaderSizes.Contains(headerSize) || headerSize > bytes.Length) + { + return false; + } + + if (headerSize == 12) + { + ushort bitCount = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(10)); + int paletteEntries = bitCount <= 8 ? 1 << bitCount : 0; + long offset = 14 + 12 + paletteEntries * 3L; + if (offset > 14 + bytes.Length) + { + return false; + } + + offBits = (int)offset; + return true; + } + + ushort bitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(14)); + uint coloursUsed = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(32)); + long entries = coloursUsed != 0 ? coloursUsed : bitsPerPixel <= 8 ? 1u << bitsPerPixel : 0; + long headerOffset = 14 + headerSize + entries * 4L; + if (headerOffset > 14 + bytes.Length) + { + return false; + } + + offBits = (int)headerOffset; + return true; + } + + private static byte[]? Extract( + byte[] data, + (uint start, uint size)? range, + IReadOnlyList? pages) + { + if (range is not { } r || r.size == 0 || r.size > int.MaxValue) + { + return null; + } + + if (pages is not null) + { + foreach (var page in pages) + { + if (!page.IsStoredUncompressed || r.start < page.FileOffset) + { + continue; + } + + long relative = r.start - page.FileOffset; + if (relative + r.size > page.Length) + { + continue; + } + + return Take(data, page.SectionOffset + relative, (int)r.size); + } + } + + // Older writers stored section-relative offsets; accept them when the absolute + // interpretation does not fit any page. + return Take(data, r.start, (int)r.size); + } - private static byte[]? Extract(byte[] data, (int start, int size)? range) + private static byte[]? Take(byte[] data, long start, int size) { - if (range is not { } r || r.start <= 0 || r.size <= 0 || r.size > data.Length - r.start) + if (start < 0 || size <= 0 || start > data.Length - size) { return null; } - var bytes = new byte[r.size]; - Buffer.BlockCopy(data, r.start, bytes, 0, r.size); + var bytes = new byte[size]; + Buffer.BlockCopy(data, (int)start, bytes, 0, size); return bytes; } diff --git a/tests/DwgIO.Tests/DwgFixtureTests.cs b/tests/DwgIO.Tests/DwgFixtureTests.cs index ccb41e9..a9b8246 100644 --- a/tests/DwgIO.Tests/DwgFixtureTests.cs +++ b/tests/DwgIO.Tests/DwgFixtureTests.cs @@ -140,9 +140,8 @@ public void Preview_HasImageWhenSectionPresent() => CheckAll(path => Assert.True(doc.Preview is not null, $"AcDb:Preview present but not parsed; diagnostics: {Diagnostics(doc)}"); - // AC1032 files carry PNG previews that extract cleanly; older writers may store - // a body whose declared size overruns the section (a blank/FF thumbnail), and - // those legitimately extract to nothing. + // A preview section may still lack a usable image when its directory is absent, + // points outside the section, or does not describe a recognised image format. if (doc.Preview.ImageKind != DwgPreviewImageKind.None) { Assert.True(doc.Preview.HasImage, $"preview kind {doc.Preview.ImageKind} but no bytes"); diff --git a/tests/DwgIO.Tests/MetadataParserTests.cs b/tests/DwgIO.Tests/MetadataParserTests.cs index dba56ec..ffaafa7 100644 --- a/tests/DwgIO.Tests/MetadataParserTests.cs +++ b/tests/DwgIO.Tests/MetadataParserTests.cs @@ -1,3 +1,5 @@ +using System.Buffers.Binary; +using DwgIO.Internal.Container; using DwgIO.Internal.Parsing; using DwgIO.Model; using Xunit; @@ -108,6 +110,116 @@ public void Preview_PngExtraction() Assert.True(preview.HasImage); } + [Fact] + public void Preview_AbsoluteOffset_MapsThroughPageFileOffset() + { + var png = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0xFF, 0xEE }; + const long pageFileOffset = 1000; + const int position = 100; + var data = BuildPreviewSection( + [(0x06, (uint)(pageFileOffset + position), (uint)png.Length)], + position, + png); + var layout = new[] { new SectionPageLayout(0, data.Length, pageFileOffset, true) }; + + var preview = PreviewParser.Parse(data, layout); + + Assert.Equal(DwgPreviewImageKind.Png, preview.ImageKind); + Assert.Equal(png, preview.ImageBytes); + } + + [Theory] + [InlineData((ushort)8, 1078)] + [InlineData((ushort)24, 54)] + public void Preview_BareDib_GetsBmpFileHeader(ushort bitCount, int expectedOffBits) + { + var dib = BuildDib(bitCount); + const long pageFileOffset = 2048; + const int position = 64; + var data = BuildPreviewSection( + [(0x02, (uint)(pageFileOffset + position), (uint)dib.Length)], + position, + dib); + var layout = new[] { new SectionPageLayout(0, data.Length, pageFileOffset, true) }; + + var preview = PreviewParser.Parse(data, layout); + + Assert.Equal(DwgPreviewImageKind.Bmp, preview.ImageKind); + Assert.Equal("BM", System.Text.Encoding.ASCII.GetString(preview.ImageBytes, 0, 2)); + Assert.Equal(14 + dib.Length, preview.ImageBytes.Length); + Assert.Equal((uint)preview.ImageBytes.Length, BinaryPrimitives.ReadUInt32LittleEndian(preview.ImageBytes.AsSpan(2))); + Assert.Equal((uint)expectedOffBits, BinaryPrimitives.ReadUInt32LittleEndian(preview.ImageBytes.AsSpan(10))); + Assert.Equal(dib, preview.ImageBytes[14..]); + } + + [Fact] + public void Preview_InvalidImageBytes_ReturnsNoImage() + { + var junk = Enumerable.Repeat((byte)0x11, 100).ToArray(); + const long pageFileOffset = 500; + const int position = 40; + var data = BuildPreviewSection( + [(0x02, (uint)(pageFileOffset + position), (uint)junk.Length)], + position, + junk); + var layout = new[] { new SectionPageLayout(0, data.Length, pageFileOffset, true) }; + + var preview = PreviewParser.Parse(data, layout); + + Assert.Equal(DwgPreviewImageKind.None, preview.ImageKind); + Assert.False(preview.HasImage); + } + + private static byte[] BuildPreviewSection( + (byte Code, uint Start, uint Size)[] entries, + int imageOffset, + byte[] image) + { + var data = new List(); + data.AddRange(PreviewParserSentinels.Start); + WriteU32(data, (uint)(16 + 4 + 1 + entries.Length * 9 + imageOffset + image.Length)); + data.Add((byte)entries.Length); + foreach (var entry in entries) + { + data.Add(entry.Code); + WriteU32(data, entry.Start); + WriteU32(data, entry.Size); + } + + while (data.Count < imageOffset) + { + data.Add(0); + } + + data.AddRange(image); + data.AddRange(PreviewParserSentinels.End); + return [.. data]; + } + + private static byte[] BuildDib(ushort bitCount) + { + const int width = 2; + const int height = 2; + int paletteEntries = bitCount <= 8 ? 1 << bitCount : 0; + int stride = (width * bitCount + 31) / 32 * 4; + int pixelBytes = stride * height; + var dib = new byte[40 + paletteEntries * 4 + pixelBytes]; + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(0), 40); + BinaryPrimitives.WriteInt32LittleEndian(dib.AsSpan(4), width); + BinaryPrimitives.WriteInt32LittleEndian(dib.AsSpan(8), height); + BinaryPrimitives.WriteUInt16LittleEndian(dib.AsSpan(12), 1); + BinaryPrimitives.WriteUInt16LittleEndian(dib.AsSpan(14), bitCount); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(20), (uint)pixelBytes); + return dib; + } + + private static void WriteU32(List data, uint value) + { + Span buffer = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(buffer, value); + data.AddRange(buffer.ToArray()); + } + private static class PreviewParserSentinels { public static readonly byte[] Start = From 46e6ac14cef026eb7d258e3ea0f894c8e0d54024 Mon Sep 17 00:00:00 2001 From: mahach666 Date: Mon, 16 Nov 2026 12:10:02 +0300 Subject: [PATCH 2/3] Preserve WMF kind, fix BMP bitfield offset and spanning pages Keep the image kind found in its directory slot instead of re-detecting (which dropped WMF), include WMF in DetectKind, account BI_BITFIELDS masks in bfOffBits, and extract images whose bytes span consecutive uncompressed pages. --- src/DwgIO/Internal/Parsing/PreviewParser.cs | 92 ++++++++++++++++--- .../PreviewParserRegressionTests.cs | 68 ++++++++++++++ 2 files changed, 149 insertions(+), 11 deletions(-) create mode 100644 tests/DwgIO.Tests/PreviewParserRegressionTests.cs diff --git a/src/DwgIO/Internal/Parsing/PreviewParser.cs b/src/DwgIO/Internal/Parsing/PreviewParser.cs index 6503f70..05ff565 100644 --- a/src/DwgIO/Internal/Parsing/PreviewParser.cs +++ b/src/DwgIO/Internal/Parsing/PreviewParser.cs @@ -59,13 +59,28 @@ public static DwgPreview Parse(byte[] data, IReadOnlyList? pa } // Prefer the slot each format belongs to, but keep looking when a slot - // carries bytes that are not a valid image of that format. - var image = FindImage(data, bmp, pages, out var kind) - ?? FindImage(data, png, pages, out kind) - ?? FindImage(data, wmf, pages, out kind) - ?? CarveImageMagic(data); + // carries bytes that are not a valid image of that format. Keep the kind + // reported by FindImage: re-detecting would drop WMF, which DetectKind + // historically did not know. + byte[]? image = null; + var kind = DwgPreviewImageKind.None; + foreach (var slot in new[] { bmp, png, wmf }) + { + var bytes = FindImage(data, slot, pages, out var found); + if (bytes is not null) + { + image = bytes; + kind = found; + break; + } + } + + if (image is null) + { + image = CarveImageMagic(data); + kind = image is null ? DwgPreviewImageKind.None : DetectKind(image); + } - kind = image is null ? DwgPreviewImageKind.None : DetectKind(image); if (kind == DwgPreviewImageKind.None) { image = null; @@ -116,6 +131,7 @@ public static DwgPreview Parse(byte[] data, IReadOnlyList? pa private static DwgPreviewImageKind DetectKind(byte[] bytes) => IsPng(bytes) ? DwgPreviewImageKind.Png : bytes.Length >= 2 && bytes[0] == (byte)'B' && bytes[1] == (byte)'M' ? DwgPreviewImageKind.Bmp + : IsWmf(bytes) ? DwgPreviewImageKind.Wmf : DwgPreviewImageKind.None; private static bool IsPng(byte[] bytes) => @@ -183,7 +199,13 @@ private static bool TryReadDibHeader(byte[] bytes, out int offBits) ushort bitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(14)); uint coloursUsed = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(32)); long entries = coloursUsed != 0 ? coloursUsed : bitsPerPixel <= 8 ? 1u << bitsPerPixel : 0; - long headerOffset = 14 + headerSize + entries * 4L; + // With BI_BITFIELDS (3) or BI_ALPHABITFIELDS (6) three DWORD colour masks + // follow the 40-byte BITMAPINFOHEADER before the palette. + uint compression = headerSize >= 20 && bytes.Length >= 20 + ? BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(16)) + : 0; + int maskCount = headerSize == 40 && (compression == 3 || compression == 6) ? 3 : 0; + long headerOffset = 14 + headerSize + maskCount * 4L + entries * 4L; if (headerOffset > 14 + bytes.Length) { return false; @@ -205,20 +227,68 @@ private static bool TryReadDibHeader(byte[] bytes, out int offBits) if (pages is not null) { + // Absolute offsets map through the page holding the image start. The image + // may span pages: its bytes are contiguous in the assembled section, with + // a file-header gap between page payloads, so verify that the whole + // section range is covered by consecutive uncompressed pages. + long? sectionStart = null; foreach (var page in pages) { - if (!page.IsStoredUncompressed || r.start < page.FileOffset) + if (!page.IsStoredUncompressed) { continue; } - long relative = r.start - page.FileOffset; - if (relative + r.size > page.Length) + if ((long)r.start < page.FileOffset) { continue; } - return Take(data, page.SectionOffset + relative, (int)r.size); + long relative = (long)r.start - page.FileOffset; + if (relative >= page.Length) + { + continue; + } + + sectionStart = (long)page.SectionOffset + relative; + break; + } + + if (sectionStart.HasValue) + { + long sectionEnd = sectionStart.Value + r.size; + long covered = sectionStart.Value; + foreach (var page in pages + .Where(p => p.IsStoredUncompressed) + .OrderBy(p => p.SectionOffset)) + { + long intervalStart = page.SectionOffset; + long intervalEnd = intervalStart + page.Length; + if (intervalEnd <= covered) + { + continue; + } + + if (intervalStart > covered) + { + break; // gap in the assembled section + } + + covered = intervalEnd; + if (covered >= sectionEnd) + { + break; + } + } + + if (covered >= sectionEnd) + { + var spanning = Take(data, sectionStart.Value, (int)r.size); + if (spanning is not null) + { + return spanning; + } + } } } diff --git a/tests/DwgIO.Tests/PreviewParserRegressionTests.cs b/tests/DwgIO.Tests/PreviewParserRegressionTests.cs new file mode 100644 index 0000000..6184492 --- /dev/null +++ b/tests/DwgIO.Tests/PreviewParserRegressionTests.cs @@ -0,0 +1,68 @@ +using System.Buffers.Binary; +using DwgIO.Internal.Container; +using DwgIO.Internal.Parsing; +using DwgIO.Model; +using Xunit; + +namespace DwgIO.Tests; + +public class PreviewParserRegressionTests +{ + private static byte[] Preview(byte code, uint start, byte[] image) + { + var data = new byte[64 + image.Length + 16]; + Convert.FromHexString("1F256D07D43628289D57CA3F9D44102B").CopyTo(data, 0); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(16), (uint)data.Length); + data[20] = 1; + data[21] = code; + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(22), start); + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(26), (uint)image.Length); + image.CopyTo(data, 64); + Convert.FromHexString("E0DA92F82BC9D7D762A835C062BBEFD4").CopyTo(data, 64 + image.Length); + return data; + } + + private static byte[] BitfieldsDib() + { + var dib = new byte[56]; + BinaryPrimitives.WriteUInt32LittleEndian(dib, 40); + BinaryPrimitives.WriteInt32LittleEndian(dib.AsSpan(4), 1); + BinaryPrimitives.WriteInt32LittleEndian(dib.AsSpan(8), 1); + BinaryPrimitives.WriteUInt16LittleEndian(dib.AsSpan(12), 1); + BinaryPrimitives.WriteUInt16LittleEndian(dib.AsSpan(14), 16); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(16), 3); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(20), 4); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(40), 0xF800); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(44), 0x07E0); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(48), 0x001F); + BinaryPrimitives.WriteUInt16LittleEndian(dib.AsSpan(52), 0xF800); + return dib; + } + + [Fact] + public void Wmf_DirectoryEntry_PreservesImage() + { + byte[] wmf = Convert.FromHexString("0100090000030C0000000000030000000000030000000000"); + var preview = PreviewParser.Parse(Preview(3, 64, wmf)); + Assert.Equal(DwgPreviewImageKind.Wmf, preview.ImageKind); + Assert.Equal(wmf, preview.ImageBytes); + } + + [Fact] + public void BitfieldsDib_OffsetSkipsColorMasks() + { + var preview = PreviewParser.Parse(Preview(2, 64, BitfieldsDib())); + Assert.Equal(DwgPreviewImageKind.Bmp, preview.ImageKind); + Assert.Equal(66u, BinaryPrimitives.ReadUInt32LittleEndian(preview.ImageBytes.AsSpan(10))); + } + + [Fact] + public void AbsoluteDib_SpanningTwoPages_PreservesImage() + { + var data = Preview(2, 1064, BitfieldsDib()); + SectionPageLayout[] pages = [new(0, 92, 1000, true), new(92, data.Length - 92, 1124, true)]; + var preview = PreviewParser.Parse(data, pages); + Assert.Equal(DwgPreviewImageKind.Bmp, preview.ImageKind); + Assert.True(preview.HasImage); + } +} From 50eb322d0f562370f432e06106a1b1ecd1e18b0f Mon Sep 17 00:00:00 2001 From: mahach666 Date: Mon, 16 Nov 2026 12:37:06 +0300 Subject: [PATCH 3/3] Count four masks for BI_ALPHABITFIELDS DIBs BI_ALPHABITFIELDS carries red, green, blue and alpha masks after the 40-byte header; BI_BITFIELDS carries three. Add a 32bpp regression test expecting bfOffBits 70. --- src/DwgIO/Internal/Parsing/PreviewParser.cs | 11 ++++++++-- .../PreviewParserRegressionTests.cs | 21 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/DwgIO/Internal/Parsing/PreviewParser.cs b/src/DwgIO/Internal/Parsing/PreviewParser.cs index 05ff565..7955527 100644 --- a/src/DwgIO/Internal/Parsing/PreviewParser.cs +++ b/src/DwgIO/Internal/Parsing/PreviewParser.cs @@ -199,12 +199,19 @@ private static bool TryReadDibHeader(byte[] bytes, out int offBits) ushort bitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(14)); uint coloursUsed = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(32)); long entries = coloursUsed != 0 ? coloursUsed : bitsPerPixel <= 8 ? 1u << bitsPerPixel : 0; - // With BI_BITFIELDS (3) or BI_ALPHABITFIELDS (6) three DWORD colour masks + // With BI_BITFIELDS (3) three DWORD colour masks, and with + // BI_ALPHABITFIELDS (6) four DWORD masks (red, green, blue, alpha), // follow the 40-byte BITMAPINFOHEADER before the palette. uint compression = headerSize >= 20 && bytes.Length >= 20 ? BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(16)) : 0; - int maskCount = headerSize == 40 && (compression == 3 || compression == 6) ? 3 : 0; + int maskCount = headerSize == 40 ? compression switch + { + 3 => 3, + 6 => 4, + _ => 0, + } + : 0; long headerOffset = 14 + headerSize + maskCount * 4L + entries * 4L; if (headerOffset > 14 + bytes.Length) { diff --git a/tests/DwgIO.Tests/PreviewParserRegressionTests.cs b/tests/DwgIO.Tests/PreviewParserRegressionTests.cs index 6184492..1046694 100644 --- a/tests/DwgIO.Tests/PreviewParserRegressionTests.cs +++ b/tests/DwgIO.Tests/PreviewParserRegressionTests.cs @@ -56,6 +56,27 @@ public void BitfieldsDib_OffsetSkipsColorMasks() Assert.Equal(66u, BinaryPrimitives.ReadUInt32LittleEndian(preview.ImageBytes.AsSpan(10))); } + [Fact] + public void AlphaBitfields_FourMasks_AreBeforePixels() + { + var dib = new byte[60]; + BinaryPrimitives.WriteUInt32LittleEndian(dib, 40); + BinaryPrimitives.WriteInt32LittleEndian(dib.AsSpan(4), 1); + BinaryPrimitives.WriteInt32LittleEndian(dib.AsSpan(8), 1); + BinaryPrimitives.WriteUInt16LittleEndian(dib.AsSpan(12), 1); + BinaryPrimitives.WriteUInt16LittleEndian(dib.AsSpan(14), 32); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(16), 6); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(20), 4); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(40), 0x00FF0000); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(44), 0x0000FF00); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(48), 0x000000FF); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(52), 0xFF000000); + BinaryPrimitives.WriteUInt32LittleEndian(dib.AsSpan(56), 0xFFFF0000); + var preview = PreviewParser.Parse(Preview(2, 64, dib)); + Assert.Equal(DwgPreviewImageKind.Bmp, preview.ImageKind); + Assert.Equal(70u, BinaryPrimitives.ReadUInt32LittleEndian(preview.ImageBytes.AsSpan(10))); + } + [Fact] public void AbsoluteDib_SpanningTwoPages_PreservesImage() {