Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
More image formats: APNG, QOI, DDS, DICOM, OpenEXR and others
KnifeLemon15d9670b4934
diff --git a/README.ko.md b/README.ko.mdindex f6e5d109..d52e1b71 100644--- a/README.ko.md+++ b/README.ko.md@@ -29,7 +29,7 @@<table><tr><td width="33%" valign="top"><b>커서 바로 옆에서</b><br>앱 창을 열 필요가 없어요. 끌고 있는 파일에 맞는 형식만 지금 있는 자리에 나타나요.</td>- <td width="33%" valign="top"><b>180가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD를 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>+ <td width="33%" valign="top"><b>190가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD를 오피스·한컴오피스·LibreOffice 없이 변환해요.</td><td width="33%" valign="top"><b>내 컴퓨터 안에서만</b><br>아무것도 업로드하지 않아요. 오프라인으로 동작하고 결과는 원본 옆에 저장해요.</td></tr></table>@@ -81,7 +81,7 @@| 원본 | 변환 대상 ||---|---|-| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등)는 읽기 | 위 형식끼리(HEIC⁵), PDF, 크기 조정, 흑백 |+| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR 등; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등), DICOM, OpenEXR, HDR은 읽기 | 위 형식끼리(HEIC⁵), PDF, 크기 조정, 흑백 || **벡터**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF(벡터), PNG 등 이미지, SVG ↔ SVGZ, PDF → EPS/PS¹ || **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ; 합치기, 나누기, 페이지 범위 || **문서**: DOCX, DOCM, DOTX, EML · DOC, ODT, RTF, WPS, WPD, Pages 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML |@@ -90,7 +90,7 @@| **한글**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, 마크다운, HTML || **텍스트**: TXT, 마크다운, HTML · reStructuredText, LaTeX³ | PDF, DOCX, HWPX, EPUB || **전자책**: EPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ · LIT, LRF, CHM, PDB 등⁴ | PDF, EPUB, DOCX, TXT, HTML, HWPX · MOBI, AZW3⁴ |-| **동영상**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB 등 | MP4, WEBM, MOV, MKV, AVI, GIF, MP3, M4A, 720p |+| **동영상**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB 등 | MP4, WEBM, MOV, MKV, AVI, GIF, APNG, MP3, M4A, 720p || **오디오**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR 등 | MP3, M4A, WAV, FLAC, OGG, OPUS, AAC || **압축 파일**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG 등 | 압축 풀기, ZIP, 7Z, TAR, TAR.GZ; 여러 파일 → ZIP 하나 || **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |diff --git a/README.md b/README.mdindex c2f73df1..2d607e9c 100644--- a/README.md+++ b/README.md@@ -29,7 +29,7 @@<table><tr><td width="33%" valign="top"><b>Right at your cursor</b><br>No app window to open. The formats appear where you already are, only the ones that make sense for the files you drag.</td>- <td width="33%" valign="top"><b>180 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts and CAD work without Office, Hancom Office or LibreOffice.</td>+ <td width="33%" valign="top"><b>190 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts and CAD work without Office, Hancom Office or LibreOffice.</td><td width="33%" valign="top"><b>Stays on your computer</b><br>Nothing is uploaded. Filee works offline and saves the result next to the original.</td></tr></table>@@ -81,7 +81,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a| From | To ||---|---|-| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …) read | any of these (HEIC⁵), PDF, resized, grayscale |+| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR read | any of these (HEIC⁵), PDF, resized, grayscale || **Vector**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG² | PDF (vector), PNG and other images, SVG ↔ SVGZ, PDF → EPS/PS¹ || **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ; merge, split, page ranges || **Documents**: DOCX, DOCM, DOTX, EML · DOC, ODT, RTF, WPS, WPD, Pages, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML |@@ -90,7 +90,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a| **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML || **Text**: TXT, Markdown, HTML · reStructuredText, LaTeX³ | PDF, DOCX, HWPX, EPUB || **E-books**: EPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ · LIT, LRF, CHM, PDB, …⁴ | PDF, EPUB, DOCX, TXT, HTML, HWPX · MOBI, AZW3⁴ |-| **Video**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB, … | MP4, WEBM, MOV, MKV, AVI, GIF, MP3, M4A, 720p |+| **Video**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, TS, M2TS, 3GP, OGV, VOB, … | MP4, WEBM, MOV, MKV, AVI, GIF, APNG, MP3, M4A, 720p || **Audio**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR, … | MP3, M4A, WAV, FLAC, OGG, OPUS, AAC || **Archives**: ZIP, 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, ISO, CAB, DMG, ALZ, EGG, … | extract, ZIP, 7Z, TAR, TAR.GZ; any files → one ZIP || **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 9ca8989c..6e8464b8 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -29,7 +29,7 @@<table><tr><td width="33%" valign="top"><b>就在光标旁</b><br>无需打开应用窗口。只显示适合当前拖动文件的格式,就在你所在的位置。</td>- <td width="33%" valign="top"><b>180 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体和 CAD,无需 Office、韩文办公软件或 LibreOffice。</td>+ <td width="33%" valign="top"><b>190 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体和 CAD,无需 Office、韩文办公软件或 LibreOffice。</td><td width="33%" valign="top"><b>只在你的电脑上</b><br>不上传任何文件。Filee 离线工作,结果保存在原文件旁边。</td></tr></table>@@ -80,7 +80,7 @@| 源格式 | 目标格式 ||---|---|-| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)仅读取 | 上述格式互转(HEIC⁵)、PDF、缩放、灰度 |+| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、APNG、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC、QOI、DDS、PCX、MNG、CUR 等;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)、DICOM、OpenEXR、HDR 仅读取 | 上述格式互转(HEIC⁵)、PDF、缩放、灰度 || **矢量图**:SVG、SVGZ、EMF、WMF、AI · EPS、PS¹ · CDR、VSD、CGM、ODG² | PDF(矢量)、PNG 等图片、SVG ↔ SVGZ、PDF → EPS/PS¹ || **PDF** | DOCX、HWPX、TXT、PNG、JPG、TIFF、CBZ;合并、拆分、页码范围 || **文档**:DOCX、DOCM、DOTX、EML · DOC、ODT、RTF、WPS、WPD、Pages 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML |@@ -89,7 +89,7 @@| **HWP**:HWP、HWPX | PDF、PNG、DOCX、HWPX ↔ HWP、TXT、Markdown、HTML || **文本**:TXT、Markdown、HTML · reStructuredText、LaTeX³ | PDF、DOCX、HWPX、EPUB || **电子书**:EPUB、MOBI、AZW3、AZW、AZW4、FB2、CBZ、CBR、CB7、HTMLZ、TXTZ · LIT、LRF、CHM、PDB 等⁴ | PDF、EPUB、DOCX、TXT、HTML、HWPX · MOBI、AZW3⁴ |-| **视频**⁵:MP4、MOV、MKV、WEBM、AVI、WMV、FLV、MPEG、TS、M2TS、3GP、OGV、VOB 等 | MP4、WEBM、MOV、MKV、AVI、GIF、MP3、M4A、720p |+| **视频**⁵:MP4、MOV、MKV、WEBM、AVI、WMV、FLV、MPEG、TS、M2TS、3GP、OGV、VOB 等 | MP4、WEBM、MOV、MKV、AVI、GIF、APNG、MP3、M4A、720p || **音频**⁵:MP3、M4A、AAC、WAV、FLAC、OGG、OPUS、WMA、AIFF、AMR 等 | MP3、M4A、WAV、FLAC、OGG、OPUS、AAC || **压缩包**:ZIP、7Z、RAR、TAR、TAR.GZ、TAR.BZ2、TAR.XZ、GZ、ISO、CAB、DMG、ALZ、EGG 等 | 解压、ZIP、7Z、TAR、TAR.GZ;多个文件 → 一个 ZIP || **CAD**:DWG、DXF | PDF、SVG、PNG、DWG ↔ DXF |diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex da0fca5f..4de1b924 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -5,7 +5,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| Engine | How it gets there | Handles ||---|---|---|-| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM ↔ each other; HEIC (written with FFmpeg), XCF, camera RAW (LibRaw) and EMF/WMF (Windows) read |+| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, MNG, QOI, DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster, MIFF ↔ each other, and **APNG** (Filee's own reader and writer); HEIC (written with FFmpeg), XCF, camera RAW (LibRaw), DICOM (uncompressed ones by Filee's own reader), Photo CD, OpenEXR, Radiance HDR and EMF/WMF (Windows) read || Vector graphics | built in (Svg.Skia, SkiaSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, PDF-compatible AI → PDF || ICNS | built in | images → ICNS (16–1024 px), ICNS → images || PDFsharp | built in (library) | images → PDF, merge, split, page ranges |@@ -26,7 +26,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats || Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, reStructuredText and LaTeX ↔ Markdown/HTML/DOCX/ODT (and → RTF, EPUB, TXT) || Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PDF → EPS/PS, PostScript-based AI → PDF (images through PDF and PDFium) |-| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video, video → animated GIF or a still frame, audio extraction, audio ↔ audio, GIF and photos → MP4/WEBM/MOV, images → HEIC |+| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video, video → animated GIF / APNG or a still frame, audio extraction, audio ↔ audio, GIF, APNG and photos → MP4/WEBM/MOV, images → HEIC || Calibre | **optional download** (~216 MB, 660 MB on disk) | rare e-book formats: LIT, LRF, CHM, PDB, PML, RB, SNB, TCR, OEB → EPUB; EPUB → MOBI, AZW3, LIT, LRF, PDB, PML, RB, SNB, TCR |DOCX, XLSX, XLS, ODS and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX@@ -78,9 +78,45 @@ current.## Images and vector graphics-- **Animations.** An animated GIF or WebP keeps every frame and its timing when converted to GIF or WebP (animated- GIF ↔ animated WebP, lossy or lossless as the preset says) and becomes a multi-page TIFF; other targets get the first- frame. Multi-page TIFFs and PDFs stay one image per page in WebP.+- **Animations.** An animated GIF, WebP, APNG or MNG keeps every frame and its timing when converted to one of these+ (animated GIF ↔ animated WebP ↔ APNG ↔ MNG, WebP lossy or lossless as the preset says) and becomes a multi-page TIFF;+ other targets get the first frame. Multi-page TIFFs and PDFs stay one image per page in WebP.+- **APNG** (`Magick/Apng.cs`) is Filee's own code, written from the APNG specification: ImageMagick reads only an+ APNG's default image and writes APNG through an external FFmpeg. Every frame is an ordinary PNG decoded or encoded by+ ImageMagick; Filee handles the chunks around them.+ - Reading composes each frame onto the canvas as a player shows it: `fcTL` regions and offsets, blend `SOURCE` / `OVER`,+ dispose `NONE` / `BACKGROUND` / `PREVIOUS`, delays (a denominator of 0 means hundredths) and the loop count. A+ default image that comes before the first `fcTL` is not part of the animation and is skipped. Animated PNGs saved+ as `.png` are recognised by their `acTL` chunk and stay animated as GIF, WebP or APNG; other targets get the first+ frame.+ - Writing gives every frame the same pixel format (8-bit RGB, or RGBA when any frame is transparent or smaller than+ the canvas): the first frame is the default image (`IDAT`, so viewers without APNG support show it), the others are+ `fdAT` chunks holding only the rectangle that changed (dispose `NONE`, blend `SOURCE`); a frame identical to the one+ before lengthens its delay instead. Checked with FFmpeg's APNG demuxer.+ - APNG ↔ video needs FFmpeg: video → APNG uses its `apng` encoder and muxer (24-bit RGB, looping, the GIF's frame rate+ and width limits), APNG → MP4/WEBM/MOV its APNG demuxer. Animated WebP and GIF still reach video through GIF, a+ still picture through PNG.+- **More raster formats** through ImageMagick's own coders, each checked against `MagickNET.SupportedFormats` and+ converted there and back in `ImageFormatTests`: QOI, MNG (animated), DDS (DXT block compression, which is lossy; of+ a texture with mipmaps the largest image is read), PCX, CUR (at most 256 × 256, larger pictures are scaled down), XPM,+ XBM and WBMP (1-bit), PAM, PFM, SGI (`.sgi`, `.rgb`, `.rgba`, `.bw`, always read as SGI; ImageMagick would take+ `.rgb` for headerless pixels), Sun Raster (`.ras`, `.sun`) and MIFF. XBM, WBMP, PFM, PCX and Sun Raster are written+ without transparency (flattened onto the preset's background): PFM has none, and the alpha planes ImageMagick can+ put into PCX and Sun Raster are read by hardly any other program. Not offered: PICT, because ImageMagick can't read+ back direct-colour PICTs wider than about 130 pixels that it wrote itself.+- **Read only**: Photo CD (the 768 × 512 base image), OpenEXR and Radiance HDR. The bundled Magick.NET is the 8-bit+ (Q8) build without HDRI, so high-dynamic-range values are clipped to the displayable range and stored with 8 bits per+ channel; there is no tone mapping. Writing EXR or HDR from 8-bit pictures would only make larger files, so they are+ not targets.+- **DICOM** (`.dcm`, `.dicom`, read only). The Q8 build reads only 8-bit DICOM, while CT, MR and X-ray scanners store+ 12 or 16 bits, so `Magick/Dicom.cs` (written from the DICOM standard, PS3.5 and PS3.3 C.7.6.3 / C.11.2) reads+ uncompressed files itself: implicit and explicit VR little endian, explicit VR big endian and deflated files, with or+ without the 128-byte preamble; 8 or 16 bits allocated, signed or unsigned; MONOCHROME1 (inverted) and MONOCHROME2,+ RGB and YBR_FULL (interleaved or planar); every frame of a multi-frame file. Grey values go through the rescale+ slope / intercept and the file's first window (centre / width) like a viewer's default view, or are stretched over+ the file's range when there is no window, to 8 bits. Compressed pixel data (JPEG, JPEG-LS, JPEG 2000, RLE) is left to+ ImageMagick, which manages only 8-bit images; others fail with a message asking for an uncompressed export.+- **Fujifilm HEIF** (`.hif`) is read as HEIC.- **Layered files.** PSD/PSB convert from Photoshop's composite (ImageMagick merges the layers when a file was savedwithout "maximize compatibility"). GIMP XCF layers are composited at their offsets with their blend modes; hiddenlayers are left out. ImageMagick reads 8-bit XCF without zlib tile compression (GIMP 2.10+ "better but slower@@ -483,9 +519,9 @@ Filee (with the GPL source offer), then an `engines.json` component and an optio## FFmpeg-`Media/FfmpegConverter.cs` converts every video format to every video format, to animated GIF, to a still PNG frame-and to every audio format (the sound track); every audio format to every audio format; and GIF and PNG to MP4, WEBM-and MOV.+`Media/FfmpegConverter.cs` converts every video format to every video format, to animated GIF or APNG, to a still PNG+frame and to every audio format (the sound track); every audio format to every audio format; and GIF, APNG and PNG to+MP4, WEBM and MOV.Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on MP3 files.- The download is the gyan.dev **9.0.2 "full_build-shared"** Windows build (GPL-3.0, run as a separate program).@@ -506,6 +542,7 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on| DV | DV25 with the same NTSC/PAL frames as VOB, 48 kHz stereo PCM || MXF | OP1a with long-GOP MPEG-2 + 48 kHz PCM || GIF | two passes: palettegen over the whole clip, then paletteuse; 15/12/10 fps and at most 640/480/320 px wide (High/Balanced/Small) |+ | APNG | one pass with the `apng` encoder (24-bit RGB, mixed prediction) and muxer, looping; the same frame rates and widths as GIF || MP3 · M4A/M4B · AAC · OGG · OPUS · WEBA · MKA · WMA · MP2 · AC3 · AMR | LAME VBR (V0/V2/V5) or CBR · AAC · AAC (ADTS) · Vorbis · Opus · Opus · Opus · WMA 2 · MP2 · AC-3 · AMR-NB 12.2k (8 kHz mono) || WAV · AIFF · AU · CAF · VOC · FLAC | 16-bit PCM (WAV: 8/16/24/32-bit or 32-bit float; RF64 over 4 GB) · FLAC |@@ -540,9 +577,10 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" onPNG's ICC profile is read (`-flags2 +icc_profiles`), so primaries and transfer are tagged as the photo's (DisplayP3 stays P3); RGB → BT.709 YUV in TV range; transparency is premultiplied onto black. The size is kept (made even)unless it exceeds H.264/VP9 level 6.2 (8192 × 4352 pixels, 16384 per side) or the preset's maximum height. The- image engines' still picture → GIF edges cost 12 (`ImageEncoder.Edge`) and PNG → video 11, so a photo takes the- PNG route (21 < 22) while animated GIF/WebP, multi-page TIFF and PDF keep the GIF route (20): a moving video or a- slideshow of the pages.+ image engines' still picture → GIF and → APNG edges cost 12 (`ImageEncoder.Edge`) and PNG → video 11, so a photo+ takes the PNG route (21 < 22) while animated GIF/WebP/MNG, multi-page TIFF and PDF keep the GIF route (20): a moving+ video or a slideshow of the pages. APNG → video costs 11, so an APNG goes straight to video and nothing else detours+ through it.- **Images → HEIC** (`Heic/HeicWriter.cs`): ImageMagick has no HEVC encoder and FFmpeg no HEIF muxer, so the work issplit. ImageMagick reads any image it knows and applies the preset (orientation, resize, metadata; transparency isflattened onto the background colour, HEIC alpha needs an auxiliary picture Filee does not write) and writes andiff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 2828fbba..27aeea1a 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -60,7 +60,7 @@"engine.reason.error": "Error while checking","engine.reason.unsupported_platform": "Not available on this platform","engine.reason.needs_package": "Needs {0}. Install it in Settings → Engines",- "engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, PSD, camera RAW and more.\nQuality, size and DPI follow your preset.",+ "engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, camera RAW and more.\nQuality, size and DPI follow your preset.","engine.pdfium.description": "Renders PDF pages to PNG, JPG and TIFF (also multi-page TIFF and GIF) at the preset's resolution.","engine.pdfsharp.description": "Makes PDFs from images and merges, splits or cuts page ranges out of PDFs.","engine.rhwp.description": "Renders HWP/HWPX to PDF and converts HWP ↔ HWPX.\nIt also draws documents that reach PDF through HWPX (DOCX, XLSX, PPTX, e-books…).",@@ -78,7 +78,7 @@"engine.cad.description": "AutoCAD drawings: DWG ↔ DXF, and both to PDF, SVG and PNG.","engine.archive.description": "Extracts ZIP, 7Z, RAR, TAR, ISO and more, and packs ZIP, 7Z or TAR.GZ (7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) to PDF, EPUB, DOCX and text.\nAlso documents to EPUB and PDF to CBZ.",- "engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC and more.\nAlso extracts sound, makes GIFs and saves images as HEIC.",+ "engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC and more.\nAlso extracts sound, makes GIF and APNG animations and saves images as HEIC.","engine.pandoc.description": "Markdown and HTML ↔ ODT and RTF, DOCX → Markdown\nreStructuredText and LaTeX ↔ Markdown, HTML, DOCX and ODT","engine.ghostscript.description": "EPS, PostScript and older Illustrator files to PDF and images; PDF to EPS and PS.","engine.calibre.description": "Rare e-book formats (LIT, LRF, CHM, PDB, RB…) and Kindle output (MOBI, AZW3).",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex c0074be4..c8c34694 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -60,7 +60,7 @@"engine.reason.error": "확인 중 오류","engine.reason.unsupported_platform": "이 플랫폼에서는 사용할 수 없음","engine.reason.needs_package": "{0} 필요 (설정 → 변환 엔진에서 설치)",- "engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, PSD, 카메라 RAW 등 이미지를 변환해요.\n품질·크기·DPI는 프리셋대로 맞춰요.",+ "engine.magick.description": "JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, APNG, PSD, 카메라 RAW 등 이미지를 변환해요.\n품질·크기·DPI는 프리셋대로 맞춰요.","engine.pdfium.description": "PDF 페이지를 PNG, JPG, TIFF(여러 페이지 TIFF·GIF 포함)로 프리셋 해상도에 맞춰 그려요.","engine.pdfsharp.description": "이미지로 PDF를 만들고, PDF를 합치거나 나누거나 원하는 페이지만 잘라내요.","engine.rhwp.description": "HWP/HWPX를 PDF로 그리고, HWP ↔ HWPX를 바꿔요.\nHWPX를 거쳐 PDF가 되는 문서(DOCX, XLSX, PPTX, 전자책 등)도 그려요.",@@ -78,7 +78,7 @@"engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.","engine.archive.description": "ZIP, 7Z, RAR, TAR, ISO 등을 풀고, ZIP·7Z·TAR.GZ로 묶어요(7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2, 만화책(CBZ, CBR)을 PDF, EPUB, DOCX, 텍스트로 바꿔요.\n문서는 EPUB으로, PDF는 CBZ로도 만들어요.",- "engine.ffmpeg.description": "MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC 등 동영상·오디오를 변환해요.\n소리 추출, GIF 만들기, 이미지 → HEIC도 해요.",+ "engine.ffmpeg.description": "MP4, MOV, MKV, WEBM, MP3, M4A, WAV, FLAC 등 동영상·오디오를 변환해요.\n소리 추출, GIF·APNG 만들기, 이미지 → HEIC도 해요.","engine.pandoc.description": "마크다운·HTML ↔ ODT·RTF, DOCX → 마크다운\nreStructuredText·LaTeX ↔ 마크다운·HTML·DOCX·ODT","engine.ghostscript.description": "EPS, 포스트스크립트, 예전 일러스트레이터 파일을 PDF와 이미지로, PDF를 EPS·PS로.","engine.calibre.description": "드문 전자책 형식(LIT, LRF, CHM, PDB, RB…)과 킨들용 출력(MOBI, AZW3).",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 8ec41bb7..f66213e7 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -60,7 +60,7 @@"engine.reason.error": "检查时出错","engine.reason.unsupported_platform": "此平台不可用","engine.reason.needs_package": "需要 {0},请在“设置 → 转换引擎”中安装",- "engine.magick.description": "JPG、PNG、WEBP、AVIF、HEIC、TIFF、GIF、PSD、相机 RAW 等图片。\n质量、尺寸和 DPI 按预设处理。",+ "engine.magick.description": "JPG、PNG、WEBP、AVIF、HEIC、TIFF、GIF、APNG、PSD、相机 RAW 等图片。\n质量、尺寸和 DPI 按预设处理。","engine.pdfium.description": "按预设分辨率将 PDF 页面渲染为 PNG、JPG、TIFF(也支持多页 TIFF 和 GIF)。","engine.pdfsharp.description": "用图片生成 PDF,合并、拆分 PDF 或截取指定页码。","engine.rhwp.description": "将 HWP/HWPX 渲染为 PDF,并在 HWP ↔ HWPX 之间转换。\n经 HWPX 转为 PDF 的文档(DOCX、XLSX、PPTX、电子书等)也由它渲染。",@@ -78,7 +78,7 @@"engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。","engine.archive.description": "解压 ZIP、7Z、RAR、TAR、ISO 等,并打包为 ZIP、7Z 或 TAR.GZ(7-Zip)。","engine.ebook.description": "EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)转为 PDF、EPUB、DOCX 和文本。\n也能把文档转为 EPUB、把 PDF 转为 CBZ。",- "engine.ffmpeg.description": "MP4、MOV、MKV、WEBM、MP3、M4A、WAV、FLAC 等视频和音频。\n还能提取声音、制作 GIF、把图片保存为 HEIC。",+ "engine.ffmpeg.description": "MP4、MOV、MKV、WEBM、MP3、M4A、WAV、FLAC 等视频和音频。\n还能提取声音、制作 GIF 和 APNG、把图片保存为 HEIC。","engine.pandoc.description": "Markdown 和 HTML ↔ ODT、RTF,DOCX → Markdown\nreStructuredText、LaTeX ↔ Markdown、HTML、DOCX、ODT","engine.ghostscript.description": "EPS、PostScript 和旧版 Illustrator 文件转为 PDF 和图片;PDF 转为 EPS 和 PS。","engine.calibre.description": "少见的电子书格式(LIT、LRF、CHM、PDB、RB…)以及 Kindle 输出(MOBI、AZW3)。",diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.csindex b608376d..e9c4a115 100644--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs@@ -237,8 +237,9 @@ public sealed partial class PresetEditorViewModel : ObservableObjectpublic bool ShowPdfBuild => TargetId == "pdf";public bool ShowPdfSplit => TargetId == "pdf";- /// <summary>PDF → a single-image format: the pages can be stacked into one tall image (TIFF and GIF keep pages).</summary>- public bool ShowPdfCombine => TargetCategory == FormatCategory.Image && TargetId is not ("tiff" or "gif" or "ico" or "icns" or "svg" or "pdf");+ /// <summary>PDF → a single-image format: the pages can be stacked into one tall image (TIFF, GIF, APNG and MNG keep pages).</summary>+ public bool ShowPdfCombine => TargetCategory == FormatCategory.Image+ && TargetId is not ("tiff" or "gif" or "apng" or "mng" or "ico" or "cur" or "icns" or "svg" or "pdf");public bool ShowDocument => TargetId == "pdf";public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels;/// <summary>Mono / stereo for every audio target but AMR, which is mono by definition.</summary>diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex 46c2be56..26f7c34d 100644--- a/src/Filee.Core/Formats/FormatRegistry.cs+++ b/src/Filee.Core/Formats/FormatRegistry.cs@@ -21,7 +21,7 @@ public static class FormatRegistrynew("gif", "GIF", FormatCategory.Image, ["gif"]),new("ico", "ICO", FormatCategory.Image, ["ico"]),new("avif", "AVIF", FormatCategory.Image, ["avif"]),- new("heic", "HEIC", FormatCategory.Image, ["heic", "heif"]),+ new("heic", "HEIC", FormatCategory.Image, ["heic", "heif", "hif"]),new("jxl", "JPEG XL", FormatCategory.Image, ["jxl"]),new("jp2", "JPEG 2000", FormatCategory.Image, ["jp2", "j2k", "jpf", "jpx"]),new("psd", "PSD", FormatCategory.Image, ["psd"]),@@ -29,6 +29,24 @@ public static class FormatRegistrynew("tga", "TGA", FormatCategory.Image, ["tga", "icb", "vda", "vst"]),new("ppm", "PPM", FormatCategory.Image, ["ppm", "pgm", "pbm", "pnm"]),new("icns", "ICNS", FormatCategory.Image, ["icns"]),+ new("apng", "APNG", FormatCategory.Image, ["apng"]),+ new("mng", "MNG", FormatCategory.Image, ["mng"]),+ new("qoi", "QOI", FormatCategory.Image, ["qoi"]),+ new("dds", "DDS", FormatCategory.Image, ["dds"]),+ new("pcx", "PCX", FormatCategory.Image, ["pcx"]),+ new("cur", "CUR", FormatCategory.Image, ["cur"]),+ new("xpm", "XPM", FormatCategory.Image, ["xpm"]),+ new("xbm", "XBM", FormatCategory.Image, ["xbm"]),+ new("wbmp", "WBMP", FormatCategory.Image, ["wbmp"]),+ new("pam", "PAM", FormatCategory.Image, ["pam"]),+ new("pfm", "PFM", FormatCategory.Image, ["pfm"]),+ new("sgi", "SGI", FormatCategory.Image, ["sgi", "rgb", "rgba", "bw"]),+ new("ras", "Sun Raster", FormatCategory.Image, ["ras", "sun"]),+ new("miff", "MIFF", FormatCategory.Image, ["miff"]),+ new("dcm", "DICOM", FormatCategory.Image, ["dcm", "dicom"], Writable: false),+ new("pcd", "Photo CD", FormatCategory.Image, ["pcd"], Writable: false),+ new("exr", "OpenEXR", FormatCategory.Image, ["exr"], Writable: false),+ new("hdr", "Radiance HDR", FormatCategory.Image, ["hdr"], Writable: false),new("xcf", "XCF", FormatCategory.Image, ["xcf"], Writable: false),new("raw", "RAW", FormatCategory.Image,["dng", "cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "orf", "rw2", "raf", "pef", "dcr", "kdc",diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex 7e4f98ea..4df29b84 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -50,7 +50,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 10;+ public const int CurrentSchemaVersion = 11;public int SchemaVersion { get; set; } = CurrentSchemaVersion;diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex ae92ef14..bc9e8a08 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -360,6 +360,11 @@ internal static class SettingsMigrationspresets.Add(BuiltInData.CreatePresets().Single(p => p.Id == "remove-background"));changed = true;}++ // v11: more image formats (APNG, MNG, QOI, DDS, DICOM, OpenEXR, …, Fujifilm's .hif): the images donut learns+ // their extensions unless another donut already has them.+ if (from < 11)+ changed |= LearnExtensions(profiles, ClaimedExtensions(profiles));return changed;}@@ -373,17 +378,8 @@ internal static class SettingsMigrations}var presetIds = presets.Select(p => p.Id).ToHashSet();- // Extensions checked on a mixed-selection profile only limit that profile; they don't claim files.- var claimed = profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);- var defaults = BuiltInData.CreateProfiles().ToDictionary(p => p.Id);- foreach (var profile in profiles.Where(p => !p.IsFallback && defaults.ContainsKey(p.Id)))- {- foreach (var extension in defaults[profile.Id].Extensions.Where(claimed.Add))- {- profile.Extensions.Add(extension);- changed = true;- }- }+ var claimed = ClaimedExtensions(profiles);+ changed |= LearnExtensions(profiles, claimed);var text = profiles.FindIndex(p => p.Id == "text");var insertAt = text >= 0 ? text + 1 : profiles.FindIndex(p => p.IsFallback);@@ -404,6 +400,29 @@ internal static class SettingsMigrationsreturn changed;}+ /// <summary>Extensions the user's donuts open. Those checked on a mixed-selection profile only limit that profile.</summary>+ private static HashSet<string> ClaimedExtensions(List<ToolbarProfile> profiles) =>+ profiles.Where(p => !p.IsFallback).SelectMany(p => p.Extensions).ToHashSet(StringComparer.OrdinalIgnoreCase);++ /// <summary>+ /// Gives the built-in donuts the extensions their defaults have now, unless a donut already has them+ /// (<paramref name="claimed"/> gains what was added). Returns true when something was added.+ /// </summary>+ private static bool LearnExtensions(List<ToolbarProfile> profiles, HashSet<string> claimed)+ {+ var changed = false;+ var defaults = BuiltInData.CreateProfiles().ToDictionary(p => p.Id);+ foreach (var profile in profiles.Where(p => !p.IsFallback && defaults.ContainsKey(p.Id)))+ {+ foreach (var extension in defaults[profile.Id].Extensions.Where(claimed.Add))+ {+ profile.Extensions.Add(extension);+ changed = true;+ }+ }+ return changed;+ }+/// <summary>Presets that settings schema 7 puts on the built-in donuts: (donut, preset, after which preset).</summary>private static readonly (string Profile, string Preset, string After)[] Version7Offers =[diff --git a/src/Filee.Engines/Cad/CadConverter.cs b/src/Filee.Engines/Cad/CadConverter.csindex cf5309cd..08ee5c08 100644--- a/src/Filee.Engines/Cad/CadConverter.cs+++ b/src/Filee.Engines/Cad/CadConverter.cs@@ -104,7 +104,7 @@ public sealed class CadConverter(ILogger? logger = null) : IConverterusing var image = new MagickImage(data.ToArray());image.Density = new Density(dpi, dpi, DensityUnit.PixelsPerInch);ImageEncoder.ApplyOptions(image, step.Preset.Image, step.To);- image.Write(output, ImageEncoder.ToMagickFormat(step.To));+ ImageEncoder.WriteImage(image, output, step.To);}private void Report(string input, CadScene scene)diff --git a/src/Filee.Engines/Magick/Apng.cs b/src/Filee.Engines/Magick/Apng.csnew file mode 100644index 00000000..101e8e17--- /dev/null+++ b/src/Filee.Engines/Magick/Apng.cs@@ -0,0 +1,401 @@+// Animated PNG (APNG) reader and writer, written from the APNG specification (PNG 3rd edition, W3C, and Mozilla's+// original APNG 1.0 description). ImageMagick reads only the default image of an APNG and writes APNG through an+// external FFmpeg, so Filee assembles the chunks itself: every frame is an ordinary PNG encoded or decoded by+// ImageMagick, the animation is acTL (frame count, loops) plus one fcTL (region, delay, dispose and blend operations)+// per frame, the first frame's data in IDAT and the others' in fdAT chunks with a shared sequence number.++using System.Buffers.Binary;+using System.Text;+using Filee.Engines.Archives;+using ImageMagick;+using ImageMagick.Formats;++namespace Filee.Engines.Magick;++/// <summary>Reads APNG files into fully composed frames and writes frames as APNG.</summary>+internal static class Apng+{+ private static readonly byte[] Signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];++ /// <summary>The ticks per second of frame delays handed to ImageMagick (GIF's hundredths of a second).</summary>+ private const int TicksPerSecond = 100;++ /// <summary>Largest IDAT / fdAT chunk written; any size up to 2³¹ − 1 is allowed, smaller ones stream better.</summary>+ private const int MaxChunkData = 1 << 20;++ private const byte DisposeNone = 0, DisposeBackground = 1, DisposePrevious = 2;+ private const byte BlendSource = 0, BlendOver = 1;++ private sealed record Chunk(string Type, byte[] Data);++ /// <summary>One fcTL with the image data that follows it.</summary>+ private sealed class Frame(uint width, uint height, uint x, uint y, ushort delayNumerator, ushort delayDenominator, byte dispose, byte blend)+ {+ public uint Width { get; } = width;+ public uint Height { get; } = height;+ public uint X { get; } = x;+ public uint Y { get; } = y;+ public ushort DelayNumerator { get; } = delayNumerator;+ public ushort DelayDenominator { get; } = delayDenominator;+ public byte Dispose { get; } = dispose;+ public byte Blend { get; } = blend;+ public MemoryStream Data { get; } = new();+ }++ /// <summary>+ /// True when <paramref name="path"/> is a PNG with an acTL chunk before its image data, i.e. an animated PNG+ /// (often saved with the .png extension).+ /// </summary>+ public static bool IsAnimated(string path)+ {+ try+ {+ using var stream = File.OpenRead(path);+ Span<byte> header = stackalloc byte[8];+ if (stream.ReadAtLeast(header, 8, throwOnEndOfStream: false) < 8 || !header.SequenceEqual(Signature))+ return false;+ while (stream.ReadAtLeast(header, 8, throwOnEndOfStream: false) == 8)+ {+ var length = BinaryPrimitives.ReadUInt32BigEndian(header);+ var type = Encoding.ASCII.GetString(header[4..]);+ if (type == "acTL")+ return true;+ if (type is "IDAT" or "IEND" || length > int.MaxValue)+ return false;+ stream.Seek(length + 4L, SeekOrigin.Current); // data and CRC+ }+ return false;+ }+ catch (IOException)+ {+ return false;+ }+ }++ /// <summary>+ /// Reads every frame of an APNG, each composed onto the canvas as a player shows it (dispose and blend operations+ /// applied), with its delay and the loop count. A PNG without animation comes back as its one image; the default+ /// image of an APNG whose first frame comes after it is not part of the animation and is skipped.+ /// </summary>+ public static MagickImageCollection Read(string path)+ {+ var chunks = ReadChunks(File.ReadAllBytes(path));+ if (chunks.Count == 0 || chunks[0].Type != "IHDR" || chunks[0].Data.Length != 13)+ throw new InvalidDataException("The file is not a PNG image or is damaged.");+ var header = chunks[0].Data;+ var canvasWidth = BinaryPrimitives.ReadUInt32BigEndian(header);+ var canvasHeight = BinaryPrimitives.ReadUInt32BigEndian(header.AsSpan(4));++ var animation = chunks.FirstOrDefault(c => c.Type == "acTL");+ if (animation is null || animation.Data.Length != 8)+ return new MagickImageCollection(path, new MagickReadSettings { Format = MagickFormat.Png });+ var plays = BinaryPrimitives.ReadUInt32BigEndian(animation.Data.AsSpan(4));++ // Chunks every frame needs to decode like the default image: palette, transparency, colour space.+ var shared = new List<Chunk>();+ var frames = new List<Frame>();+ Frame? current = null;+ var seenImageData = false;+ foreach (var chunk in chunks.Skip(1))+ {+ switch (chunk.Type)+ {+ case "fcTL":+ current = ParseFrameControl(chunk.Data, canvasWidth, canvasHeight);+ frames.Add(current);+ break;+ case "IDAT":+ seenImageData = true;+ current?.Data.Write(chunk.Data); // without an fcTL before it, the default image is not a frame+ break;+ case "fdAT":+ if (chunk.Data.Length < 4 || current is null)+ throw new InvalidDataException("The APNG file is damaged (fdAT chunk).");+ current.Data.Write(chunk.Data.AsSpan(4)); // after the 4-byte sequence number+ break;+ case "IEND":+ case "acTL":+ break;+ default:+ if (!seenImageData)+ shared.Add(chunk);+ break;+ }+ }+ frames.RemoveAll(f => f.Data.Length == 0);+ if (frames.Count == 0)+ throw new InvalidDataException("The APNG file has no frames.");++ var collection = new MagickImageCollection();+ try+ {+ using var canvas = new MagickImage(MagickColors.Transparent, canvasWidth, canvasHeight);+ canvas.ColorSpace = ColorSpace.sRGB;+ for (var i = 0; i < frames.Count; i++)+ {+ var frame = frames[i];+ using var picture = new MagickImage(FramePng(header, shared, frame), new MagickReadSettings { Format = MagickFormat.Png });+ picture.Alpha(AlphaOption.Set);++ var dispose = i == 0 && frame.Dispose == DisposePrevious ? DisposeBackground : frame.Dispose;+ using var previous = dispose == DisposePrevious ? canvas.Clone() : null;++ canvas.Composite(picture, (int)frame.X, (int)frame.Y,+ frame.Blend == BlendOver ? CompositeOperator.Over : CompositeOperator.Copy, Channels.All);++ var composed = canvas.Clone();+ composed.Page = new MagickGeometry(0, 0, canvasWidth, canvasHeight);+ composed.AnimationTicksPerSecond = TicksPerSecond;+ composed.AnimationDelay = DelayTicks(frame.DelayNumerator, frame.DelayDenominator);+ composed.AnimationIterations = plays;+ // Every frame is the whole picture: the next one replaces it instead of being drawn over it.+ composed.GifDisposeMethod = GifDisposeMethod.Background;+ collection.Add(composed);++ if (dispose == DisposeBackground)+ {+ using var clear = new MagickImage(MagickColors.Transparent, frame.Width, frame.Height);+ canvas.Composite(clear, (int)frame.X, (int)frame.Y, CompositeOperator.Copy, Channels.All);+ }+ else if (previous is not null)+ {+ canvas.Composite(previous, 0, 0, CompositeOperator.Copy, Channels.All);+ }+ }+ return collection;+ }+ catch+ {+ collection.Dispose();+ throw;+ }+ }++ /// <summary>Delay in hundredths of a second; a denominator of 0 means hundredths (APNG specification).</summary>+ private static uint DelayTicks(ushort numerator, ushort denominator) =>+ (uint)Math.Round(numerator * (double)TicksPerSecond / (denominator == 0 ? 100 : denominator));++ private static Frame ParseFrameControl(byte[] data, uint canvasWidth, uint canvasHeight)+ {+ if (data.Length != 26)+ throw new InvalidDataException("The APNG file is damaged (fcTL chunk).");+ var span = data.AsSpan();+ var frame = new Frame(+ width: BinaryPrimitives.ReadUInt32BigEndian(span[4..]),+ height: BinaryPrimitives.ReadUInt32BigEndian(span[8..]),+ x: BinaryPrimitives.ReadUInt32BigEndian(span[12..]),+ y: BinaryPrimitives.ReadUInt32BigEndian(span[16..]),+ delayNumerator: BinaryPrimitives.ReadUInt16BigEndian(span[20..]),+ delayDenominator: BinaryPrimitives.ReadUInt16BigEndian(span[22..]),+ dispose: span[24],+ blend: span[25]);+ if (frame.Width == 0 || frame.Height == 0 || (ulong)frame.X + frame.Width > canvasWidth+ || (ulong)frame.Y + frame.Height > canvasHeight || frame.Dispose > DisposePrevious || frame.Blend > BlendOver)+ throw new InvalidDataException("The APNG file is damaged (a frame lies outside the picture).");+ return frame;+ }++ /// <summary>A standalone PNG of one frame: the file's header with the frame's size, the shared chunks and its data.</summary>+ private static byte[] FramePng(byte[] header, List<Chunk> shared, Frame frame)+ {+ using var png = new MemoryStream();+ png.Write(Signature);+ var frameHeader = (byte[])header.Clone();+ BinaryPrimitives.WriteUInt32BigEndian(frameHeader, frame.Width);+ BinaryPrimitives.WriteUInt32BigEndian(frameHeader.AsSpan(4), frame.Height);+ WriteChunk(png, "IHDR", frameHeader);+ foreach (var chunk in shared)+ WriteChunk(png, chunk.Type, chunk.Data);+ WriteChunk(png, "IDAT", frame.Data.ToArray());+ WriteChunk(png, "IEND", []);+ return png.ToArray();+ }++ /// <summary>+ /// Writes <paramref name="frames"/> as one APNG. Frames are placed at the top left of a canvas as large as the+ /// largest frame. Each frame after the first stores only the rectangle that changed (dispose "none", blend+ /// "source"), and a frame identical to the one before only lengthens its delay. Every frame is 8-bit RGB, or RGBA+ /// when any frame has transparency, because all frames of an APNG share the header's pixel format.+ /// </summary>+ public static void Write(IReadOnlyList<IMagickImage<byte>> frames, string path)+ {+ if (frames.Count == 0)+ throw new ArgumentException("No frames to write.", nameof(frames));+ var width = frames.Max(f => f.Width);+ var height = frames.Max(f => f.Height);+ // Smaller frames are padded with transparency.+ var alpha = frames.Any(f => f.HasAlpha || f.Width != width || f.Height != height);+ var format = alpha ? MagickFormat.Png32 : MagickFormat.Png24;++ // Full-canvas pixels of every frame, to find what changed between them.+ var pictures = new List<(MagickImage Image, byte[] Pixels, uint DelayNumerator, uint DelayDenominator)>();+ try+ {+ foreach (var frame in frames)+ {+ var image = (MagickImage)frame.Clone();+ image.Page = new MagickGeometry(0, 0, image.Width, image.Height);+ if (image.Width != width || image.Height != height)+ {+ image.Alpha(AlphaOption.Set);+ image.BackgroundColor = MagickColors.Transparent;+ image.Extent(width, height, Gravity.Northwest);+ }+ var pixels = image.GetPixels().ToByteArray(PixelMapping.RGBA)!;+ var ticks = frame.AnimationTicksPerSecond > 0 ? (uint)frame.AnimationTicksPerSecond : TicksPerSecond;+ if (pictures.Count > 0 && pixels.AsSpan().SequenceEqual(pictures[^1].Pixels) && pictures[^1].DelayDenominator == ticks)+ {+ var last = pictures[^1];+ pictures[^1] = last with { DelayNumerator = last.DelayNumerator + frame.AnimationDelay };+ image.Dispose();+ continue;+ }+ pictures.Add((image, pixels, frame.AnimationDelay, ticks));+ }++ using var output = new MemoryStream();+ output.Write(Signature);+ byte[]? header = null;+ var sequence = 0u;+ for (var i = 0; i < pictures.Count; i++)+ {+ var (image, pixels, delayNumerator, delayDenominator) = pictures[i];+ var region = i == 0 ? (X: 0u, Y: 0u, Width: width, Height: height) : ChangedRegion(pictures[i - 1].Pixels, pixels, width, height);+ using var part = region.Width == width && region.Height == height+ ? (MagickImage)image.Clone()+ : (MagickImage)image.CloneArea(new MagickGeometry((int)region.X, (int)region.Y, region.Width, region.Height));+ part.Page = new MagickGeometry(0, 0, part.Width, part.Height);+ part.Settings.SetDefines(new PngWriteDefines { ExcludeChunks = PngChunkFlags.date });+ var encoded = ReadChunks(part.ToByteArray(format));+ var data = encoded.Where(c => c.Type == "IDAT").SelectMany(c => c.Data).ToArray();++ if (i == 0)+ {+ header = encoded[0].Data;+ WriteChunk(output, "IHDR", header);+ // Colour information and metadata of the first frame apply to the whole animation.+ foreach (var chunk in encoded.Skip(1).TakeWhile(c => c.Type != "IDAT"))+ WriteChunk(output, chunk.Type, chunk.Data);+ var control = new byte[8];+ BinaryPrimitives.WriteUInt32BigEndian(control, (uint)pictures.Count);+ BinaryPrimitives.WriteUInt32BigEndian(control.AsSpan(4), frames[0].AnimationIterations);+ WriteChunk(output, "acTL", control);+ }+ else if (!encoded[0].Data.AsSpan(8).SequenceEqual(header.AsSpan(8)))+ {+ throw new InvalidOperationException("APNG frames were encoded with different pixel formats.");+ }++ var (numerator, denominator) = FitDelay(delayNumerator, delayDenominator);+ var frameControl = new byte[26];+ var span = frameControl.AsSpan();+ BinaryPrimitives.WriteUInt32BigEndian(span, sequence++);+ BinaryPrimitives.WriteUInt32BigEndian(span[4..], part.Width);+ BinaryPrimitives.WriteUInt32BigEndian(span[8..], part.Height);+ BinaryPrimitives.WriteUInt32BigEndian(span[12..], region.X);+ BinaryPrimitives.WriteUInt32BigEndian(span[16..], region.Y);+ BinaryPrimitives.WriteUInt16BigEndian(span[20..], numerator);+ BinaryPrimitives.WriteUInt16BigEndian(span[22..], denominator);+ span[24] = DisposeNone;+ span[25] = BlendSource;+ WriteChunk(output, "fcTL", frameControl);++ var offset = 0;+ do+ {+ var piece = data.AsSpan(offset, Math.Min(MaxChunkData, data.Length - offset));+ offset += piece.Length;+ if (i == 0)+ {+ WriteChunk(output, "IDAT", piece);+ continue;+ }+ var sequenced = new byte[piece.Length + 4];+ BinaryPrimitives.WriteUInt32BigEndian(sequenced, sequence++);+ piece.CopyTo(sequenced.AsSpan(4));+ WriteChunk(output, "fdAT", sequenced);+ }+ while (offset < data.Length);+ }+ WriteChunk(output, "IEND", []);+ File.WriteAllBytes(path, output.ToArray());+ }+ finally+ {+ foreach (var picture in pictures)+ picture.Image.Dispose();+ }+ }++ /// <summary>The smallest rectangle holding every pixel that differs (at least one pixel).</summary>+ private static (uint X, uint Y, uint Width, uint Height) ChangedRegion(byte[] before, byte[] after, uint width, uint height)+ {+ var stride = (int)width * 4;+ int top = -1, bottom = -1, left = (int)width, right = -1;+ for (var y = 0; y < height; y++)+ {+ var rowBefore = before.AsSpan(y * stride, stride);+ var rowAfter = after.AsSpan(y * stride, stride);+ if (rowBefore.SequenceEqual(rowAfter))+ continue;+ if (top < 0)+ top = y;+ bottom = y;+ var first = rowBefore.CommonPrefixLength(rowAfter) / 4;+ var last = (int)width - 1;+ while (last > first && rowBefore.Slice(last * 4, 4).SequenceEqual(rowAfter.Slice(last * 4, 4)))+ last--;+ left = Math.Min(left, first);+ right = Math.Max(right, last);+ }+ if (top < 0)+ return (0, 0, 1, 1); // only the delay differs (another tick rate): repeat one pixel+ return ((uint)left, (uint)top, (uint)(right - left + 1), (uint)(bottom - top + 1));+ }++ /// <summary>Scales a delay down until both parts fit the 16-bit fields of fcTL.</summary>+ private static (ushort Numerator, ushort Denominator) FitDelay(uint numerator, uint denominator)+ {+ while (numerator > ushort.MaxValue || denominator > ushort.MaxValue)+ {+ numerator = (numerator + 1) / 2;+ denominator = Math.Max(1, (denominator + 1) / 2);+ }+ return ((ushort)numerator, (ushort)denominator);+ }++ private static List<Chunk> ReadChunks(byte[] file)+ {+ if (file.Length < 8 || !file.AsSpan(0, 8).SequenceEqual(Signature))+ throw new InvalidDataException("The file is not a PNG image.");+ var chunks = new List<Chunk>();+ var position = 8;+ while (position + 12 <= file.Length)+ {+ var length = BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(position));+ if (length > (uint)(file.Length - position - 12))+ throw new InvalidDataException("The PNG file is damaged (a chunk runs past the end).");+ var type = Encoding.ASCII.GetString(file, position + 4, 4);+ chunks.Add(new Chunk(type, file.AsSpan(position + 8, (int)length).ToArray()));+ position += 12 + (int)length;+ if (type == "IEND")+ break;+ }+ return chunks;+ }++ private static void WriteChunk(Stream stream, string type, ReadOnlySpan<byte> data)+ {+ Span<byte> number = stackalloc byte[4];+ BinaryPrimitives.WriteUInt32BigEndian(number, (uint)data.Length);+ stream.Write(number);+ var typeBytes = Encoding.ASCII.GetBytes(type);+ stream.Write(typeBytes);+ stream.Write(data);+ var crc = new Crc32();+ crc.Append(typeBytes);+ crc.Append(data);+ BinaryPrimitives.WriteUInt32BigEndian(number, crc.Value);+ stream.Write(number);+ }+}diff --git a/src/Filee.Engines/Magick/Dicom.cs b/src/Filee.Engines/Magick/Dicom.csnew file mode 100644index 00000000..4b76aa4f--- /dev/null+++ b/src/Filee.Engines/Magick/Dicom.cs@@ -0,0 +1,325 @@+// DICOM images (medical scans) stored without compression, read by Filee itself, written from the DICOM standard+// (PS3.5 data encoding, PS3.3 C.7.6.3 image pixel module, C.11.2 VOI LUT). ImageMagick's Q8 build reads only 8-bit+// DICOM: a 12- or 16-bit grey image, which CT, MR and X-ray scanners write, needs a palette larger than it has.+// Here every frame becomes an 8-bit picture: stored values → rescale slope / intercept → the file's first window+// (centre / width), or the full range of values when there is none. Compressed pixel data (JPEG, JPEG 2000, RLE, …)+// is left to ImageMagick.++using System.Buffers.Binary;+using System.Globalization;+using System.IO.Compression;+using System.Text;+using ImageMagick;++namespace Filee.Engines.Magick;++/// <summary>Reads uncompressed DICOM images into 8-bit frames.</summary>+internal static class Dicom+{+ private const uint UndefinedLength = 0xFFFFFFFF;++ private const string ImplicitLittleEndian = "1.2.840.10008.1.2";+ private const string ExplicitLittleEndian = "1.2.840.10008.1.2.1";+ private const string DeflatedExplicitLittleEndian = "1.2.840.10008.1.2.1.99";+ private const string ExplicitBigEndian = "1.2.840.10008.1.2.2";++ /// <summary>Value representations with a reserved 16 bits and a 32-bit length in explicit VR encoding.</summary>+ private static readonly HashSet<string> LongVrs = ["OB", "OD", "OF", "OL", "OV", "OW", "SQ", "SV", "UC", "UN", "UR", "UT", "UV"];++ private const uint PixelDataTag = 0x7FE00010;++ /// <summary>Elements of the image pixel module (and rescale / window) this reader uses.</summary>+ private static readonly HashSet<uint> Wanted =+ [+ 0x00280002, 0x00280004, 0x00280006, 0x00280008, 0x00280010, 0x00280011, 0x00280100, 0x00280101, 0x00280102,+ 0x00280103, 0x00281050, 0x00281051, 0x00281052, 0x00281053, PixelDataTag,+ ];++ /// <summary>+ /// The frames of <paramref name="path"/>, or null when its pixel data is compressed or laid out in a way this reader+ /// does not handle (palette colour, YBR subsampled), for ImageMagick to try.+ /// </summary>+ /// <exception cref="InvalidDataException">The file is not DICOM or is damaged.</exception>+ public static MagickImageCollection? TryRead(string path)+ {+ var file = File.ReadAllBytes(path);+ var position = file.Length >= 132 && file.AsSpan(128, 4).SequenceEqual("DICM"u8) ? 132 : 0;++ // File meta information (group 0002) is always explicit VR little endian.+ string? syntax = null;+ var meta = new Reader(file, position, explicitVr: true, bigEndian: false);+ while (meta.Position + 4 <= file.Length && meta.PeekGroup() == 0x0002)+ {+ var element = meta.Next();+ if (element.Tag == 0x00020010)+ syntax = Text(element.Value);+ }++ var data = file;+ var start = meta.Position;+ bool explicitVr, bigEndian = false;+ switch (syntax)+ {+ case null:+ // No meta information (older files): explicit if a value representation follows the first tag.+ explicitVr = start + 6 <= file.Length && char.IsAsciiLetterUpper((char)file[start + 4]) && char.IsAsciiLetterUpper((char)file[start + 5]);+ break;+ case ImplicitLittleEndian:+ explicitVr = false;+ break;+ case ExplicitLittleEndian:+ explicitVr = true;+ break;+ case ExplicitBigEndian:+ explicitVr = true;+ bigEndian = true;+ break;+ case DeflatedExplicitLittleEndian:+ using (var inflated = new MemoryStream())+ {+ using (var deflate = new DeflateStream(new MemoryStream(file, start, file.Length - start), CompressionMode.Decompress))+ deflate.CopyTo(inflated);+ data = inflated.ToArray();+ }+ start = 0;+ explicitVr = true;+ break;+ default:+ return null; // compressed (encapsulated) pixel data+ }++ var values = new Dictionary<uint, byte[]>();+ var reader = new Reader(data, start, explicitVr, bigEndian);+ while (reader.Position + 8 <= data.Length)+ {+ var element = reader.Next();+ if (element.Undefined)+ {+ if (element.Tag == PixelDataTag)+ return null; // encapsulated: compressed frames+ reader.SkipSequence();+ continue;+ }+ if (Wanted.Contains(element.Tag))+ values[element.Tag] = element.Value;+ if (element.Tag == PixelDataTag)+ break;+ }+ if (!values.TryGetValue(PixelDataTag, out var pixels))+ throw new InvalidDataException("The DICOM file has no image.");+ return Decode(values, pixels, bigEndian);+ }++ private static MagickImageCollection? Decode(Dictionary<uint, byte[]> values, byte[] pixels, bool bigEndian)+ {+ int Number(uint tag, int fallback) => values.TryGetValue(tag, out var v) && v.Length >= 2+ ? bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(v) : BinaryPrimitives.ReadUInt16LittleEndian(v) : fallback;+ double? Decimal(uint tag) => values.TryGetValue(tag, out var v) && double.TryParse(Text(v).Split('\\')[0],+ NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : null;++ var samples = Number(0x00280002, 1);+ var photometric = values.TryGetValue(0x00280004, out var p) ? Text(p) : "MONOCHROME2";+ var planar = Number(0x00280006, 0);+ var frames = (int)(Decimal(0x00280008) ?? 1);+ var rows = Number(0x00280010, 0);+ var columns = Number(0x00280011, 0);+ var allocated = Number(0x00280100, 8);+ var stored = Number(0x00280101, allocated);+ var highBit = Number(0x00280102, stored - 1);+ var signed = Number(0x00280103, 0) == 1;+ var slope = Decimal(0x00281053) ?? 1;+ var intercept = Decimal(0x00281052) ?? 0;+ var center = Decimal(0x00281050);+ var width = Decimal(0x00281051);++ var grey = samples == 1 && photometric is "MONOCHROME1" or "MONOCHROME2";+ var colour = samples == 3 && photometric is "RGB" or "YBR_FULL";+ if (!grey && !colour || allocated is not (8 or 16) || stored is < 1 or > 16 || stored > allocated || highBit >= allocated)+ return null;+ if (rows == 0 || columns == 0 || frames < 1)+ throw new InvalidDataException("The DICOM image has no size.");+ var pixelCount = rows * columns;+ var frameBytes = (long)pixelCount * samples * allocated / 8;+ if (pixels.Length < frameBytes * frames)+ throw new InvalidDataException("The DICOM file is damaged (its image data is incomplete).");++ var shift = highBit - stored + 1;+ var mask = (1 << stored) - 1;+ int Raw(int frame, int index)+ {+ var offset = frame * frameBytes + (long)index * allocated / 8;+ int value = allocated == 8 ? pixels[offset]+ : bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(pixels.AsSpan((int)offset))+ : BinaryPrimitives.ReadUInt16LittleEndian(pixels.AsSpan((int)offset));+ value = (value >> shift) & mask;+ return signed && (value & (1 << (stored - 1))) != 0 ? value - (1 << stored) : value;+ }++ // Grey: values → 0..255 through the window, or the range of values in the whole file without one.+ Func<double, double> toGrey;+ if (grey && width is >= 1 && center is { } c)+ {+ var w = width.Value;+ toGrey = x => x <= c - 0.5 - (w - 1) / 2 ? 0 : x > c - 0.5 + (w - 1) / 2 ? 255 : ((x - (c - 0.5)) / (w - 1) + 0.5) * 255;+ }+ else if (grey)+ {+ double min = double.MaxValue, max = double.MinValue;+ for (var f = 0; f < frames; f++)+ for (var i = 0; i < pixelCount; i++)+ {+ var x = Raw(f, i) * slope + intercept;+ min = Math.Min(min, x);+ max = Math.Max(max, x);+ }+ var range = max - min;+ toGrey = x => range <= 0 ? 0 : (x - min) / range * 255;+ }+ else+ {+ toGrey = x => x;+ }++ var collection = new MagickImageCollection();+ try+ {+ for (var f = 0; f < frames; f++)+ {+ var rgb = new byte[pixelCount * 3];+ for (var i = 0; i < pixelCount; i++)+ {+ if (grey)+ {+ var level = Math.Clamp(toGrey(Raw(f, i) * slope + intercept), 0, 255);+ var value = (byte)Math.Round(photometric == "MONOCHROME1" ? 255 - level : level);+ rgb[i * 3] = rgb[i * 3 + 1] = rgb[i * 3 + 2] = value;+ continue;+ }+ var (a, b, d) = planar == 1+ ? (Raw(f, i), Raw(f, pixelCount + i), Raw(f, 2 * pixelCount + i))+ : (Raw(f, i * 3), Raw(f, i * 3 + 1), Raw(f, i * 3 + 2));+ var down = Math.Max(0, stored - 8);+ (a, b, d) = (a >> down, b >> down, d >> down);+ if (photometric == "YBR_FULL")+ (a, b, d) = ((int)Math.Round(a + 1.402 * (d - 128)), (int)Math.Round(a - 0.344136 * (b - 128) - 0.714136 * (d - 128)),+ (int)Math.Round(a + 1.772 * (b - 128)));+ rgb[i * 3] = (byte)Math.Clamp(a, 0, 255);+ rgb[i * 3 + 1] = (byte)Math.Clamp(b, 0, 255);+ rgb[i * 3 + 2] = (byte)Math.Clamp(d, 0, 255);+ }+ var image = new MagickImage();+ image.ReadPixels(rgb, new PixelReadSettings((uint)columns, (uint)rows, StorageType.Char, PixelMapping.RGB));+ if (grey)+ image.ColorType = ColorType.Grayscale;+ collection.Add(image);+ }+ return collection;+ }+ catch+ {+ collection.Dispose();+ throw;+ }+ }++ private static string Text(byte[] value) => Encoding.ASCII.GetString(value).TrimEnd('\0', ' ');++ private readonly record struct Element(uint Tag, byte[] Value, bool Undefined);++ /// <summary>Reads data elements one after the other (PS3.5 chapter 7).</summary>+ private sealed class Reader(byte[] data, int position, bool explicitVr, bool bigEndian)+ {+ public int Position { get; private set; } = position;++ public ushort PeekGroup() => U16(Position);++ public Element Next()+ {+ if (Position + 8 > data.Length)+ throw Damaged();+ var tag = (uint)U16(Position) << 16 | U16(Position + 2);+ uint length;+ if (explicitVr && tag >> 16 != 0xFFFE)+ {+ var vr = Encoding.ASCII.GetString(data, Position + 4, 2);+ if (LongVrs.Contains(vr))+ {+ if (Position + 12 > data.Length)+ throw Damaged();+ length = U32(Position + 8);+ Position += 12;+ }+ else+ {+ length = U16(Position + 6);+ Position += 8;+ }+ }+ else+ {+ length = U32(Position + 4);+ Position += 8;+ }+ if (length == UndefinedLength)+ return new Element(tag, [], true);+ if (length > data.Length - Position)+ throw Damaged();+ var value = data.AsSpan(Position, (int)length).ToArray();+ Position += (int)length;+ return new Element(tag, value, false);+ }++ /// <summary>Skips a sequence of undefined length: items until the sequence delimitation item.</summary>+ public void SkipSequence()+ {+ while (true)+ {+ var item = Header();+ if (item.Tag == 0xFFFEE0DD)+ return;+ if (item.Tag != 0xFFFEE000)+ throw Damaged();+ if (item.Length != UndefinedLength)+ {+ Skip(item.Length);+ continue;+ }+ // An item of undefined length: elements until the item delimitation item.+ while (true)+ {+ if (U16(Position) == 0xFFFE && U16(Position + 2) == 0xE00D)+ {+ Header();+ break;+ }+ if (Next().Undefined)+ SkipSequence();+ }+ }+ }++ private (uint Tag, uint Length) Header()+ {+ if (Position + 8 > data.Length)+ throw Damaged();+ var header = ((uint)U16(Position) << 16 | U16(Position + 2), U32(Position + 4));+ Position += 8;+ return header;+ }++ private void Skip(uint length)+ {+ if (length > data.Length - Position)+ throw Damaged();+ Position += (int)length;+ }++ private ushort U16(int at) => at + 2 > data.Length ? throw Damaged()+ : bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(at)) : BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(at));++ private uint U32(int at) => at + 4 > data.Length ? throw Damaged()+ : bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(at)) : BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(at));++ private static InvalidDataException Damaged() => new("The DICOM file is damaged.");+ }+}diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.csindex 574820af..2ce16283 100644--- a/src/Filee.Engines/Magick/ImageEncoder.cs+++ b/src/Filee.Engines/Magick/ImageEncoder.cs@@ -11,13 +11,16 @@ internal static class ImageEncoder{/// <summary>/// Image formats ImageMagick can read (see <see cref="ImageReader"/> for RAW, layered and metafile sources).- /// Camera RAW is decoded by LibRaw, XCF and HEIC are read only. EMF/WMF are Windows metafiles, which ImageMagick- /// renders through GDI+ on Windows only (<see cref="Metafiles"/>).+ /// Camera RAW is decoded by LibRaw; XCF, HEIC, DICOM, Photo CD, OpenEXR and Radiance HDR are read only. EMF/WMF+ /// are Windows metafiles, which ImageMagick renders through GDI+ on Windows only (<see cref="Metafiles"/>). APNG is+ /// read and written by Filee's own <see cref="Apng"/> (its frames decoded and encoded by ImageMagick)./// </summary>public static readonly string[] Readable =["png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif", "heic","jxl", "jp2", "psd", "psb", "tga", "ppm", "xcf", "raw",+ "apng", "mng", "qoi", "dds", "pcx", "cur", "xpm", "xbm", "wbmp", "pam", "pfm", "sgi", "ras", "miff",+ "dcm", "pcd", "exr", "hdr",];/// <summary>Vector metafiles ImageMagick rasterizes (Windows only: it uses GDI+).</summary>@@ -31,24 +34,26 @@ internal static class ImageEncoder["png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif","jxl", "jp2", "psd", "psb", "tga", "ppm",+ "apng", "mng", "qoi", "dds", "pcx", "cur", "xpm", "xbm", "wbmp", "pam", "pfm", "sgi", "ras", "miff",];/// <summary>Formats that store several frames/pages in one file.</summary>- private static readonly HashSet<string> MultiFrame = ["tiff", "gif"];+ private static readonly HashSet<string> MultiFrame = ["tiff", "gif", "apng", "mng"];/// <summary>/// Formats whose frames are an animation. Between these, all frames are kept with their timing (an animated GIF/// becomes an animated WebP and the other way round); any other target gets the first frame./// </summary>- private static readonly HashSet<string> Animated = ["gif", "webp"];+ private static readonly HashSet<string> Animated = ["gif", "webp", "apng", "mng"];/// <summary>/// The edge an image engine offers from a picture in <paramref name="source"/> to <paramref name="target"/>. GIF/// holds 256 colours, so a still picture costs more there: it reaches video through a full-colour PNG instead- /// (FFmpeg), while animations and multi-page files still go through GIF and keep their frames.+ /// (FFmpeg), while animations and multi-page files still go through GIF and keep their frames. Still picture → APNG+ /// costs as much, so photos never reach video as a one-frame animation./// </summary>public static ConversionEdge Edge(string source, string target) =>- new(source, target, target == "gif" && !MultiFrame.Contains(source) && !Animated.Contains(source) ? 12 : 10);+ new(source, target, target is "gif" or "apng" && !MultiFrame.Contains(source) && !Animated.Contains(source) ? 12 : 10);/// <summary>True when frames of <paramref name="sourceFormat"/> are written as one animation in <paramref name="targetFormat"/>.</summary>public static bool KeepsAnimation(string sourceFormat, string targetFormat) =>@@ -56,9 +61,21 @@ internal static class ImageEncoder/// <summary>/// Formats written without an alpha channel: transparent pixels are flattened onto the background colour. HEIC- /// could carry alpha as an auxiliary picture; Filee's writer (Heic/HeicWriter) does not.+ /// could carry alpha as an auxiliary picture; Filee's writer (Heic/HeicWriter) does not. XBM and WBMP are 1-bit, PFM+ /// has no alpha, and the alpha planes of PCX and Sun Raster are an ImageMagick extension other programs ignore (its+ /// palette writers drop them altogether)./// </summary>- private static readonly HashSet<string> NoAlpha = ["jpg", "ppm", "heic"];+ private static readonly HashSet<string> NoAlpha = ["jpg", "ppm", "heic", "xbm", "wbmp", "pfm", "pcx", "ras"];++ /// <summary>+ /// Formats read with their ImageMagick coder named instead of guessed from the file: some extensions mean another+ /// format to ImageMagick (.rgb and .bw are headerless pixel data there, SGI here) and WBMP has no signature.+ /// </summary>+ public static readonly HashSet<string> ExplicitCoder =+ ["mng", "qoi", "dds", "pcx", "cur", "xpm", "xbm", "wbmp", "pam", "pfm", "sgi", "ras", "miff", "dcm", "pcd", "exr", "hdr"];++ /// <summary>Formats holding one picture in several sizes (icons) or mipmaps: the largest is converted.</summary>+ private static readonly HashSet<string> SizeVariants = ["ico", "cur", "dds"];/// <summary>Every format ImageMagick reads as input: the raster formats plus, on Windows, the metafiles.</summary>public static IEnumerable<string> Sources =>@@ -81,6 +98,25 @@ internal static class ImageEncoder"psb" => MagickFormat.Psb,"tga" => MagickFormat.Tga,"ppm" => MagickFormat.Ppm,+ "mng" => MagickFormat.Mng,+ "qoi" => MagickFormat.Qoi,+ "dds" => MagickFormat.Dds,+ "pcx" => MagickFormat.Pcx,+ "cur" => MagickFormat.Cur,+ "xpm" => MagickFormat.Xpm,+ "xbm" => MagickFormat.Xbm,+ "wbmp" => MagickFormat.Wbmp,+ "pam" => MagickFormat.Pam,+ "pfm" => MagickFormat.Pfm,+ "sgi" => MagickFormat.Sgi,+ "ras" => MagickFormat.Sun,+ "miff" => MagickFormat.Miff,+ "dcm" => MagickFormat.Dcm,+ "pcd" => MagickFormat.Pcd,+ "exr" => MagickFormat.Exr,+ "hdr" => MagickFormat.Hdr,+ // Every frame is a PNG; Apng assembles the animation (ImageMagick would need FFmpeg for it).+ "apng" => MagickFormat.Png,_ => throw new NotSupportedException($"ImageMagick cannot handle '{formatId}'."),};@@ -105,7 +141,8 @@ internal static class ImageEncoder/// <summary>/// Chooses which frames of a (possibly multi-frame) source are converted.- /// ICO: the largest icon. Animated GIF/WebP: every frame for a GIF/WebP/TIFF target, else the first frame.+ /// ICO, CUR, DDS: the largest image. Animations (GIF, WebP, APNG, MNG): every frame for an animated or TIFF+ /// target, else the first frame./// PSD/PSB: the composite (frame 0; any further frames are layers). Otherwise: all frames/pages./// </summary>public static List<IMagickImage<byte>> SelectFrames(MagickImageCollection images, string sourceFormat, string targetFormat)@@ -118,7 +155,7 @@ internal static class ImageEncoderreturn frames;if (sourceFormat is "psd" or "psb")return [frames[0]];- if (sourceFormat == "ico")+ if (SizeVariants.Contains(sourceFormat))return [frames.OrderByDescending(f => (long)f.Width * f.Height).First()];if (Animated.Contains(sourceFormat) && !MultiFrame.Contains(targetFormat) && !KeepsAnimation(sourceFormat, targetFormat))return [frames[0]];@@ -232,6 +269,11 @@ internal static class ImageEncodercase "ico":PrepareIcon(image, options);break;+ case "cur":+ // A cursor stores at most 256 × 256 pixels.+ if (image.Width > 256 || image.Height > 256)+ image.Resize(new MagickGeometry(256, 256));+ break;case "psd":case "psb":// ImageMagick writes a broken layer section for palette images with transparency (as read from@@ -254,6 +296,17 @@ internal static class ImageEncodervar written = new List<string>();var (format, extension) = OutputFormat(targetFormat, options ?? new ImageOptions(), sourcePath);+ if (targetFormat == "apng")+ {+ // One file, also for a single frame (a one-frame animation).+ var animationPath = output.Allocate(extension);+ if (animationPath is null)+ return written;+ Apng.Write(frames, animationPath);+ written.Add(animationPath);+ return written;+ }+if (frames.Count > 1 && (MultiFrame.Contains(targetFormat) || animation)){var path = output.Allocate(extension);@@ -278,6 +331,15 @@ internal static class ImageEncoderreturn written;}+ /// <summary>Writes one image as <paramref name="targetFormat"/> (APNG through <see cref="Apng"/>).</summary>+ public static void WriteImage(IMagickImage<byte> image, string path, string targetFormat)+ {+ if (targetFormat == "apng")+ Apng.Write([image], path);+ else+ image.Write(path, ToMagickFormat(targetFormat));+ }+private static void PrepareIcon(IMagickImage<byte> image, ImageOptions options){// Icons must be square: pad the shorter side with transparency, then let ImageMagickdiff --git a/src/Filee.Engines/Magick/ImageReader.cs b/src/Filee.Engines/Magick/ImageReader.csindex 681c17dc..7dc798b3 100644--- a/src/Filee.Engines/Magick/ImageReader.cs+++ b/src/Filee.Engines/Magick/ImageReader.cs@@ -1,6 +1,8 @@// Reads source images with ImageMagick, handling the formats that need more than "open the file": camera RAW// (LibRaw settings), layered PSD/PSB/XCF (one flattened picture instead of one file per layer) and Windows-// metafiles (rendered at the preset's DPI). Used by every engine that takes a raster image as input.+// metafiles (rendered at the preset's DPI), APNG (Filee's own reader composes the frames) and uncompressed DICOM+// (Filee's own reader, as ImageMagick's Q8 build reads only 8-bit DICOM). Used by every engine that takes a raster+// image as input.using System.Buffers.Binary;using Filee.Core.Presets;@@ -21,12 +23,24 @@ internal static class ImageReader/// </summary>public static MagickImageCollection Read(string path, string formatId, Preset preset){+ if (formatId == "apng")+ return Apng.Read(path);+ if (formatId == "dcm" && Dicom.TryRead(path) is { } scan)+ return scan;+var images = new MagickImageCollection();var settings = Settings(formatId, preset);try{images.Read(path, settings);}+ catch (MagickException ex) when (formatId == "dcm")+ {+ images.Dispose();+ throw new InvalidOperationException(+ "This DICOM image is compressed in a way Filee can't read (more than 8 bits per sample, or an unusual " ++ "compression). Export it uncompressed from the viewing software and try again. (" + ex.Message + ")", ex);+ }catch (MagickException ex) when (formatId == "xcf"){images.Dispose();@@ -48,6 +62,18 @@ internal static class ImageReaderimage.Density = density;}+ // A MIFF palette image keeps its transparency per pixel while its palette says opaque, so writers that store a+ // palette (PNG) would lose it: make it direct colour with the pixels' own alpha.+ if (formatId == "miff")+ {+ foreach (var image in images.Where(i => i.ClassType == ClassType.Pseudo && i.HasAlpha))+ {+ var rgba = image.GetPixels().ToByteArray(PixelMapping.RGBA)!;+ image.ClassType = ClassType.Direct;+ image.ImportPixels(rgba, new PixelImportSettings(image.Width, image.Height, StorageType.Char, PixelMapping.RGBA));+ }+ }+if (formatId == "xcf" && images.Count > 0){var flat = FlattenXcf(images, XcfCanvasSize(path));@@ -61,6 +87,8 @@ internal static class ImageReaderinternal static MagickReadSettings Settings(string formatId, Preset preset){var settings = new MagickReadSettings();+ if (ImageEncoder.ExplicitCoder.Contains(formatId))+ settings.Format = ImageEncoder.ToMagickFormat(formatId);switch (formatId){case "raw":diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.csindex 62714785..b15b607e 100644--- a/src/Filee.Engines/Magick/MagickImageConverter.cs+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs@@ -7,8 +7,9 @@ using ImageMagick;namespace Filee.Engines.Magick;/// <summary>-/// Converts between PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA and PPM, and reads-/// HEIC, XCF, camera RAW and (on Windows) EMF/WMF.+/// Converts between PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, APNG, MNG, QOI,+/// DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster and MIFF, and reads HEIC, XCF, camera RAW, DICOM,+/// Photo CD, OpenEXR, Radiance HDR and (on Windows) EMF/WMF./// </summary>public sealed class MagickImageConverter : IConverter, ITiffMerger{@@ -66,11 +67,13 @@ public sealed class MagickImageConverter : IConverter, ITiffMergerpublic Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>Task.Run<IReadOnlyList<string>>(() =>{- using var images = ImageReader.Read(step.InputPath, step.From, step.Preset);+ // Animated PNGs are often saved as .png: read them as APNG, so they stay animated as GIF or WebP.+ var from = step.From == "png" && Apng.IsAnimated(step.InputPath) ? "apng" : step.From;+ using var images = ImageReader.Read(step.InputPath, from, step.Preset);cancellationToken.ThrowIfCancellationRequested();progress?.Report(0.3);- var frames = ImageEncoder.SelectFrames(images, step.From, step.To);+ var frames = ImageEncoder.SelectFrames(images, from, step.To);foreach (var frame in frames){cancellationToken.ThrowIfCancellationRequested();@@ -79,7 +82,7 @@ public sealed class MagickImageConverter : IConverter, ITiffMergerprogress?.Report(0.7);var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath,- ImageEncoder.KeepsAnimation(step.From, step.To));+ ImageEncoder.KeepsAnimation(from, step.To));progress?.Report(1);return written;}, cancellationToken);diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.csindex e095bc51..a50854d5 100644--- a/src/Filee.Engines/Media/FfmpegConverter.cs+++ b/src/Filee.Engines/Media/FfmpegConverter.cs@@ -1,6 +1,6 @@// Video and audio conversion with FFmpeg (GPL-3.0 build, an optional download run as a separate program in-// engines/ffmpeg): video ↔ video, video → animated GIF or a still frame, audio extraction, audio ↔ audio and-// GIF or a still picture → video, and images → HEIC (FFmpeg's HEVC encoder, Filee's own container writer).+// engines/ffmpeg): video ↔ video, video → animated GIF / APNG or a still frame, audio extraction, audio ↔ audio and+// GIF, APNG or a still picture → video, and images → HEIC (FFmpeg's HEVC encoder, Filee's own container writer).// Container and codec choices live in MediaEncoding, the process handling in FfmpegRunner.using System.Collections.Concurrent;@@ -30,17 +30,18 @@ public sealed partial class FfmpegConverter : IConverterpublic IReadOnlyList<ConversionEdge> Edges { get; } = BuildEdges();/// <summary>- /// Every video format (read by FFmpeg's demuxers) → every video target, animated GIF, a still PNG frame and every- /// audio target; every audio format → every audio target (including itself: re-encode with another bitrate);- /// GIF and PNG → MP4, WEBM, MOV; every image ImageMagick reads → HEIC. Only formats the pinned build can write- /// are targets (see MediaEncoding).+ /// Every video format (read by FFmpeg's demuxers) → every video target, animated GIF or APNG, a still PNG frame and+ /// every audio target; every audio format → every audio target (including itself: re-encode with another bitrate);+ /// GIF, APNG and PNG → MP4, WEBM, MOV; every image ImageMagick reads → HEIC. Only formats the pinned build can+ /// write are targets (see MediaEncoding)./// </summary>/// <remarks>- /// The GIF edge costs more (slow, 256 colours), so video → JPG / PDF / TIFF … goes through the still frame- /// (video → PNG → image engines) and never renders an animated GIF of a whole film just to take one frame of it.- /// The other way, a photo (HEIC, JPG, …) reaches video as a full-colour PNG: the image engines' still → GIF edges- /// cost 12 (<see cref="Magick.ImageEncoder.Edge"/>), so 10 + 11 beats 12 + 10. Animated GIF/WebP and PDF or TIFF- /// pages keep the GIF route (10 + 10), which keeps their frames.+ /// The GIF and APNG edges cost more (slow, large), so video → JPG / PDF / TIFF … goes through the still frame+ /// (video → PNG → image engines) and never renders an animation of a whole film just to take one frame of it.+ /// The other way, a photo (HEIC, JPG, …) reaches video as a full-colour PNG: the image engines' still → GIF and+ /// still → APNG edges cost 12 (<see cref="Magick.ImageEncoder.Edge"/>), so 10 + 11 beats 12 + 10 and 12 + 11.+ /// Animated GIF/WebP and PDF or TIFF pages keep the GIF route (10 + 10, APNG costs 10 + 11), which keeps their+ /// frames; an APNG goes straight to video./// </remarks>private static List<ConversionEdge> BuildEdges(){@@ -51,8 +52,10 @@ public sealed partial class FfmpegConverter : IConverter[.. from source in videos from target in videoTargets select new ConversionEdge(source, target),.. videos.Select(source => new ConversionEdge(source, "gif", 15)),+ .. videos.Select(source => new ConversionEdge(source, "apng", 15)),.. from source in audios from target in MediaEncoding.AudioTargets.Keys select new ConversionEdge(source, target),.. MediaEncoding.PictureToVideoTargets.Select(target => new ConversionEdge("gif", target)),+ .. MediaEncoding.PictureToVideoTargets.Select(target => new ConversionEdge("apng", target, 11)),.. MediaEncoding.PictureToVideoTargets.Select(target => new ConversionEdge("png", target, 11)),// HEIC: ImageMagick reads, x265 encodes, Filee writes the container (see Heic/HeicWriter)... ImageEncoder.Sources.Select(source => new ConversionEdge(source, "heic")),diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.csindex 96260289..a1061f9a 100644--- a/src/Filee.Engines/Media/MediaEncoding.cs+++ b/src/Filee.Engines/Media/MediaEncoding.cs@@ -123,6 +123,8 @@ internal static class MediaEncoding{if (target == "gif")return AnimatedGif(input, output, options, info, workDirectory);+ if (target == "apng")+ return [new FfmpegPass(AnimatedPng(input, output, options, info), 1)];if (target == "png")return [new FfmpegPass(PosterFrame(input, output, info), 1)];if (VideoTargets.TryGetValue(target, out var video))@@ -515,6 +517,22 @@ internal static class MediaEncodingreturn [new FfmpegPass(first, 0.4), new FfmpegPass(second, 0.6)];}+ /// <summary>+ /// Animated PNG with FFmpeg's APNG encoder and muxer: full colour (24-bit RGB, no palette pass), looping, with the+ /// frame rate and width limits of GIF, since every frame is stored losslessly.+ /// </summary>+ private static List<string> AnimatedPng(string input, string output, MediaOptions options, MediaInfo info)+ {+ var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");+ var quality = options.Quality;+ var chain = GifFrames(video, options.MaxHeight, fps: Choose(quality, 15, 12, 10), maxWidth: Choose(quality, 640, 480, 320));+ return+ [+ .. Common, "-i", input, "-map", "0:V:0", "-vf", chain, "-an",+ "-c:v", "apng", "-pix_fmt", "rgb24", "-pred", "mixed", "-plays", "0", "-f", "apng", "-progress", "pipe:1", output,+ ];+ }+/// <summary>Frame rate, square pixels and size of the GIF frames (never upscaled).</summary>private static string GifFrames(VideoStreamInfo video, int maxHeight, int fps, int maxWidth){diff --git a/src/Filee.Engines/Pdf/PdfiumConverter.cs b/src/Filee.Engines/Pdf/PdfiumConverter.csindex bca97069..a83d5653 100644--- a/src/Filee.Engines/Pdf/PdfiumConverter.cs+++ b/src/Filee.Engines/Pdf/PdfiumConverter.cs@@ -18,7 +18,7 @@ namespace Filee.Engines.Pdf;/// <summary>PDF → every raster format ImageMagick writes (PNG, JPG, WEBP, TIFF, …, PSD, TGA, PPM).</summary>public sealed class PdfiumConverter : IConverter{- private static readonly HashSet<string> MultiPageTargets = ["tiff", "gif"];+ private static readonly HashSet<string> MultiPageTargets = ["tiff", "gif", "apng", "mng"];/// <summary>A tall image beyond this many pixels is scaled down (a 300-page PDF at 300 dpi would need gigabytes).</summary>internal const long MaxStackedPixels = 200_000_000;diff --git a/tests/Filee.Core.Tests/SmallParsersTests.cs b/tests/Filee.Core.Tests/SmallParsersTests.csindex 4f1dfcca..ef2c9003 100644--- a/tests/Filee.Core.Tests/SmallParsersTests.cs+++ b/tests/Filee.Core.Tests/SmallParsersTests.cs@@ -27,6 +27,10 @@ public class FormatRegistryTests[InlineData("b.tif", "tiff")][InlineData("c.HWPX", "hwpx")][InlineData(".md", "md")]+ [InlineData("DSCF0001.HIF", "heic")] // Fujifilm's HEIF+ [InlineData("anim.apng", "apng")]+ [InlineData("scan.dicom", "dcm")]+ [InlineData("texture.rgb", "sgi")]public void Detects_formats(string path, string id) => Assert.Equal(id, FormatRegistry.Detect(path)?.Id);[Fact]diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex cf18bdab..64e50faf 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -210,6 +210,26 @@ public class UserDataStoreTestsAssert.False(SettingsMigrations.ApplyToLibrary(9, presets, profiles)); // once only}+ [Fact]+ public void Version_10_libraries_open_the_new_image_formats_on_the_images_donut()+ {+ // As written by 1.11.x: the images donut knows no APNG, QOI, DICOM or .hif; a donut of the user takes DDS.+ var presets = BuiltInData.CreatePresets();+ var profiles = BuiltInData.CreateProfiles();+ var images = profiles.Single(p => p.Id == "images");+ images.Extensions.RemoveAll(e => e is "apng" or "qoi" or "dcm" or "hif" or "dds");+ profiles.Insert(0, new ToolbarProfile { Id = "game", Name = "Game textures", Extensions = ["dds"] });++ Assert.True(SettingsMigrations.ApplyToLibrary(10, presets, profiles));++ Assert.Contains("apng", images.Extensions);+ Assert.Contains("qoi", images.Extensions);+ Assert.Contains("dcm", images.Extensions);+ Assert.Contains("hif", images.Extensions);+ Assert.DoesNotContain("dds", images.Extensions);+ Assert.False(SettingsMigrations.ApplyToLibrary(10, presets, profiles)); // once only+ }+[Fact]public void Catalog_migration_ignores_extensions_checked_on_mixed_profiles(){diff --git a/tests/Filee.Engines.Tests/ApngTests.cs b/tests/Filee.Engines.Tests/ApngTests.csnew file mode 100644index 00000000..cca8fad1--- /dev/null+++ b/tests/Filee.Engines.Tests/ApngTests.cs@@ -0,0 +1,286 @@+// APNG: Filee's own reader and writer (Magick/Apng.cs). Animations are generated in the tests: GIFs with ImageMagick,+// and APNGs chunk by chunk (ApngBuilder) to cover the dispose and blend operations of the specification.++using System.Buffers.Binary;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Archives;+using Filee.Engines.Magick;+using ImageMagick;++namespace Filee.Engines.Tests;++public class ApngTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static void AssertDone(ConversionJob job)+ {+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");+ }++ /// <summary>A 3-frame animated GIF (red, green, blue; 20, 30 and 40 hundredths of a second, looping).</summary>+ private static string MakeAnimatedGif(string folder)+ {+ using var frames = new MagickImageCollection();+ foreach (var (color, delay) in new[] { (MagickColors.Red, 20u), (MagickColors.Lime, 30u), (MagickColors.Blue, 40u) })+ frames.Add(new MagickImage(color, 64, 48) { AnimationDelay = delay });+ var path = Path.Combine(folder, "anim.gif");+ frames.Write(path, MagickFormat.Gif);+ return path;+ }++ private static IMagickColor<byte> Pixel(IMagickImage<byte> image, int x, int y) => image.GetPixels().GetPixel(x, y).ToColor()!;++ [Fact]+ public async Task Animated_gif_becomes_an_apng_and_back()+ {+ var dir = fx.NewFolder();+ var toApng = await fx.ConvertAsync([MakeAnimatedGif(dir)], new Preset { TargetFormat = "apng" });++ AssertDone(toApng);+ var apng = toApng.Outputs.Single();+ Assert.Equal(".apng", Path.GetExtension(apng));+ var chunks = ApngBuilder.Chunks(File.ReadAllBytes(apng));+ Assert.Equal(["IHDR", "acTL"], chunks.Select(c => c.Type).Where(t => t is "IHDR" or "acTL"));+ Assert.Equal(3u, BinaryPrimitives.ReadUInt32BigEndian(chunks.Single(c => c.Type == "acTL").Data));+ Assert.Equal(3, chunks.Count(c => c.Type == "fcTL"));+ Assert.True(chunks.FindIndex(c => c.Type == "fcTL") < chunks.FindIndex(c => c.Type == "IDAT"), "the default image is the first frame");+ // A viewer without APNG support shows the first frame.+ using (var still = new MagickImage(apng, new MagickReadSettings { Format = MagickFormat.Png }))+ Assert.True(Pixel(still, 32, 24).R > 200, "first frame is red");++ var back = await fx.ConvertAsync([apng], new Preset { TargetFormat = "gif", Output = { FileNamePattern = "{name}_back" } });++ AssertDone(back);+ using var gif = new MagickImageCollection(back.Outputs.Single());+ Assert.Equal(3, gif.Count);+ Assert.Equal([20u, 30u, 40u], gif.Select(f => f.AnimationDelay));+ Assert.True(Pixel(gif[1], 32, 24).G > 200, "second frame is green");+ Assert.True(Pixel(gif[2], 32, 24).B > 200, "third frame is blue");+ }++ [Fact]+ public async Task Apng_becomes_an_animated_webp_and_a_still_picture()+ {+ var dir = fx.NewFolder();+ var apng = (await fx.ConvertAsync([MakeAnimatedGif(dir)], new Preset { TargetFormat = "apng" })).Outputs.Single();++ var webp = await fx.ConvertAsync([apng], new Preset { TargetFormat = "webp", Image = { WebpLossless = true } });+ var jpg = await fx.ConvertAsync([apng], new Preset { TargetFormat = "jpg" });++ AssertDone(webp);+ using (var frames = new MagickImageCollection(webp.Outputs.Single()))+ {+ Assert.Equal(3, frames.Count);+ Assert.Equal([20u, 30u, 40u], frames.Select(f => f.AnimationDelay));+ }+ AssertDone(jpg);+ using var first = new MagickImage(jpg.Outputs.Single());+ Assert.True(Pixel(first, 32, 24).R > 200, "a still format takes the first frame");+ }++ [Fact]+ public async Task An_animated_png_saved_as_png_stays_animated()+ {+ var dir = fx.NewFolder();+ var apng = (await fx.ConvertAsync([MakeAnimatedGif(dir)], new Preset { TargetFormat = "apng" })).Outputs.Single();+ var png = Path.Combine(dir, "sticker.png");+ File.Copy(apng, png);++ var job = await fx.ConvertAsync([png], new Preset { TargetFormat = "gif" });++ AssertDone(job);+ using var gif = new MagickImageCollection(job.Outputs.Single());+ Assert.Equal(3, gif.Count);+ }++ [Fact]+ public void Frames_are_composed_with_their_dispose_and_blend_operations()+ {+ var dir = fx.NewFolder();+ using var red = new MagickImage(MagickColors.Red, 40, 40);+ using var clear = new MagickImage(MagickColors.Transparent, 10, 10);+ using var blue = new MagickImage(new MagickColor(0, 0, 255, 128), 10, 10);+ using var green = new MagickImage(MagickColors.Lime, 1, 1);+ using var yellow = new MagickImage(MagickColors.Yellow, 40, 40);+ var path = Path.Combine(dir, "ops.apng");+ File.WriteAllBytes(path, ApngBuilder.Build(40, 40, plays: 2, hiddenDefault: yellow,+ [+ new(red, 0, 0, 5, 0, ApngBuilder.DisposeNone, ApngBuilder.BlendSource), // 5/100 s (denominator 0)+ new(clear, 0, 0, 1, 10, ApngBuilder.DisposeBackground, ApngBuilder.BlendSource), // punches a hole+ new(blue, 30, 30, 1, 10, ApngBuilder.DisposePrevious, ApngBuilder.BlendOver), // shown once, then undone+ new(green, 20, 20, 1, 1, ApngBuilder.DisposeNone, ApngBuilder.BlendOver),+ ]));++ using var frames = Apng.Read(path);++ Assert.Equal(4, frames.Count); // the hidden default image (yellow) is not a frame+ Assert.Equal([5u, 10u, 10u, 100u], frames.Select(f => f.AnimationDelay));+ Assert.All(frames, f => Assert.Equal(2u, f.AnimationIterations));+ Assert.Equal(255, Pixel(frames[0], 5, 5).R);+ Assert.Equal(0, Pixel(frames[1], 5, 5).A); // SOURCE replaces, transparency included+ Assert.Equal(255, Pixel(frames[1], 35, 35).R);+ var mixed = Pixel(frames[2], 35, 35); // OVER: half blue over red+ Assert.InRange(mixed.R, 100, 160);+ Assert.InRange(mixed.B, 100, 160);+ Assert.Equal(0, Pixel(frames[2], 5, 5).A); // BACKGROUND cleared the hole's region+ Assert.Equal(255, Pixel(frames[3], 35, 35).R); // PREVIOUS restored the red+ Assert.Equal(0, Pixel(frames[3], 35, 35).B);+ Assert.Equal(255, Pixel(frames[3], 20, 20).G);+ Assert.Equal(0, Pixel(frames[3], 5, 5).A);+ }++ [Fact]+ public void Unchanged_frames_are_merged_and_changed_ones_store_only_what_changed()+ {+ var dir = fx.NewFolder();+ using var first = new MagickImage(MagickColors.Red, 64, 48) { AnimationDelay = 10 };+ using var same = new MagickImage(MagickColors.Red, 64, 48) { AnimationDelay = 15 };+ using var dot = new MagickImage(MagickColors.Red, 64, 48) { AnimationDelay = 20 };+ using (var pixels = dot.GetPixels())+ pixels.SetArea(10, 20, 4, 3, Enumerable.Repeat(new byte[] { 0, 0, 255 }, 12).SelectMany(p => p).ToArray());+ var path = Path.Combine(dir, "merged.apng");++ Apng.Write([first, same, dot], path);++ var controls = ApngBuilder.Chunks(File.ReadAllBytes(path)).Where(c => c.Type == "fcTL").Select(c => c.Data).ToList();+ Assert.Equal(2, controls.Count);+ Assert.Equal(25, BinaryPrimitives.ReadUInt16BigEndian(controls[0].AsSpan(20))); // 10 + 15+ Assert.Equal((4u, 3u, 10u, 20u), (BinaryPrimitives.ReadUInt32BigEndian(controls[1].AsSpan(4)),+ BinaryPrimitives.ReadUInt32BigEndian(controls[1].AsSpan(8)), BinaryPrimitives.ReadUInt32BigEndian(controls[1].AsSpan(12)),+ BinaryPrimitives.ReadUInt32BigEndian(controls[1].AsSpan(16))));++ using var frames = Apng.Read(path);+ Assert.Equal(2, frames.Count);+ Assert.Equal(0d, frames[1].Compare(dot, ErrorMetric.Absolute));+ }++ [Fact]+ public void Frames_of_different_sizes_share_one_canvas()+ {+ var dir = fx.NewFolder();+ using var big = new MagickImage(MagickColors.Red, 80, 60);+ using var small = new MagickImage(MagickColors.Blue, 40, 30);+ var path = Path.Combine(dir, "sizes.apng");++ Apng.Write([big, small], path);++ using var frames = Apng.Read(path);+ Assert.All(frames, f => Assert.Equal((80u, 60u), (f.Width, f.Height)));+ Assert.True(Pixel(frames[1], 10, 10).B > 200);+ Assert.Equal(0, Pixel(frames[1], 70, 50).A);+ }++ [Fact]+ public void Damaged_files_fail_with_a_clear_message()+ {+ var dir = fx.NewFolder();+ using var red = new MagickImage(MagickColors.Red, 10, 10);+ var path = Path.Combine(dir, "bad.apng");+ File.WriteAllBytes(path, ApngBuilder.Build(10, 10, plays: 0, hiddenDefault: null,+ [new(red, 5, 5, 1, 10, ApngBuilder.DisposeNone, ApngBuilder.BlendSource)])); // outside the 10 × 10 canvas++ var error = Assert.Throws<InvalidDataException>(() => Apng.Read(path));+ Assert.Contains("outside", error.Message);+ Assert.False(Apng.IsAnimated(Path.Combine(dir, "missing.png")));+ }+}++/// <summary>Writes APNG files chunk by chunk, independent of Filee's writer.</summary>+internal static class ApngBuilder+{+ public const byte DisposeNone = 0, DisposeBackground = 1, DisposePrevious = 2;+ public const byte BlendSource = 0, BlendOver = 1;++ public sealed record Frame(IMagickImage<byte> Image, uint X, uint Y, ushort DelayNumerator, ushort DelayDenominator, byte Dispose, byte Blend);++ public sealed record Chunk(string Type, byte[] Data);++ private static readonly byte[] Signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];++ /// <param name="hiddenDefault">A default image (IDAT) before the first frame, not part of the animation.</param>+ public static byte[] Build(uint width, uint height, uint plays, IMagickImage<byte>? hiddenDefault, IReadOnlyList<Frame> frames)+ {+ using var output = new MemoryStream();+ output.Write(Signature);+ var header = new byte[13];+ BinaryPrimitives.WriteUInt32BigEndian(header, width);+ BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(4), height);+ header[8] = 8; // bit depth+ header[9] = 6; // RGBA+ Write(output, "IHDR", header);+ var control = new byte[8];+ BinaryPrimitives.WriteUInt32BigEndian(control, (uint)frames.Count);+ BinaryPrimitives.WriteUInt32BigEndian(control.AsSpan(4), plays);+ Write(output, "acTL", control);+ if (hiddenDefault is not null)+ Write(output, "IDAT", ImageData(hiddenDefault));++ var sequence = 0u;+ for (var i = 0; i < frames.Count; i++)+ {+ var frame = frames[i];+ var fctl = new byte[26];+ BinaryPrimitives.WriteUInt32BigEndian(fctl, sequence++);+ BinaryPrimitives.WriteUInt32BigEndian(fctl.AsSpan(4), frame.Image.Width);+ BinaryPrimitives.WriteUInt32BigEndian(fctl.AsSpan(8), frame.Image.Height);+ BinaryPrimitives.WriteUInt32BigEndian(fctl.AsSpan(12), frame.X);+ BinaryPrimitives.WriteUInt32BigEndian(fctl.AsSpan(16), frame.Y);+ BinaryPrimitives.WriteUInt16BigEndian(fctl.AsSpan(20), frame.DelayNumerator);+ BinaryPrimitives.WriteUInt16BigEndian(fctl.AsSpan(22), frame.DelayDenominator);+ fctl[24] = frame.Dispose;+ fctl[25] = frame.Blend;+ Write(output, "fcTL", fctl);+ var data = ImageData(frame.Image);+ if (i == 0 && hiddenDefault is null)+ {+ Write(output, "IDAT", data);+ continue;+ }+ var fdat = new byte[data.Length + 4];+ BinaryPrimitives.WriteUInt32BigEndian(fdat, sequence++);+ data.CopyTo(fdat.AsSpan(4));+ Write(output, "fdAT", fdat);+ }+ Write(output, "IEND", []);+ return output.ToArray();+ }++ public static List<Chunk> Chunks(byte[] png)+ {+ Assert.True(png.AsSpan(0, 8).SequenceEqual(Signature));+ var chunks = new List<Chunk>();+ for (var position = 8; position + 12 <= png.Length;)+ {+ var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(position));+ var type = Encoding.ASCII.GetString(png, position + 4, 4);+ var data = png.AsSpan(position + 8, length).ToArray();+ var crc = new Crc32();+ crc.Append(png.AsSpan(position + 4, 4 + length));+ Assert.Equal(crc.Value, BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(position + 8 + length)));+ chunks.Add(new Chunk(type, data));+ position += 12 + length;+ }+ return chunks;+ }++ /// <summary>The zlib stream of an 8-bit RGBA PNG of <paramref name="image"/>.</summary>+ private static byte[] ImageData(IMagickImage<byte> image) =>+ Chunks(image.ToByteArray(MagickFormat.Png32)).Where(c => c.Type == "IDAT").SelectMany(c => c.Data).ToArray();++ private static void Write(Stream stream, string type, byte[] data)+ {+ var buffer = new byte[4];+ BinaryPrimitives.WriteUInt32BigEndian(buffer, (uint)data.Length);+ stream.Write(buffer);+ var typeBytes = Encoding.ASCII.GetBytes(type);+ stream.Write(typeBytes);+ stream.Write(data);+ var crc = new Crc32();+ crc.Append(typeBytes);+ crc.Append(data);+ BinaryPrimitives.WriteUInt32BigEndian(buffer, crc.Value);+ stream.Write(buffer);+ }+}diff --git a/tests/Filee.Engines.Tests/DicomTests.cs b/tests/Filee.Engines.Tests/DicomTests.csnew file mode 100644index 00000000..48156680--- /dev/null+++ b/tests/Filee.Engines.Tests/DicomTests.cs@@ -0,0 +1,322 @@+// DICOM: Filee's reader of uncompressed images (Magick/Dicom.cs) and ImageMagick for 8-bit ones. The files are built+// element by element in the tests (DicomBuilder), as scanners write them.++using System.Buffers.Binary;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Magick;+using ImageMagick;++namespace Filee.Engines.Tests;++public class DicomTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static byte Grey(IMagickImage<byte> image, int x, int y) => image.GetPixels().GetPixel(x, y).ToColor()!.R;++ private string Save(byte[] dicom, string name = "scan.dcm")+ {+ var path = Path.Combine(fx.NewFolder(), name);+ File.WriteAllBytes(path, dicom);+ return path;+ }++ [Fact]+ public async Task A_12_bit_scan_converts_to_png_with_its_full_range()+ {+ // 12 bits in 16-bit words, as CT, MR and X-ray scanners store them; ImageMagick's Q8 build can't read these.+ var source = Save(new DicomBuilder { Ramp = (0, 4095) }.Build());++ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "png" });++ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));+ using var png = new MagickImage(job.Outputs.Single());+ Assert.Equal((64u, 32u), (png.Width, png.Height));+ Assert.Equal(0, Grey(png, 0, 5));+ Assert.Equal(255, Grey(png, 63, 5));+ Assert.InRange(Grey(png, 32, 5), 120, 136);+ }++ [Fact]+ public void Rescale_and_window_apply_like_a_viewer()+ {+ // CT: signed values, Hounsfield units = stored − 1024; a soft-tissue window (centre 40, width 400).+ using var frames = Dicom.TryRead(Save(new DicomBuilder+ {+ Signed = true,+ Ramp = (-200, 1000),+ Intercept = -1024,+ Window = (40, 400),+ }.Build()))!;++ var image = Assert.Single(frames);+ // −1224 HU on the left is below the window (black), −24 HU on the right is inside it:+ // ((−24 − (40 − 0.5)) / 399 + 0.5) × 255 ≈ 87.+ Assert.Equal(0, Grey(image, 0, 0));+ Assert.InRange(Grey(image, 63, 0), 85, 89);+ }++ [Fact]+ public void Monochrome1_is_inverted_and_frames_are_kept()+ {+ using var frames = Dicom.TryRead(Save(new DicomBuilder+ {+ Photometric = "MONOCHROME1",+ Frames = 3,+ Ramp = (0, 255),+ BitsAllocated = 8,+ BitsStored = 8,+ }.Build()))!;++ Assert.Equal(3, frames.Count);+ Assert.All(frames, f => Assert.Equal(255, Grey(f, 0, 0))); // 0 is white in MONOCHROME1+ Assert.All(frames, f => Assert.Equal(0, Grey(f, 63, 0)));+ }++ [Fact]+ public void Implicit_vr_files_without_a_preamble_and_big_endian_files_are_read()+ {+ using (var implicitVr = Dicom.TryRead(Save(new DicomBuilder { ImplicitVr = true, Preamble = false, Ramp = (0, 1000) }.Build()))!)+ Assert.Equal(255, Grey(implicitVr.Single(), 63, 0));+ using (var bigEndian = Dicom.TryRead(Save(new DicomBuilder { BigEndian = true, Ramp = (0, 1000) }.Build()))!)+ Assert.Equal(255, Grey(bigEndian.Single(), 63, 0));+ using (var deflated = Dicom.TryRead(Save(new DicomBuilder { Deflated = true, Ramp = (0, 1000) }.Build()))!)+ Assert.Equal(255, Grey(deflated.Single(), 63, 0));+ }++ [Fact]+ public void Ybr_full_becomes_rgb()+ {+ // Y 128, Cb 128, Cr 200: a reddish grey. R = Y + 1.402 (Cr − 128) ≈ 229, G ≈ 77, B = 128.+ using var frames = Dicom.TryRead(Save(new DicomBuilder { Rgb = true, Ybr = (128, 128, 200), BitsAllocated = 8, BitsStored = 8 }.Build()))!;+ var pixel = frames.Single().GetPixels().GetPixel(3, 3).ToColor()!;+ Assert.Equal((229, 77, 128), (pixel.R, pixel.G, pixel.B));+ }++ [Fact]+ public void Sequences_of_undefined_length_are_skipped()+ {+ using var frames = Dicom.TryRead(Save(new DicomBuilder { NestedSequence = true, Ramp = (0, 4095) }.Build()))!;+ Assert.Equal(255, Grey(frames.Single(), 63, 0));+ }++ [Fact]+ public void Rgb_planes_are_interleaved()+ {+ using var frames = Dicom.TryRead(Save(new DicomBuilder { Rgb = true, BitsAllocated = 8, BitsStored = 8 }.Build()))!;+ var pixel = frames.Single().GetPixels().GetPixel(10, 10).ToColor()!;+ Assert.Equal((200, 100, 50), (pixel.R, pixel.G, pixel.B));+ }++ [Fact]+ public void Compressed_pixel_data_is_left_to_imagemagick()+ {+ var path = Save(new DicomBuilder { TransferSyntax = "1.2.840.10008.1.2.4.70" }.Build()); // JPEG lossless+ Assert.Null(Dicom.TryRead(path));+ }+}++/// <summary>Writes small DICOM Part 10 files.</summary>+internal sealed class DicomBuilder+{+ public int Width { get; init; } = 64;+ public int Height { get; init; } = 32;+ public int Frames { get; init; } = 1;+ public int BitsAllocated { get; init; } = 16;+ public int BitsStored { get; init; } = 12;+ public bool Signed { get; init; }+ public string Photometric { get; init; } = "MONOCHROME2";+ public bool Rgb { get; init; }+ /// <summary>Stored values from the left column to the right one.</summary>+ public (int Left, int Right) Ramp { get; init; } = (0, 4095);+ public double? Intercept { get; init; }+ public (double Center, double Width)? Window { get; init; }+ public bool ImplicitVr { get; init; }+ public bool BigEndian { get; init; }+ public bool Preamble { get; init; } = true;+ public bool NestedSequence { get; init; }+ public bool Deflated { get; init; }+ /// <summary>With <see cref="Rgb"/>: the planes hold this Y, Cb, Cr (YBR_FULL) instead of R 200, G 100, B 50.</summary>+ public (byte Y, byte Cb, byte Cr)? Ybr { get; init; }+ /// <summary>A compressed transfer syntax: the pixel data becomes one encapsulated fragment.</summary>+ public string? TransferSyntax { get; init; }++ public byte[] Build()+ {+ var syntax = TransferSyntax ?? (ImplicitVr ? "1.2.840.10008.1.2" : BigEndian ? "1.2.840.10008.1.2.2"+ : Deflated ? "1.2.840.10008.1.2.1.99" : "1.2.840.10008.1.2.1");+ using var body = new MemoryStream();+ Element(body, 0x0008, 0x0016, "UI", Text("1.2.840.10008.5.1.4.1.1.7"));+ if (NestedSequence)+ {+ // (0008,1115) Referenced Series Sequence of undefined length with one item of undefined length.+ Header(body, 0x0008, 0x1115, "SQ", 0xFFFFFFFF);+ ItemHeader(body, 0xE000, 0xFFFFFFFF);+ Element(body, 0x0020, 0x000E, "UI", Text("1.2.3"));+ ItemHeader(body, 0xE00D, 0);+ ItemHeader(body, 0xE0DD, 0);+ }+ Element(body, 0x0028, 0x0002, "US", UShort(Rgb ? 3 : 1));+ Element(body, 0x0028, 0x0004, "CS", Text(Ybr is not null ? "YBR_FULL" : Rgb ? "RGB" : Photometric));+ if (Rgb)+ Element(body, 0x0028, 0x0006, "US", UShort(1)); // planar: all red, then green, then blue+ if (Frames > 1)+ Element(body, 0x0028, 0x0008, "IS", Text(Frames.ToString(System.Globalization.CultureInfo.InvariantCulture)));+ Element(body, 0x0028, 0x0010, "US", UShort(Height));+ Element(body, 0x0028, 0x0011, "US", UShort(Width));+ Element(body, 0x0028, 0x0100, "US", UShort(BitsAllocated));+ Element(body, 0x0028, 0x0101, "US", UShort(BitsStored));+ Element(body, 0x0028, 0x0102, "US", UShort(BitsStored - 1));+ Element(body, 0x0028, 0x0103, "US", UShort(Signed ? 1 : 0));+ if (Window is { } window)+ {+ Element(body, 0x0028, 0x1050, "DS", Text($"{window.Center}\\{window.Center + 10}"));+ Element(body, 0x0028, 0x1051, "DS", Text($"{window.Width}\\{window.Width + 10}"));+ }+ if (Intercept is { } intercept)+ {+ Element(body, 0x0028, 0x1052, "DS", Text(intercept.ToString(System.Globalization.CultureInfo.InvariantCulture)));+ Element(body, 0x0028, 0x1053, "DS", Text("1"));+ }+ if (TransferSyntax is not null)+ {+ // Encapsulated: undefined length, an empty offset table and one fragment.+ Header(body, 0x7FE0, 0x0010, "OB", 0xFFFFFFFF);+ ItemHeader(body, 0xE000, 0);+ ItemHeader(body, 0xE000, 4);+ body.Write([0xFF, 0xD8, 0xFF, 0xD9]);+ ItemHeader(body, 0xE0DD, 0);+ }+ else+ {+ Element(body, 0x7FE0, 0x0010, BitsAllocated == 8 ? "OB" : "OW", Pixels());+ }++ using var meta = new MemoryStream();+ Write(meta, 0x0002, 0x0001, "OB", [0, 1], littleEndian: true, explicitVr: true);+ Write(meta, 0x0002, 0x0010, "UI", Text(syntax), littleEndian: true, explicitVr: true);++ using var file = new MemoryStream();+ if (Preamble)+ {+ file.Write(new byte[128]);+ file.Write("DICM"u8);+ var length = new byte[4];+ BinaryPrimitives.WriteUInt32LittleEndian(length, (uint)meta.Length);+ Write(file, 0x0002, 0x0000, "UL", length, littleEndian: true, explicitVr: true);+ meta.WriteTo(file);+ }+ if (Deflated)+ {+ using var deflate = new System.IO.Compression.DeflateStream(file, System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true);+ body.WriteTo(deflate);+ }+ else+ {+ body.WriteTo(file);+ }+ return file.ToArray();+ }++ private byte[] Pixels()+ {+ var bytesPerSample = BitsAllocated / 8;+ if (Rgb)+ {+ var (first, second, third) = Ybr ?? (200, 100, 50);+ var planes = new byte[Width * Height * 3];+ Array.Fill(planes, first, 0, Width * Height);+ Array.Fill(planes, second, Width * Height, Width * Height);+ Array.Fill(planes, third, 2 * Width * Height, Width * Height);+ return planes;+ }+ var frame = new byte[Width * Height * bytesPerSample];+ for (var y = 0; y < Height; y++)+ for (var x = 0; x < Width; x++)+ {+ var value = Ramp.Left + (Ramp.Right - Ramp.Left) * x / (Width - 1);+ var stored = (ushort)(value & ((1 << BitsStored) - 1)); // two's complement in the stored bits+ var at = (y * Width + x) * bytesPerSample;+ if (bytesPerSample == 1)+ frame[at] = (byte)stored;+ else if (BigEndian)+ BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(at), stored);+ else+ BinaryPrimitives.WriteUInt16LittleEndian(frame.AsSpan(at), stored);+ }+ return Enumerable.Repeat(frame, Frames).SelectMany(f => f).ToArray();+ }++ private static byte[] Text(string value) => Encoding.ASCII.GetBytes(value.Length % 2 == 0 ? value : value + " ");++ private byte[] UShort(int value)+ {+ var bytes = new byte[2];+ if (BigEndian)+ BinaryPrimitives.WriteUInt16BigEndian(bytes, (ushort)value);+ else+ BinaryPrimitives.WriteUInt16LittleEndian(bytes, (ushort)value);+ return bytes;+ }++ private void Element(Stream stream, ushort group, ushort element, string vr, byte[] value) =>+ Write(stream, group, element, vr, value, !BigEndian, !ImplicitVr);++ private void Header(Stream stream, ushort group, ushort element, string vr, uint length) =>+ WriteHeader(stream, group, element, vr, length, !BigEndian, !ImplicitVr);++ private void ItemHeader(Stream stream, ushort element, uint length)+ {+ var header = new byte[8];+ if (BigEndian)+ {+ BinaryPrimitives.WriteUInt16BigEndian(header, 0xFFFE);+ BinaryPrimitives.WriteUInt16BigEndian(header.AsSpan(2), element);+ BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(4), length);+ }+ else+ {+ BinaryPrimitives.WriteUInt16LittleEndian(header, 0xFFFE);+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(2), element);+ BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4), length);+ }+ stream.Write(header);+ }++ private static void Write(Stream stream, ushort group, ushort element, string vr, byte[] value, bool littleEndian, bool explicitVr)+ {+ WriteHeader(stream, group, element, vr, (uint)value.Length, littleEndian, explicitVr);+ stream.Write(value);+ }++ private static void WriteHeader(Stream stream, ushort group, ushort element, string vr, uint length, bool littleEndian, bool explicitVr)+ {+ var longForm = vr is "OB" or "OW" or "SQ" or "UN";+ var header = new byte[!explicitVr || longForm ? (explicitVr ? 12 : 8) : 8];+ void U16(int at, ushort v)+ {+ if (littleEndian) BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(at), v);+ else BinaryPrimitives.WriteUInt16BigEndian(header.AsSpan(at), v);+ }+ void U32(int at, uint v)+ {+ if (littleEndian) BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(at), v);+ else BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(at), v);+ }+ U16(0, group);+ U16(2, element);+ if (!explicitVr)+ {+ U32(4, length);+ }+ else+ {+ Encoding.ASCII.GetBytes(vr, header.AsSpan(4));+ if (longForm)+ U32(8, length);+ else+ U16(6, (ushort)length);+ }+ stream.Write(header);+ }+}diff --git a/tests/Filee.Engines.Tests/ImageFormatTests.cs b/tests/Filee.Engines.Tests/ImageFormatTests.csnew file mode 100644index 00000000..673be188--- /dev/null+++ b/tests/Filee.Engines.Tests/ImageFormatTests.cs@@ -0,0 +1,158 @@+// The less common raster formats ImageMagick (Magick.NET Q8) reads and writes for Filee: every one is checked against+// the coders the bundled build really has, then converted there and back. Inputs are generated in the tests.++using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Presets;+using Filee.Engines.Magick;+using ImageMagick;++namespace Filee.Engines.Tests;++public class ImageFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ /// <summary>Formats Filee reads and writes with ImageMagick's own coders (APNG is Filee's, see ApngTests).</summary>+ private static readonly string[] ReadWrite = ["mng", "qoi", "dds", "pcx", "cur", "xpm", "xbm", "wbmp", "pam", "pfm", "sgi", "ras", "miff"];++ private static readonly string[] ReadOnly = ["dcm", "pcd", "exr", "hdr"];++ private static void AssertDone(ConversionJob job)+ {+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");+ Assert.All(job.Outputs, o => Assert.True(new FileInfo(o).Length > 0, o));+ }++ [Fact]+ public void The_bundled_imagemagick_has_a_coder_for_every_format()+ {+ var formats = MagickNET.SupportedFormats.ToDictionary(f => f.Format);+ foreach (var id in ReadWrite.Concat(ReadOnly))+ {+ var info = formats[ImageEncoder.ToMagickFormat(id)];+ Assert.True(info.SupportsReading, $"{id} read");+ Assert.Equal(ReadWrite.Contains(id), FormatRegistry.Get(id).Writable);+ if (ReadWrite.Contains(id))+ Assert.True(info.SupportsWriting, $"{id} write");+ }+ Assert.Equal(ReadWrite.Order(), ImageEncoder.Writable.Intersect(ReadWrite.Concat(ReadOnly)).Order());+ Assert.Equal(ReadWrite.Concat(ReadOnly).Order(), ImageEncoder.Readable.Intersect(ReadWrite.Concat(ReadOnly)).Order());+ }++ /// <summary>+ /// PNG → format → PNG. <paramref name="maxError"/> is the root mean square error (0–1) of the round trip against the+ /// source, both flattened onto white like formats without transparency do: lossless formats give 0, DDS (DXT+ /// blocks) a little, the 1-bit XBM and WBMP a lot.+ /// </summary>+ [Theory]+ [InlineData("mng", 0.001)]+ [InlineData("qoi", 0.001)]+ [InlineData("dds", 0.05)]+ [InlineData("pcx", 0.001)]+ [InlineData("cur", 0.02)] // scaled to 256 px+ [InlineData("xpm", 0.02)]+ [InlineData("xbm", 0.7)]+ [InlineData("wbmp", 0.7)]+ [InlineData("pam", 0.001)]+ [InlineData("pfm", 0.01)]+ [InlineData("sgi", 0.001)]+ [InlineData("ras", 0.001)]+ [InlineData("miff", 0.001)]+ public async Task Png_converts_to_the_format_and_back(string format, double maxError)+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "a.png", MagickFormat.Png);++ var to = await fx.ConvertAsync([source], new Preset { TargetFormat = format });++ AssertDone(to);+ var converted = to.Outputs.Single();+ Assert.Equal("." + FormatRegistry.Get(format).PrimaryExtension, Path.GetExtension(converted));+ var expectedWidth = format == "cur" ? 256u : 320u;+ using (var image = new MagickImage(converted, new MagickReadSettings { Format = ImageEncoder.ToMagickFormat(format) }))+ Assert.Equal(expectedWidth, image.Width);++ var back = await fx.ConvertAsync([converted], new Preset { TargetFormat = "png", Output = { FileNamePattern = "{name}_back" } });++ AssertDone(back);+ using var result = new MagickImage(back.Outputs.Single());+ using var original = new MagickImage(source);+ Assert.Equal((expectedWidth, original.Height * expectedWidth / original.Width), (result.Width, result.Height));+ if (format == "cur")+ original.Resize(result.Width, result.Height);+ Assert.InRange(OnWhite(original).Compare(OnWhite(result), ErrorMetric.RootMeanSquared), 0, maxError);+ }++ private static MagickImage OnWhite(MagickImage image)+ {+ var flat = (MagickImage)image.Clone();+ flat.BackgroundColor = MagickColors.White;+ flat.Alpha(AlphaOption.Remove);+ flat.ColorSpace = ColorSpace.sRGB;+ return flat;+ }++ [Fact]+ public async Task An_animated_gif_becomes_an_animated_mng_and_back()+ {+ var dir = fx.NewFolder();+ var gif = Path.Combine(dir, "anim.gif");+ using (var frames = new MagickImageCollection())+ {+ foreach (var (color, delay) in new[] { (MagickColors.Red, 20u), (MagickColors.Lime, 30u), (MagickColors.Blue, 40u) })+ frames.Add(new MagickImage(color, 64, 48) { AnimationDelay = delay });+ frames.Write(gif, MagickFormat.Gif);+ }++ var mng = await fx.ConvertAsync([gif], new Preset { TargetFormat = "mng" });+ AssertDone(mng);+ var back = await fx.ConvertAsync([mng.Outputs.Single()], new Preset { TargetFormat = "gif", Output = { FileNamePattern = "{name}_back" } });++ AssertDone(back);+ using var again = new MagickImageCollection(back.Outputs.Single());+ Assert.Equal(3, again.Count);+ Assert.Equal([20u, 30u, 40u], again.Select(f => f.AnimationDelay));+ }++ [Theory]+ [InlineData("exr", MagickFormat.Exr, 320u)]+ [InlineData("hdr", MagickFormat.Hdr, 320u)]+ [InlineData("pcd", MagickFormat.Pcd, 768u)] // Photo CD's base resolution+ public async Task Read_only_formats_convert_to_png(string format, MagickFormat magickFormat, uint expectedWidth)+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "picture." + format, magickFormat);++ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "png" });++ AssertDone(job);+ using var png = new MagickImage(job.Outputs.Single());+ Assert.Equal(expectedWidth, png.Width);+ }++ [Fact]+ public async Task Sgi_files_named_rgb_are_read_as_sgi_not_as_raw_pixels()+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "texture.rgb", MagickFormat.Sgi);++ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "png" });++ AssertDone(job);+ using var png = new MagickImage(job.Outputs.Single());+ Assert.Equal((320u, 200u), (png.Width, png.Height));+ }++ [Fact]+ public async Task Large_pictures_become_cursors_of_at_most_256_pixels()+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "big.png", MagickFormat.Png, 600, 300);++ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "cur" });++ AssertDone(job);+ using var cursor = new MagickImage(job.Outputs.Single(), new MagickReadSettings { Format = MagickFormat.Cur });+ Assert.Equal((256u, 128u), (cursor.Width, cursor.Height));+ }+}diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.csindex d836d40a..e1474db4 100644--- a/tests/Filee.Engines.Tests/MediaTests.cs+++ b/tests/Filee.Engines.Tests/MediaTests.cs@@ -50,6 +50,8 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>[InlineData("gif", "mp4")][InlineData("gif", "webm")][InlineData("png", "mov")]+ [InlineData("apng", "mp4")]+ [InlineData("mov", "apng")][InlineData("rm", "mp4")][InlineData("dss", "mp3")]public void Media_conversions_take_one_ffmpeg_step(string from, string to)@@ -76,6 +78,7 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>[InlineData("jpg", "mp4", "magick")][InlineData("avif", "webm", "magick")][InlineData("svg", "mov", "vector")]+ [InlineData("qoi", "mp4", "magick")]public void Photos_reach_video_as_a_full_colour_png_not_a_gif(string from, string to, string imageEngine){var route = Planner().Plan(from, to);@@ -87,6 +90,7 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>[InlineData("pdf", "mp4", "pdfium")] // a slideshow of the pages[InlineData("webp", "mov", "magick")] // an animated WebP keeps moving[InlineData("tiff", "webm", "magick")]+ [InlineData("mng", "mp4", "magick")]public void Animations_and_pages_still_reach_video_through_gif(string from, string to, string imageEngine){var route = Planner().Plan(from, to);@@ -262,6 +266,20 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.Contains("paletteuse", After(second, "-filter_complex"));}+ [Fact]+ public void Apng_is_one_full_colour_looping_pass_with_the_gif_limits()+ {+ var pass = Assert.Single(MediaEncoding.Plan("in.mp4", "out.apng", "apng", new MediaOptions { Quality = MediaQuality.High },+ new MediaInfo(TimeSpan.FromSeconds(3), Hd, new AudioStreamInfo(2, 44100), null), "work"));+ var args = pass.Arguments;+ Assert.Equal("fps=15,scale=w='min(iw,640)':h=ih:force_original_aspect_ratio=decrease:flags=lanczos", After(args, "-vf"));+ Assert.Equal("apng", After(args, "-c:v"));+ Assert.Equal("rgb24", After(args, "-pix_fmt"));+ Assert.Equal("0", After(args, "-plays"));+ Assert.Equal("apng", After(args, "-f"));+ Assert.Contains("-an", args);+ }+[Fact]public void A_still_picture_is_shown_for_five_seconds_at_full_size(){@@ -536,6 +554,51 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.InRange(mp4.Duration, 1.5, 2.5);}+ [Fact]+ public async Task Video_becomes_an_apng_and_back()+ {+ SkipUnlessInstalled();+ var source = await MakeClipAsync(fx.NewFolder(), "anim.mp4", seconds: 1, size: "640x360", audio: false);+ var apng = await ConvertAsync(source, "apng");+ var probed = await ProbeAsync(apng);+ Assert.Equal("apng", probed.Video?.Codec);+ Assert.Equal((480, 270), (probed.Video!.Width, probed.Video.Height)); // Balanced: at most 480 px wide+ Assert.InRange(probed.Video.Frames, 10, 15); // 1 s at 12 fps++ // Filee's own reader takes FFmpeg's APNG: every frame, as GIF.+ var gif = await ConvertAsync(apng, "gif");+ using (var frames = new ImageMagick.MagickImageCollection(gif))+ Assert.Equal(probed.Video.Frames, frames.Count);++ // APNG → MP4 straight through FFmpeg.+ var mp4 = await ProbeAsync(await ConvertAsync(apng, "mp4"));+ Assert.Equal("h264", mp4.Video?.Codec);+ Assert.InRange(mp4.Duration, 0.7, 1.3);+ }++ [Fact]+ public async Task Ffmpeg_reads_the_apng_filee_writes()+ {+ SkipUnlessInstalled();+ var folder = fx.NewFolder();+ var gif = Path.Combine(folder, "anim.gif");+ using (var frames = new ImageMagick.MagickImageCollection())+ {+ foreach (var color in new[] { ImageMagick.MagickColors.Red, ImageMagick.MagickColors.Lime, ImageMagick.MagickColors.Blue })+ frames.Add(new ImageMagick.MagickImage(color, 64, 48) { AnimationDelay = 20 });+ frames.Write(gif, ImageMagick.MagickFormat.Gif);+ }++ var apng = await ConvertAsync(gif, "apng");++ var probed = await ProbeAsync(apng);+ Assert.Equal("apng", probed.Video?.Codec);+ Assert.Equal((64, 48, 3), (probed.Video!.Width, probed.Video.Height, probed.Video.Frames));+ // FFmpeg takes the frame delays: three frames of 0.2 s make a 0.6 s video.+ var mp4 = await ProbeAsync(await ConvertAsync(apng, "mp4"));+ Assert.InRange(mp4.Duration, 0.5, 0.75);+ }+[Fact]public async Task A_photo_becomes_a_still_video_in_full_colour(){