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
Photos → video in full colour, images → HEIC
KnifeLemon675dbcc8729e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f08810d1..0ae78118 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,15 @@ find it, what it does and doesn't do.another, e.g. to post a whole document at once. Use **Long image** on the PDF donut (PNG), or tick "Stack the pagesinto one tall image" in any image preset. Pages of different widths are centred; a result taller than the formatstores (JPG 65,500 px, WebP 16,383 px) or very large is scaled down to fit. TIFF and GIF keep one page per frame.+- **Photos → video in full colour.** HEIC, JPG, PNG, AVIF and other pictures → MP4, MOV or WEBM (with FFmpeg) used+ to pass through a GIF, which leaves 256 colours and bands skies and skin. They now go straight from a full-size PNG:+ a 5-second still video at the photo's own size, with its colours (Display P3 photos stay P3) and transparent areas+ in black. Only photos over about 36 megapixels (48 MP phone cameras) are scaled down, to the largest picture H.264+ and VP9 players decode. Animated GIF/WebP and PDF pages still become a moving video or a slideshow.+- **Save images as HEIC** (with FFmpeg). Any image Filee reads → HEIC, the format iPhones take photos in: about a+ quarter of a JPG's size at the same quality, stored in 512-pixel tiles like a phone photo, upright, with the colour+ profile and Exif kept. The **HEIC** preset is on the Presets page (quality 80); add it to a donut to use it.+ Transparent areas are filled with the preset's background colour.## 1.9.0diff --git a/README.ko.md b/README.ko.mdindex 59d0eae6..47a8cb60 100644--- a/README.ko.md+++ b/README.ko.md@@ -128,7 +128,7 @@ Finder에서 파일을 우클릭하면 "Filee로 변환"이 나와요. FFmpeg와| 원본 | 변환 대상 ||---|---|-| **이미지**: 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 등)는 읽기 | 위 형식끼리, PDF, 크기 조정, 흑백 |+| **이미지**: 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, 크기 조정, 흑백 || **벡터**: 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 |diff --git a/README.md b/README.mdindex b43a3a26..6705aea8 100644--- a/README.md+++ b/README.md@@ -131,7 +131,7 @@ Dolphin. Ubuntu 24.04 is the tested baseline; `INSTALL.txt` in the package lists| 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, PDF, resized, grayscale |+| **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 || **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 |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 89f779d9..4fab6d80 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -118,7 +118,7 @@ Nautilus、Nemo、Thunar 或 Dolphin 的右键菜单。测试基准为 Ubuntu 24| 源格式 | 目标格式 ||---|---|-| **图片**: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 等)仅读取 | 上述格式互转、PDF、缩放、灰度 |+| **图片**: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、缩放、灰度 || **矢量图**: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 |diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 6c5308f8..62f2a378 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, 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 ↔ each other; HEIC (written with FFmpeg), XCF, camera RAW (LibRaw) 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 → MP4/WEBM/MOV |+| 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 || 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@@ -484,7 +484,8 @@ 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 to MP4, WEBM and MOV.+and to every audio format (the sound track); every audio format to every audio format; and GIF 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).@@ -524,5 +525,25 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on(FFmpeg's encoders use every core themselves).- Video → PNG writes one still frame (a tenth into the video, where the picture has usually faded in); the imageengines turn it into JPG, WEBP, PDF, …. The GIF edge costs more, so these routes never go through an animated GIF- of the whole video. Images and PDFs → MP4/WEBM/MOV are possible through GIF (a slideshow of the PDF's pages, a- single frame for a photo).+ of the whole video.+- Pictures → MP4/WEBM/MOV go through a full-size PNG from the image engines (HEIC → PNG → MOV): a 5-second still at+ 30 fps, one quality step above the preset (identical frames cost almost nothing; x264 `-tune stillimage`). The+ PNG's ICC profile is read (`-flags2 +icc_profiles`), so primaries and transfer are tagged as the photo's (Display+ P3 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.+- **Images → HEIC** (`Heic/HeicWriter.cs`): ImageMagick has no HEVC encoder and FFmpeg no HEIF muxer, so the work is+ split. ImageMagick reads any image it knows and applies the preset (orientation, resize, metadata; transparency is+ flattened onto the background colour, HEIC alpha needs an auxiliary picture Filee does not write) and writes an+ 8-bit PNG. FFmpeg pads it to whole 512 × 512 tiles with its own edge pixels (`fillborders`), converts to BT.601+ full-range 4:2:0 like JPEG and cameras, cuts the tiles (`untile`) and has x265 encode each as an IDR picture of+ the Main profile (`-force_key_frames expr:1 -forced-idr 1`, `open-gop=0`; with `keyint=1` x265 would signal the+ "Main Intra" range extensions profile, which the `heic` brand does not allow and Windows decodes wrongly). Pictures+ up to 512 × 512 are one coded picture. Quality 1–100 maps to CRF 50 − 0.4 × quality (90 → 14, 80 → 18).+ `HevcStream` splits the Annex B output and builds the hvcC record; `HeifFile` writes ftyp `heic`/`mif1`, a grid+ item cropping the tiles to the picture size, hidden tile items, `ispe`/`pixi`, the ICC profile as `colr prof` (or+ `nclx` sRGB, BT.601 full range when there is none) and Exif (orientation reset to 1, thumbnail removed) as a `cdsc`+ item. Checked with libheif (Magick.NET), FFmpeg's HEIF demuxer and Windows' HEIF/HEVC extensions; a smooth 2000 ×+ 1500 picture is a quarter the size of a JPG at the same PSNR.diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 2d433f4b..369eb794 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -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, GZ, ISO and other archives, repacks them as ZIP, 7Z or TAR.GZ and compresses files into one archive (7-Zip).","engine.ebook.description": "E-books: EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) to PDF, EPUB, DOCX and text; documents and Markdown to EPUB; PDF to CBZ.",- "engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, AVI, MP3, M4A, WAV, FLAC and more; extracts the sound of videos and makes GIFs.",+ "engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, AVI, MP3, M4A, WAV, FLAC and more; extracts the sound of videos, makes GIFs and saves images as HEIC.","engine.pandoc.description": "Markdown and HTML ↔ ODT and RTF, DOCX → Markdown, and reStructuredText 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 8b6e9282..2d5214ba 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -78,7 +78,7 @@"engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.","engine.archive.description": "ZIP, 7Z, RAR, TAR, GZ, ISO 등 압축 파일을 풀고, ZIP·7Z·TAR.GZ로 다시 묶거나 여러 파일을 압축 파일 하나로 만들어요(7-Zip).","engine.ebook.description": "전자책: EPUB, MOBI, AZW3, FB2와 만화책(CBZ, CBR)을 PDF, EPUB, DOCX, 텍스트로 바꾸고, 문서와 마크다운은 EPUB으로, PDF는 CBZ로 만들어요.",- "engine.ffmpeg.description": "동영상·오디오: MP4, MOV, MKV, WEBM, AVI, MP3, M4A, WAV, FLAC 등. 동영상에서 소리만 뽑거나 GIF도 만들어요.",+ "engine.ffmpeg.description": "동영상·오디오: MP4, MOV, MKV, WEBM, AVI, MP3, M4A, WAV, FLAC 등. 동영상에서 소리만 뽑거나 GIF를 만들고, 이미지를 HEIC로 저장해요.","engine.pandoc.description": "마크다운·HTML ↔ ODT·RTF, DOCX → 마크다운, reStructuredText·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 0a6b428c..a75c78f3 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -78,7 +78,7 @@"engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。","engine.archive.description": "解压 ZIP、7Z、RAR、TAR、GZ、ISO 等压缩文件,重新打包为 ZIP、7Z 或 TAR.GZ,或把多个文件压缩成一个(7-Zip)。","engine.ebook.description": "电子书:EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)转为 PDF、EPUB、DOCX 和文本;文档和 Markdown 转为 EPUB;PDF 转为 CBZ。",- "engine.ffmpeg.description": "视频和音频:MP4、MOV、MKV、WEBM、AVI、MP3、M4A、WAV、FLAC 等;可提取视频中的声音,也能制作 GIF。",+ "engine.ffmpeg.description": "视频和音频:MP4、MOV、MKV、WEBM、AVI、MP3、M4A、WAV、FLAC 等;可提取视频中的声音、制作 GIF,还能把图片保存为 HEIC。","engine.pandoc.description": "Markdown 和 HTML ↔ ODT、RTF,DOCX → Markdown,以及 reStructuredText、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 c19fc875..d5789e18 100644--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs@@ -27,7 +27,7 @@ public sealed record Choice<T>(T Value, string Label, string? Detail = null) : Ipublic sealed partial class PresetEditorViewModel : ObservableObject{- private static readonly HashSet<string> LossyTargets = ["jpg", "webp", "avif"];+ private static readonly HashSet<string> LossyTargets = ["jpg", "webp", "avif", "heic"];/// <summary>Audio targets without a bitrate or quality to choose.</summary>private static readonly HashSet<string> LosslessAudioTargets = ["wav", "flac", "aiff"];diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex a24c7ec9..46c2be56 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"], Writable: false),+ new("heic", "HEIC", FormatCategory.Image, ["heic", "heif"]),new("jxl", "JPEG XL", FormatCategory.Image, ["jxl"]),new("jp2", "JPEG 2000", FormatCategory.Image, ["jp2", "j2k", "jpf", "jpx"]),new("psd", "PSD", FormatCategory.Image, ["psd"]),diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.csindex 292c4574..f2f5aeba 100644--- a/src/Filee.Core/Presets/BuiltInData.cs+++ b/src/Filee.Core/Presets/BuiltInData.cs@@ -27,6 +27,7 @@ public static class BuiltInDatanew() { Id = "to-ico", Name = "ICO", TargetFormat = "ico" },new() { Id = "to-gif", Name = "GIF", TargetFormat = "gif" },new() { Id = "to-avif", Name = "AVIF", TargetFormat = "avif", Image = { Quality = 60 } },+ new() { Id = "to-heic", Name = "HEIC", TargetFormat = "heic", Image = { Quality = 80 } },new(){Id = "half-size", NameKey = "preset.half_size", TargetFormat = SameAsSource,diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.csindex 30dac1b5..be82bf7a 100644--- a/src/Filee.Core/Presets/Preset.cs+++ b/src/Filee.Core/Presets/Preset.cs@@ -82,7 +82,7 @@ public enum TiffCompression/// <summary>Raster image encoding options.</summary>public sealed class ImageOptions{- /// <summary>Lossy quality 1-100 (JPG, WEBP, AVIF).</summary>+ /// <summary>Lossy quality 1-100 (JPG, WEBP, AVIF, HEIC).</summary>public int Quality { get; set; } = 90;public ResizeMode Resize { get; set; } = ResizeMode.None;diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 2deba682..e3791a88 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -339,12 +339,15 @@ internal static class SettingsMigrations}}- // v9: PDF → one tall image (all pages stacked), on the PDF donut after JPG (issue #50).+ // v9: PDF → one tall image (all pages stacked), on the PDF donut after JPG (issue #50), and a HEIC preset+ // (written with FFmpeg), on no donut like AVIF.if (from < 9){- if (presets.All(p => p.Id != "pdf-long-image"))+ foreach (var id in new[] { "pdf-long-image", "to-heic" }){- presets.Add(BuiltInData.CreatePresets().Single(p => p.Id == "pdf-long-image"));+ if (presets.Any(p => p.Id == id))+ continue;+ presets.Add(BuiltInData.CreatePresets().Single(p => p.Id == id));changed = true;}changed |= Offer(presets, profiles, "pdf", "pdf-long-image", "to-jpg");diff --git a/src/Filee.Engines/Cad/CadConverter.cs b/src/Filee.Engines/Cad/CadConverter.csindex c784adb1..cf5309cd 100644--- a/src/Filee.Engines/Cad/CadConverter.cs+++ b/src/Filee.Engines/Cad/CadConverter.cs@@ -39,7 +39,7 @@ public sealed class CadConverter(ILogger? logger = null) : IConverternew("dxf", "dwg"),.. from source in Sourcesfrom target in (string[])["pdf", "svg", .. ImageEncoder.Writable]- select new ConversionEdge(source, target),+ select ImageEncoder.Edge(source, target),];public EngineStatus GetStatus() => EngineStatus.Available("ACadSharp: DWG R13–2018+, DXF", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("ACadSharp", typeof(ACadSharp.CadDocument))}");diff --git a/src/Filee.Engines/Heic/HeicWriter.cs b/src/Filee.Engines/Heic/HeicWriter.csnew file mode 100644index 00000000..f1e175f8--- /dev/null+++ b/src/Filee.Engines/Heic/HeicWriter.cs@@ -0,0 +1,134 @@+// Image → HEIC. ImageMagick reads the picture and applies the preset (orientation, size, background), FFmpeg's x265+// encodes it as HEVC tiles and HeifFile puts them into the HEIC container with the colour profile and Exif.++using System.Globalization;+using Filee.Core.Conversion;+using Filee.Engines.Infrastructure;+using Filee.Engines.Magick;+using Filee.Engines.Media;+using ImageMagick;++namespace Filee.Engines.Heic;++/// <summary>Writes HEIC files with Filee's copy of FFmpeg (it has the HEVC encoder ImageMagick lacks).</summary>+internal static class HeicWriter+{+ /// <summary>Tile size of larger pictures, as cameras write them: every decoder handles 512 × 512 HEVC pictures.</summary>+ public const int TileSize = 512;++ /// <summary>A prepared picture: an 8-bit RGB PNG in the work folder and the metadata that goes next to it.</summary>+ private sealed record Picture(string Png, int Width, int Height, byte[]? IccProfile, byte[]? Exif);++ public static async Task<IReadOnlyList<string>> ConvertAsync(string ffmpeg, ConversionStep step, IProgress<double>? progress,+ CancellationToken cancellationToken)+ {+ var pictures = await Task.Run(() => Prepare(step, cancellationToken), cancellationToken);+ progress?.Report(0.15);++ var written = new List<string>();+ for (var i = 0; i < pictures.Count; i++)+ {+ var picture = pictures[i];+ var share = 0.85 / pictures.Count;+ var start = 0.15 + i * share;+ var stream = Path.Combine(step.WorkDirectory, $"heic-{Guid.NewGuid():N}.hevc");+ var (columns, rows, tileWidth, tileHeight) = Layout(picture.Width, picture.Height);++ ProcessResult result;+ using (ProgressEstimate.Start(progress, TimeSpan.FromSeconds(5), start, start + share * 0.95))+ result = await FfmpegRunner.RunAsync(ffmpeg, Arguments(picture.Png, stream, picture.Width, picture.Height,+ step.Preset.Image.Quality), null, cancellationToken);+ if (result.ExitCode != 0)+ {+ var reason = FfmpegRunner.Summarize(result.StandardError);+ throw new InvalidOperationException($"FFmpeg failed (exit code {result.ExitCode}){(reason.Length > 0 ? ": " + reason : ".")}");+ }++ var heif = HeifFile.Write(new HeifImage(picture.Width, picture.Height, HevcStream.Parse(await File.ReadAllBytesAsync(stream, cancellationToken)),+ tileWidth, tileHeight, columns, rows, picture.IccProfile, picture.Exif));+ var output = step.Output.Allocate("heic", pictures.Count > 1 ? $"_p{i + 1}" : null);+ if (output is null)+ continue;+ await File.WriteAllBytesAsync(output, heif, cancellationToken);+ written.Add(output);+ }+ progress?.Report(1);+ return written;+ }++ /// <summary>+ /// Reads the source with ImageMagick and writes every picture to convert (TIFF pages; the first frame of an+ /// animation) as a PNG, after the preset's orientation, resize and metadata options. HEIC is written without+ /// alpha, so transparency is flattened onto the preset's background colour.+ /// </summary>+ private static List<Picture> Prepare(ConversionStep step, CancellationToken cancellationToken)+ {+ using var images = ImageReader.Read(step.InputPath, step.From, step.Preset);+ var pictures = new List<Picture>();+ foreach (var frame in ImageEncoder.SelectFrames(images, step.From, "heic"))+ {+ cancellationToken.ThrowIfCancellationRequested();+ ImageEncoder.ApplyOptions(frame, step.Preset.Image, "heic");+ var icc = frame.GetColorProfile()?.ToByteArray();+ byte[]? exif = null;+ if (frame.GetExifProfile() is { } profile)+ {+ // The pixels are upright now (AutoOrient), and an old thumbnail would show them as they were.+ profile.SetValue(ExifTag.Orientation, (ushort)1);+ profile.RemoveThumbnail();+ exif = profile.ToByteArray();+ }++ var png = Path.Combine(step.WorkDirectory, $"heic-{Guid.NewGuid():N}.png");+ frame.Strip(); // FFmpeg only needs the pixels; the profiles are stored by HeifFile+ frame.Depth = 8;+ frame.Write(png, MagickFormat.Png24);+ pictures.Add(new Picture(png, (int)frame.Width, (int)frame.Height, icc, exif));+ }+ return pictures;+ }++ /// <summary>+ /// One coded picture for a picture up to 512 × 512, otherwise 512 × 512 tiles. Coded pictures have even sides+ /// (4:2:0); the grid crops the padding away again.+ /// </summary>+ internal static (int Columns, int Rows, int TileWidth, int TileHeight) Layout(int width, int height) =>+ width <= TileSize && height <= TileSize+ ? (1, 1, (width + 1) & ~1, (height + 1) & ~1)+ : ((width + TileSize - 1) / TileSize, (height + TileSize - 1) / TileSize, TileSize, TileSize);++ /// <summary>x265 constant quality for a preset quality of 1-100: 90 → 14, 80 → 18, 50 → 30.</summary>+ internal static int Crf(int quality) => Math.Clamp((int)Math.Round(50 - 0.4 * Math.Clamp(quality, 1, 100)), 0, 51);++ /// <summary>+ /// FFmpeg turns the PNG into raw HEVC: padded to whole tiles with its own edge pixels (black padding would bleed+ /// into the picture), BT.601 full-range 4:2:0 like JPEG and phone cameras, cut into tiles (row by row) and encoded+ /// by x265 as independent IDR pictures, 8-bit Main profile, which every HEIC decoder plays.+ /// </summary>+ internal static List<string> Arguments(string png, string output, int width, int height, int quality)+ {+ var (columns, rows, tileWidth, tileHeight) = Layout(width, height);+ int paddedWidth = columns * tileWidth, paddedHeight = rows * tileHeight;+ var filters = new List<string>();+ if (paddedWidth != width || paddedHeight != height)+ {+ filters.Add($"pad={paddedWidth}:{paddedHeight}:0:0");+ filters.Add($"fillborders=right={paddedWidth - width}:bottom={paddedHeight - height}:mode=smear");+ }+ filters.Add("scale=out_color_matrix=bt601:out_range=pc");+ filters.Add("format=yuv420p");+ if (columns * rows > 1)+ filters.Add($"untile={columns}x{rows}");++ return+ [+ .. MediaEncoding.Common, "-i", png, "-vf", string.Join(',', filters),+ // Every tile a forced IDR picture rather than keyint=1: with keyint=1 x265 signals "Main Intra", a range+ // extensions profile the "heic" brand does not allow and Windows' decoder gets wrong.+ "-c:v", "libx265", "-preset", "medium", "-crf", Crf(quality).ToString(CultureInfo.InvariantCulture),+ "-force_key_frames", "expr:1", "-forced-idr", "1",+ "-x265-params", "bframes=0:open-gop=0:info=0:range=full:colormatrix=smpte170m:log-level=error",+ "-f", "hevc", output,+ ];+ }+}diff --git a/src/Filee.Engines/Heic/HeifFile.cs b/src/Filee.Engines/Heic/HeifFile.csnew file mode 100644index 00000000..b696fb51--- /dev/null+++ b/src/Filee.Engines/Heic/HeifFile.cs@@ -0,0 +1,285 @@+// Writes HEIC files (ISO/IEC 23008-12, HEIF with HEVC pictures): a primary picture that is either one coded picture+// or, like an iPhone photo, a grid of 512 × 512 tiles, with its colour profile and Exif. FFmpeg only encodes the+// HEVC pictures; it has no HEIF muxer.++using System.Buffers.Binary;+using System.Text;++namespace Filee.Engines.Heic;++/// <summary>One picture to store as HEIC.</summary>+/// <param name="Width">Picture width; the tiles may extend beyond it (the grid crops them).</param>+/// <param name="Height">Picture height.</param>+/// <param name="Stream">Coded tiles, row by row (one picture when <paramref name="Columns"/> × <paramref name="Rows"/> is 1).</param>+/// <param name="TileWidth">Width of every coded tile.</param>+/// <param name="TileHeight">Height of every coded tile.</param>+/// <param name="IccProfile">ICC profile, or null to declare sRGB.</param>+/// <param name="Exif">Exif data starting with a TIFF header (an "Exif\0\0" prefix is skipped), or null.</param>+internal sealed record HeifImage(int Width, int Height, HevcStream Stream, int TileWidth, int TileHeight, int Columns, int Rows,+ byte[]? IccProfile = null, byte[]? Exif = null)+{+ /// <summary>True when the picture is a grid item rather than the coded picture itself.</summary>+ public bool IsGrid => Columns * Rows > 1 || TileWidth != Width || TileHeight != Height;+}++/// <summary>HEIF container writing.</summary>+internal static class HeifFile+{+ private const int Primary = 1;++ public static byte[] Write(HeifImage image)+ {+ var tiles = image.Stream.Pictures;+ if (tiles.Count != image.Columns * image.Rows)+ throw new InvalidDataException($"{tiles.Count} coded pictures for {image.Columns} × {image.Rows} tiles.");+ if (image.Columns > 256 || image.Rows > 256)+ throw new InvalidDataException("A HEIF grid holds at most 256 × 256 tiles.");++ // Item ids: 1 is the picture (the grid, or the only coded picture), then the tiles, then Exif.+ var grid = image.IsGrid;+ var tileIds = grid ? Enumerable.Range(Primary + 1, tiles.Count).ToList() : [Primary];+ var exif = ExifPayload(image.Exif);+ var exifId = exif is null ? 0 : tileIds[^1] + 1;++ var items = new List<(int Id, byte[] Data)>();+ if (grid)+ items.Add((Primary, GridDescription(image)));+ items.AddRange(tileIds.Select((id, i) => (id, tiles[i])));+ if (exif is not null)+ items.Add((exifId, exif));++ var ftyp = Box("ftyp", w =>+ {+ w.Text("heic");+ w.U32(0);+ w.Text("mif1");+ w.Text("heic");+ });+ // The item locations hold absolute offsets, so the header is built twice: its size does not depend on them.+ var header = Meta(image, items, tileIds, exifId, new Dictionary<int, long>());+ var offsets = new Dictionary<int, long>();+ long at = ftyp.Length + header.Length + 8; // + mdat box header+ foreach (var (id, data) in items)+ {+ offsets[id] = at;+ at += data.Length;+ }+ if (at > uint.MaxValue)+ throw new InvalidDataException("The picture is too large for a HEIC file.");+ header = Meta(image, items, tileIds, exifId, offsets);++ using var file = new MemoryStream();+ file.Write(ftyp);+ file.Write(header);+ var mdatSize = 8 + items.Sum(i => (long)i.Data.Length);+ Span<byte> mdatHeader = stackalloc byte[8];+ BinaryPrimitives.WriteUInt32BigEndian(mdatHeader, (uint)mdatSize);+ Encoding.ASCII.GetBytes("mdat", mdatHeader[4..]);+ file.Write(mdatHeader);+ foreach (var (_, data) in items)+ file.Write(data);+ return file.ToArray();+ }++ private static byte[] Meta(HeifImage image, List<(int Id, byte[] Data)> items, List<int> tileIds, int exifId, Dictionary<int, long> offsets) =>+ FullBox("meta", 0, 0, w =>+ {+ w.Raw(FullBox("hdlr", 0, 0, h =>+ {+ h.U32(0); // pre_defined+ h.Text("pict");+ h.Zeros(12);+ h.Raw([0]); // empty name+ }));+ // Data reference: everything is in this file.+ w.Raw(Box("dinf", d => d.Raw(FullBox("dref", 0, 0, r =>+ {+ r.U32(1);+ r.Raw(FullBox("url ", 0, 1, _ => { }));+ }))));+ w.Raw(FullBox("pitm", 0, 0, p => p.U16(Primary)));+ w.Raw(FullBox("iloc", 0, 0, l =>+ {+ l.Raw([0x44, 0x00]); // offset_size 4, length_size 4, base_offset_size 0+ l.U16(items.Count);+ foreach (var (id, data) in items)+ {+ l.U16(id);+ l.U16(0); // data_reference_index: this file+ l.U16(1); // one extent+ l.U32((uint)offsets.GetValueOrDefault(id));+ l.U32((uint)data.Length);+ }+ }));+ w.Raw(FullBox("iinf", 0, 0, l =>+ {+ l.U16(items.Count);+ foreach (var (id, _) in items)+ {+ var type = id == exifId ? "Exif" : id == Primary && image.IsGrid ? "grid" : "hvc1";+ // Tiles are hidden: viewers show the grid, not its pieces.+ var hidden = image.IsGrid && id != Primary && id != exifId;+ l.Raw(FullBox("infe", 2, hidden ? 1 : 0, e =>+ {+ e.U16(id);+ e.U16(0); // not protected+ e.Text(type);+ e.Raw([0]); // empty name+ }));+ }+ }));+ if (image.IsGrid || exifId != 0)+ {+ w.Raw(FullBox("iref", 0, 0, r =>+ {+ if (image.IsGrid)+ r.Raw(Box("dimg", d => References(d, Primary, tileIds)));+ if (exifId != 0)+ r.Raw(Box("cdsc", d => References(d, exifId, [Primary])));+ }));+ }+ w.Raw(Properties(image, tileIds));+ });++ private static void References(BoxWriter w, int from, List<int> to)+ {+ w.U16(from);+ w.U16(to.Count);+ foreach (var id in to)+ w.U16(id);+ }++ /// <summary>Item properties (ipco) and which item has which (ipma, 1-based indexes; hvcC is essential).</summary>+ private static byte[] Properties(HeifImage image, List<int> tileIds)+ {+ var depth = image.Stream.BitDepth;+ var properties = new List<byte[]>+ {+ Box("hvcC", w => w.Raw(image.Stream.Configuration)),+ FullBox("ispe", 0, 0, w => { w.U32((uint)image.TileWidth); w.U32((uint)image.TileHeight); }),+ FullBox("pixi", 0, 0, w => w.Raw([3, (byte)depth, (byte)depth, (byte)depth])),+ image.IccProfile is { } icc+ ? Box("colr", w => { w.Text("prof"); w.Raw(icc); })+ // sRGB (BT.709 primaries, sRGB transfer) stored as BT.601 full-range YCbCr, like JPEG.+ : Box("colr", w => { w.Text("nclx"); w.U16(1); w.U16(13); w.U16(6); w.Raw([0x80]); }),+ };+ const int hvcC = 1, tileSize = 2, pixi = 3, colr = 4;+ var associations = new List<(int Item, (int Index, bool Essential)[] Properties)>();+ if (image.IsGrid)+ {+ properties.Add(FullBox("ispe", 0, 0, w => { w.U32((uint)image.Width); w.U32((uint)image.Height); }));+ associations.Add((Primary, [(properties.Count, false), (pixi, false), (colr, false)]));+ associations.AddRange(tileIds.Select(id => (id, new[] { (hvcC, true), (tileSize, false) })));+ }+ else+ {+ associations.Add((Primary, [(hvcC, true), (tileSize, false), (pixi, false), (colr, false)]));+ }++ return Box("iprp", w =>+ {+ w.Raw(Box("ipco", c =>+ {+ foreach (var property in properties)+ c.Raw(property);+ }));+ w.Raw(FullBox("ipma", 0, 0, m =>+ {+ m.U32((uint)associations.Count);+ foreach (var (item, list) in associations)+ {+ m.U16(item);+ m.Raw([(byte)list.Length]);+ foreach (var (index, essential) in list)+ m.Raw([(byte)((essential ? 0x80 : 0) | index)]);+ }+ }));+ });+ }++ /// <summary>ImageGrid (23008-12, 6.6.2.3): rows, columns and the size the tiles are cropped to.</summary>+ private static byte[] GridDescription(HeifImage image)+ {+ var wide = image.Width > ushort.MaxValue || image.Height > ushort.MaxValue;+ var w = new BoxWriter();+ w.Raw([0, (byte)(wide ? 1 : 0), (byte)(image.Rows - 1), (byte)(image.Columns - 1)]);+ if (wide)+ {+ w.U32((uint)image.Width);+ w.U32((uint)image.Height);+ }+ else+ {+ w.U16(image.Width);+ w.U16(image.Height);+ }+ return w.ToArray();+ }++ /// <summary>The Exif item: the offset of the TIFF header ("II*\0" or "MM\0*") in the data, then the data.</summary>+ internal static byte[]? ExifPayload(byte[]? exif)+ {+ if (exif is null)+ return null;+ var tiff = -1;+ for (var i = 0; i + 3 < exif.Length && i < 16 && tiff < 0; i++)+ {+ if ((exif[i] == 'I' && exif[i + 1] == 'I' && exif[i + 2] == 42 && exif[i + 3] == 0) ||+ (exif[i] == 'M' && exif[i + 1] == 'M' && exif[i + 2] == 0 && exif[i + 3] == 42))+ tiff = i;+ }+ if (tiff < 0)+ return null;+ var payload = new byte[4 + exif.Length];+ BinaryPrimitives.WriteUInt32BigEndian(payload, (uint)tiff);+ exif.CopyTo(payload, 4);+ return payload;+ }++ private static byte[] Box(string type, Action<BoxWriter> body)+ {+ var content = new BoxWriter();+ body(content);+ var payload = content.ToArray();+ var box = new byte[8 + payload.Length];+ BinaryPrimitives.WriteUInt32BigEndian(box, (uint)box.Length);+ Encoding.ASCII.GetBytes(type, box.AsSpan(4));+ payload.CopyTo(box, 8);+ return box;+ }++ private static byte[] FullBox(string type, int version, int flags, Action<BoxWriter> body) =>+ Box(type, w =>+ {+ w.U32((uint)((version << 24) | flags));+ body(w);+ });++ /// <summary>Big-endian field writer.</summary>+ private sealed class BoxWriter+ {+ private readonly MemoryStream _stream = new();++ public void Raw(ReadOnlySpan<byte> bytes) => _stream.Write(bytes);++ public void Text(string fourCc) => _stream.Write(Encoding.ASCII.GetBytes(fourCc));++ public void Zeros(int count) => _stream.Write(new byte[count]);++ public void U16(int value)+ {+ Span<byte> bytes = stackalloc byte[2];+ BinaryPrimitives.WriteUInt16BigEndian(bytes, checked((ushort)value));+ _stream.Write(bytes);+ }++ public void U32(uint value)+ {+ Span<byte> bytes = stackalloc byte[4];+ BinaryPrimitives.WriteUInt32BigEndian(bytes, value);+ _stream.Write(bytes);+ }++ public byte[] ToArray() => _stream.ToArray();+ }+}diff --git a/src/Filee.Engines/Heic/HevcStream.cs b/src/Filee.Engines/Heic/HevcStream.csnew file mode 100644index 00000000..daf34bc4--- /dev/null+++ b/src/Filee.Engines/Heic/HevcStream.cs@@ -0,0 +1,205 @@+// Splits the raw HEVC stream FFmpeg writes (Annex B, NAL units behind start codes) into its parameter sets and one+// coded picture per tile, and builds the decoder configuration record (hvcC) that HEIF stores them in.++using System.Buffers.Binary;++namespace Filee.Engines.Heic;++/// <summary>An all-intra HEVC stream, split the way HEIF stores it.</summary>+/// <param name="Configuration">Payload of the <c>hvcC</c> box: profile, chroma format, bit depth and VPS/SPS/PPS.</param>+/// <param name="Pictures">Each coded picture as length-prefixed (4 bytes, big-endian) NAL units, ready for <c>mdat</c>.</param>+/// <param name="BitDepth">Luma bit depth (8 for Main, 10 for Main 10).</param>+internal sealed record HevcStream(byte[] Configuration, IReadOnlyList<byte[]> Pictures, int BitDepth)+{+ private const int IdrWithLeadingPictures = 19, IdrWithoutLeadingPictures = 20, Vps = 32, Sps = 33, Pps = 34;++ /// <summary>+ /// Splits an Annex B stream. Every picture must be an IDR picture; the parameter sets x265 repeats before each+ /// one must not change, because all tiles share one hvcC.+ /// </summary>+ /// <exception cref="InvalidDataException">The stream lacks parameter sets or pictures, changes them, holds a+ /// picture that is not an IDR picture, or uses sub-layers.</exception>+ public static HevcStream Parse(byte[] annexB)+ {+ byte[]? vps = null, sps = null, pps = null;+ var pictures = new List<List<byte[]>>();+ foreach (var unit in Units(annexB))+ {+ var type = (unit[0] >> 1) & 0x3F;+ switch (type)+ {+ case Vps: vps = Same(vps, unit); break;+ case Sps: sps = Same(sps, unit); break;+ case Pps: pps = Same(pps, unit); break;+ case < IdrWithLeadingPictures or > IdrWithoutLeadingPictures and < 32:+ throw new InvalidDataException($"The HEVC stream holds a picture that is not an IDR picture (NAL unit type {type}).");+ case < 32:+ // Video coding layer: a slice with first_slice_segment_in_pic_flag starts the next picture.+ if ((unit[2] & 0x80) != 0 || pictures.Count == 0)+ pictures.Add([]);+ pictures[^1].Add(unit);+ break;+ // SEI, access unit delimiters, end of stream: HEIF has no use for them.+ }+ }+ if (vps is null || sps is null || pps is null || pictures.Count == 0)+ throw new InvalidDataException("The HEVC stream has no parameter sets or no picture.");++ var (config, depth) = BuildConfiguration(vps, sps, pps);+ return new HevcStream(config, pictures.Select(LengthPrefixed).ToList(), depth);+ }++ private static byte[] Same(byte[]? known, byte[] unit) =>+ known is null || known.AsSpan().SequenceEqual(unit)+ ? unit+ : throw new InvalidDataException("The HEVC stream changes its parameter sets between pictures.");++ /// <summary>NAL units of an Annex B stream, without their start codes.</summary>+ internal static List<byte[]> Units(byte[] data)+ {+ var starts = new List<int>();+ for (var i = 0; i + 2 < data.Length; i++)+ {+ if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1)+ {+ starts.Add(i + 3);+ i += 2;+ }+ }+ var units = new List<byte[]>();+ for (var k = 0; k < starts.Count; k++)+ {+ var end = k + 1 < starts.Count ? starts[k + 1] - 3 : data.Length;+ // A four-byte start code leaves one zero byte before the next unit; NAL units never end in zero bytes.+ while (end > starts[k] && data[end - 1] == 0)+ end--;+ if (end - starts[k] >= 3)+ units.Add(data[starts[k]..end]);+ }+ return units;+ }++ private static byte[] LengthPrefixed(List<byte[]> units)+ {+ var result = new byte[units.Sum(u => 4 + u.Length)];+ var at = 0;+ foreach (var unit in units)+ {+ BinaryPrimitives.WriteUInt32BigEndian(result.AsSpan(at), (uint)unit.Length);+ unit.CopyTo(result, at + 4);+ at += 4 + unit.Length;+ }+ return result;+ }++ /// <summary>The HEVCDecoderConfigurationRecord (ISO/IEC 14496-15, 8.3.3) with one VPS, SPS and PPS.</summary>+ private static (byte[] Configuration, int BitDepth) BuildConfiguration(byte[] vps, byte[] sps, byte[] pps)+ {+ var info = SequenceInfo.Read(sps);+ using var output = new MemoryStream();+ output.WriteByte(1); // configurationVersion+ output.Write(info.ProfileTierLevel);+ Write16(output, 0xF000); // reserved + min_spatial_segmentation_idc 0+ output.WriteByte(0xFC); // reserved + parallelismType 0 (unknown)+ output.WriteByte((byte)(0xFC | info.ChromaFormat));+ output.WriteByte((byte)(0xF8 | (info.LumaBitDepth - 8)));+ output.WriteByte((byte)(0xF8 | (info.ChromaBitDepth - 8)));+ Write16(output, 0); // avgFrameRate unknown+ // constantFrameRate 0, numTemporalLayers, temporalIdNested, lengthSizeMinusOne 3 (4-byte lengths)+ output.WriteByte((byte)((info.TemporalLayers << 3) | (info.TemporalIdNested ? 0x04 : 0) | 0x03));+ output.WriteByte(3); // numOfArrays+ foreach (var (type, unit) in new[] { (Vps, vps), (Sps, sps), (Pps, pps) })+ {+ output.WriteByte((byte)(0x80 | type)); // array_completeness: these are all the sets there are+ Write16(output, 1);+ Write16(output, unit.Length);+ output.Write(unit);+ }+ return (output.ToArray(), info.LumaBitDepth);+ }++ private static void Write16(Stream stream, int value)+ {+ stream.WriteByte((byte)(value >> 8));+ stream.WriteByte((byte)value);+ }++ /// <summary>The fields of a sequence parameter set (H.265, 7.3.2.2) that hvcC repeats.</summary>+ private sealed record SequenceInfo(byte[] ProfileTierLevel, int ChromaFormat, int LumaBitDepth, int ChromaBitDepth,+ int TemporalLayers, bool TemporalIdNested)+ {+ public static SequenceInfo Read(byte[] sps)+ {+ var bits = new BitReader(Unescape(sps.AsSpan(2))); // after the two-byte NAL unit header+ bits.Read(4); // sps_video_parameter_set_id+ var subLayers = bits.Read(3);+ var nested = bits.Read(1) == 1;+ if (subLayers != 0)+ throw new InvalidDataException("HEVC streams with temporal sub-layers are not supported.");+ // general_profile_space … general_level_idc: 12 bytes, copied as they are.+ var ptl = new byte[12];+ for (var i = 0; i < ptl.Length; i++)+ ptl[i] = (byte)bits.Read(8);+ bits.ReadExpGolomb(); // sps_seq_parameter_set_id+ var chroma = bits.ReadExpGolomb();+ if (chroma == 3)+ bits.Read(1); // separate_colour_plane_flag+ bits.ReadExpGolomb(); // pic_width_in_luma_samples+ bits.ReadExpGolomb(); // pic_height_in_luma_samples+ if (bits.Read(1) == 1) // conformance_window_flag+ {+ for (var i = 0; i < 4; i++)+ bits.ReadExpGolomb();+ }+ var luma = bits.ReadExpGolomb() + 8;+ var chromaDepth = bits.ReadExpGolomb() + 8;+ return new SequenceInfo(ptl, chroma, luma, chromaDepth, subLayers + 1, nested);+ }++ /// <summary>Removes emulation prevention bytes (00 00 03 → 00 00).</summary>+ private static byte[] Unescape(ReadOnlySpan<byte> data)+ {+ var result = new List<byte>(data.Length);+ var zeros = 0;+ foreach (var b in data)+ {+ if (zeros >= 2 && b == 3)+ {+ zeros = 0;+ continue;+ }+ result.Add(b);+ zeros = b == 0 ? zeros + 1 : 0;+ }+ return [.. result];+ }+ }++ private sealed class BitReader(byte[] data)+ {+ private int _position;++ public int Read(int count)+ {+ var value = 0;+ for (var i = 0; i < count; i++, _position++)+ {+ if (_position >> 3 >= data.Length)+ throw new InvalidDataException("The HEVC sequence parameter set is truncated.");+ value = (value << 1) | ((data[_position >> 3] >> (7 - (_position & 7))) & 1);+ }+ return value;+ }++ public int ReadExpGolomb()+ {+ var zeros = 0;+ while (Read(1) == 0)+ {+ if (++zeros > 30)+ throw new InvalidDataException("The HEVC sequence parameter set is malformed.");+ }+ return (1 << zeros) - 1 + Read(zeros);+ }+ }+}diff --git a/src/Filee.Engines/Icns/IcnsConverter.cs b/src/Filee.Engines/Icns/IcnsConverter.csindex 462254d2..bd6b6bee 100644--- a/src/Filee.Engines/Icns/IcnsConverter.cs+++ b/src/Filee.Engines/Icns/IcnsConverter.cs@@ -18,7 +18,7 @@ public sealed class IcnsConverter : IConverterpublic IReadOnlyList<ConversionEdge> Edges { get; } =[.. ImageEncoder.Sources.Select(source => new ConversionEdge(source, "icns")),- .. ImageEncoder.Writable.Select(target => new ConversionEdge("icns", target)),+ .. ImageEncoder.Writable.Select(target => ImageEncoder.Edge("icns", target)),];public EngineStatus GetStatus() => EngineStatus.Available(version: EngineVersions.BuiltIn);diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.csindex 5c2d3167..7142341c 100644--- a/src/Filee.Engines/Magick/ImageEncoder.cs+++ b/src/Filee.Engines/Magick/ImageEncoder.cs@@ -24,8 +24,8 @@ internal static class ImageEncoderpublic static readonly string[] Metafiles = ["emf", "wmf"];/// <summary>- /// Image formats ImageMagick can write. HEIC is missing on purpose: the bundled build has no HEVC encoder- /// (patent licensing), so we offer AVIF instead.+ /// Image formats ImageMagick can write. HEIC is missing: the bundled build has no HEVC encoder (patent+ /// licensing), so HEIC is written with the optional FFmpeg download instead (Heic/HeicWriter)./// </summary>public static readonly string[] Writable =[@@ -42,12 +42,23 @@ internal static class ImageEncoder/// </summary>private static readonly HashSet<string> Animated = ["gif", "webp"];+ /// <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.+ /// </summary>+ public static ConversionEdge Edge(string source, string target) =>+ new(source, target, target == "gif" && !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) =>Animated.Contains(sourceFormat) && Animated.Contains(targetFormat);- /// <summary>Formats without an alpha channel: transparent pixels are flattened onto the background colour.</summary>- private static readonly HashSet<string> NoAlpha = ["jpg", "ppm"];+ /// <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.+ /// </summary>+ private static readonly HashSet<string> NoAlpha = ["jpg", "ppm", "heic"];/// <summary>Every format ImageMagick reads as input: the raster formats plus, on Windows, the metafiles.</summary>public static IEnumerable<string> Sources =>diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.csindex e3830ac0..62714785 100644--- a/src/Filee.Engines/Magick/MagickImageConverter.cs+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs@@ -19,7 +19,7 @@ public sealed class MagickImageConverter : IConverter, ITiffMergerpublic IReadOnlyList<ConversionEdge> Edges { get; } =(from source in ImageEncoder.Sourcesfrom target in ImageEncoder.Writable- select new ConversionEdge(source, target)).ToList();+ select ImageEncoder.Edge(source, target)).ToList();public EngineStatus GetStatus() =>EngineStatus.Available(MagickNET.ImageMagickVersion,diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.csindex c8cfa980..e095bc51 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 → video.+// GIF 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;@@ -8,7 +8,9 @@ using System.Diagnostics;using System.Text.RegularExpressions;using Filee.Core.Conversion;using Filee.Core.Formats;+using Filee.Engines.Heic;using Filee.Engines.Infrastructure;+using Filee.Engines.Magick;namespace Filee.Engines.Media;@@ -30,11 +32,15 @@ public sealed partial class FfmpegConverter : IConverter/// <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 → MP4, WEBM, MOV. Only formats the pinned build can write are targets (see MediaEncoding).+ /// GIF 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./// </remarks>private static List<ConversionEdge> BuildEdges(){@@ -46,7 +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)),.. from source in audios from target in MediaEncoding.AudioTargets.Keys select new ConversionEdge(source, target),- .. MediaEncoding.GifToVideoTargets.Select(target => new ConversionEdge("gif", target)),+ .. MediaEncoding.PictureToVideoTargets.Select(target => new ConversionEdge("gif", target)),+ .. 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")),];}@@ -69,6 +78,8 @@ public sealed partial class FfmpegConverter : IConverterpublic async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken){var (ffmpeg, ffprobe) = _tools ?? Locate() ?? throw new InvalidOperationException("FFmpeg was not found.");+ if (step.To == "heic")+ return await HeicWriter.ConvertAsync(ffmpeg, step, progress, cancellationToken);var input = Path.GetFullPath(step.InputPath);var info = await MediaInfo.ProbeAsync(ffprobe, input, cancellationToken);progress?.Report(0.02);@@ -77,19 +88,25 @@ public sealed partial class FfmpegConverter : IConverterif (output is null)return [];+ // A PNG is a still picture (from the image engines), shown for a few seconds.+ var still = step.From == "png";+// Album art for targets FFmpeg can't put a picture stream into (Ogg, Matroska): prepared on the side.- var cover = info.CoverStreamIndex is { } coverStream+ var cover = !still && info.CoverStreamIndex is { } coverStream? await CoverArt.PrepareAsync(ffmpeg, input, coverStream, step.To, step.WorkDirectory, cancellationToken): null;// Throws for a missing stream before anything is written (an existing file of that name stays untouched).- var passes = MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory, cover);+ var passes = still+ ? MediaEncoding.PlanStill(input, output, step.To, step.Preset.Media, info)+ : MediaEncoding.Plan(input, output, step.To, step.Preset.Media, info, step.WorkDirectory, cover);+ var duration = still ? MediaEncoding.StillDuration : info.Duration;try{var done = 0.0;foreach (var pass in passes){- await RunPassAsync(ffmpeg, pass, info.Duration, progress, done, cancellationToken);+ await RunPassAsync(ffmpeg, pass, duration, progress, done, cancellationToken);done += pass.Weight;}if (!File.Exists(output) || new FileInfo(output).Length == 0)diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.csindex 393819f8..cc879a5d 100644--- a/src/Filee.Engines/Media/MediaEncoding.cs+++ b/src/Filee.Engines/Media/MediaEncoding.cs@@ -80,8 +80,20 @@ internal static class MediaEncoding["voc"] = new("voc", null, "pcm_s16le"),};- /// <summary>Formats an animated GIF can be turned into.</summary>- public static IReadOnlyList<string> GifToVideoTargets { get; } = ["mp4", "webm", "mov"];+ /// <summary>Formats an animated GIF or a still picture (PNG) can be turned into.</summary>+ public static IReadOnlyList<string> PictureToVideoTargets { get; } = ["mp4", "webm", "mov"];++ /// <summary>How long a video made of one still picture shows it.</summary>+ public static TimeSpan StillDuration { get; } = TimeSpan.FromSeconds(5);++ /// <summary>+ /// The largest picture H.264 and VP9 at level 6.2 (their highest) allow: 8192 × 4352, about 35.6 megapixels.+ /// Larger photos (48 MP phone cameras) are scaled down to it, or many players refuse the video.+ /// </summary>+ private const long MaxVideoPixels = 8192L * 4352;++ /// <summary>The longest side VP9 level 6.2 allows (H.264 allows 16880), for panoramas within the pixel limit.</summary>+ private const int MaxVideoSide = 16384;/// <summary>Audio targets that can carry a cover picture (album art) copied from the source.</summary>private static readonly HashSet<string> CoverTargets = ["mp3", "m4a", "m4b", "flac"];@@ -481,6 +493,55 @@ internal static class MediaEncoding];}+ // ───────────────────────── Still picture → video ─────────────────────────++ /// <summary>+ /// A video that shows the PNG <paramref name="input"/> for <see cref="StillDuration"/>. The image engines write+ /// that PNG at full size and colour, so pictures never pass through a 256-colour GIF on their way to video.+ /// </summary>+ /// <remarks>+ /// The PNG's ICC profile or colour chunks give the primaries and transfer (a Display P3 photo stays P3 in the+ /// video); RGB becomes BT.709 YUV in TV range, tagged as such. Transparent areas turn black, like the bars around+ /// a video. 30 frames per second play everywhere; identical frames cost x264 (tuned for stills) and VP9 almost+ /// nothing, so the quality is one step above the preset's (Balanced encodes like High): the file is about the+ /// size of one picture either way.+ /// </remarks>+ public static IReadOnlyList<FfmpegPass> PlanStill(string input, string output, string target, MediaOptions options, MediaInfo info)+ {+ var picture = info.Video ?? throw new InvalidOperationException("The file has no picture.");+ if (!PictureToVideoTargets.Contains(target))+ throw new NotSupportedException($"FFmpeg does not turn pictures into '{target}'.");+ var spec = VideoTargets[target];+ var quality = options.Quality == MediaQuality.Small ? MediaQuality.Balanced : MediaQuality.High;++ List<string> args =+ [+ .. Common, "-flags2", "+icc_profiles", "-loop", "1", "-framerate", "30", "-i", input, "-map", "0:V:0",+ "-t", StillDuration.TotalSeconds.ToString(CultureInfo.InvariantCulture),+ "-vf", $"premultiply=inplace=1,{StillScale(picture, options.MaxHeight)}:out_color_matrix=bt709:out_range=tv,format=yuv420p",+ .. VideoCodecArguments(target, spec.VideoCodec!, quality, picture, pal: false),+ ];+ if (spec.VideoCodec == "libx264")+ args.AddRange(["-tune", "stillimage"]);+ args.AddRange(["-colorspace", "bt709", "-an", .. ContainerArguments(target), "-f", spec.Muxer, "-progress", "pipe:1", output]);+ return [new FfmpegPass(args, 1)];+ }++ /// <summary>+ /// The picture's own size, made even (4:2:0) and scaled down only to <paramref name="maxHeight"/> or to what video+ /// players decode (<see cref="MaxVideoPixels"/>, <see cref="MaxVideoSide"/>), keeping the aspect ratio.+ /// </summary>+ internal static string StillScale(VideoStreamInfo picture, int maxHeight)+ {+ double width = picture.Width, height = picture.Height;+ if (width <= 0 || height <= 0)+ return ScaleFilter(maxHeight) + ":flags=lanczos";+ var factor = Math.Min(1, Math.Min(Math.Sqrt(MaxVideoPixels / (width * height)), MaxVideoSide / Math.Max(width, height)));+ if (maxHeight > 0)+ factor = Math.Min(factor, Math.Max(16, maxHeight) / height);+ return $"scale={EvenDown(width * factor)}:{EvenDown(height * factor)}:flags=lanczos";+ }+// ───────────────────────── Helpers ─────────────────────────private static T Choose<T>(MediaQuality quality, T high, T balanced, T small) => quality switch@@ -493,4 +554,7 @@ internal static class MediaEncodingprivate static string Text(int value) => value.ToString(CultureInfo.InvariantCulture);private static int Even(double value) => Math.Max(2, (int)Math.Round(value / 2) * 2);++ /// <summary>The even number at or below <paramref name="value"/> (a tiny rounding margin keeps 1080.0000001 at 1080).</summary>+ private static int EvenDown(double value) => Math.Max(2, (int)Math.Floor(value / 2 + 1e-6) * 2);}diff --git a/src/Filee.Engines/Vector/VectorConverter.cs b/src/Filee.Engines/Vector/VectorConverter.csindex 78804b41..5d30bd86 100644--- a/src/Filee.Engines/Vector/VectorConverter.cs+++ b/src/Filee.Engines/Vector/VectorConverter.cs@@ -23,7 +23,7 @@ public sealed class VectorConverter : IConverternew("svgz", "pdf"),new("svg", "svgz"),new("svgz", "svg"),- .. ImageEncoder.Writable.SelectMany(target => new ConversionEdge[] { new("svg", target), new("svgz", target) }),+ .. ImageEncoder.Writable.SelectMany(target => new[] { ImageEncoder.Edge("svg", target), ImageEncoder.Edge("svgz", target) }),// Illustrator files are PDF inside (or PostScript, see ConvertIllustratorAsync).new("ai", "pdf"),];diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 6ee1afee..fc091c1a 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -174,11 +174,11 @@ public class UserDataStoreTests}[Fact]- public void Version_8_libraries_get_the_long_image_preset_after_jpg()+ public void Version_8_libraries_get_the_long_image_preset_after_jpg_and_a_heic_preset(){- // As written by 1.9.0: no "Long image" preset, and the PDF donut without it.+ // As written by 1.9.0: no "Long image" or HEIC preset, and the PDF donut without the long image.var presets = BuiltInData.CreatePresets();- presets.RemoveAll(p => p.Id == "pdf-long-image");+ presets.RemoveAll(p => p.Id is "pdf-long-image" or "to-heic");var profiles = BuiltInData.CreateProfiles();var pdf = profiles.Single(p => p.Id == "pdf");pdf.PresetIds.Remove("pdf-long-image");@@ -188,6 +188,8 @@ public class UserDataStoreTestsvar longImage = presets.Single(p => p.Id == "pdf-long-image");Assert.True(longImage.Pdf.CombinePages);Assert.Equal(pdf.PresetIds.IndexOf("to-jpg") + 1, pdf.PresetIds.IndexOf("pdf-long-image"));+ Assert.Equal("heic", presets.Single(p => p.Id == "to-heic").TargetFormat);+ Assert.DoesNotContain(profiles, p => p.PresetIds.Contains("to-heic"));Assert.False(SettingsMigrations.ApplyToLibrary(8, presets, profiles)); // once only}diff --git a/tests/Filee.Engines.Tests/HeicTests.cs b/tests/Filee.Engines.Tests/HeicTests.csnew file mode 100644index 00000000..59fdc063--- /dev/null+++ b/tests/Filee.Engines.Tests/HeicTests.cs@@ -0,0 +1,197 @@+// Images → HEIC with FFmpeg's x265 and Filee's HEIF writer. Every file written is read back with ImageMagick's+// libheif, an independent decoder. The real conversions run only when Filee's FFmpeg is installed+// (`pwsh build/fetch-engines.ps1 -Only ffmpeg`).++using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Heic;+using Filee.Engines.Media;+using ImageMagick;++namespace Filee.Engines.Tests;++[Collection(nameof(FfmpegCollection))]+public class HeicTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static readonly bool FfmpegInstalled = FfmpegConverter.Locate() is not null;++ private static void SkipUnlessInstalled() =>+ Assert.SkipUnless(FfmpegInstalled, "FFmpeg is not installed (pwsh build/fetch-engines.ps1 -Only ffmpeg)");++ // ───────────────────────── Without FFmpeg ─────────────────────────++ [Theory]+ [InlineData("jpg")]+ [InlineData("png")]+ [InlineData("heic")] // re-encode, e.g. smaller+ [InlineData("raw")]+ public void Images_become_heic_in_one_ffmpeg_step(string from)+ {+ var route = fx.Catalog.CreatePlanner(["ffmpeg"]).Plan(from, "heic");+ Assert.NotNull(route);+ Assert.Equal(("ffmpeg", from, "heic"), Assert.Single(route.Steps) is var s ? (s.Converter.Id, s.From, s.To) : default);+ }++ [Fact]+ public void Pdf_pages_become_heic_through_png()+ {+ var route = fx.Catalog.CreatePlanner(["ffmpeg"]).Plan("pdf", "heic");+ Assert.NotNull(route);+ Assert.Equal([("pdfium", "pdf", "png"), ("ffmpeg", "png", "heic")], route.Steps.Select(s => (s.Converter.Id, s.From, s.To)));+ }++ [Theory]+ [InlineData(512, 512, 1, 1, 512, 512)]+ [InlineData(301, 201, 1, 1, 302, 202)] // odd sides: an even coded picture, cropped by a 1 × 1 grid+ [InlineData(4032, 3024, 8, 6, 512, 512)] // a 12 MP phone photo+ [InlineData(513, 100, 2, 1, 512, 512)]+ public void Pictures_are_laid_out_like_camera_photos(int width, int height, int columns, int rows, int tileWidth, int tileHeight) =>+ Assert.Equal((columns, rows, tileWidth, tileHeight), HeicWriter.Layout(width, height));++ [Fact]+ public void FFmpeg_pads_with_edge_pixels_and_cuts_tiles()+ {+ var args = HeicWriter.Arguments("in.png", "out.hevc", 1000, 700, 80);+ var filters = args[args.IndexOf("-vf") + 1];+ Assert.Equal("pad=1024:1024:0:0,fillborders=right=24:bottom=324:mode=smear,scale=out_color_matrix=bt601:out_range=pc,format=yuv420p,untile=2x2", filters);+ Assert.Equal("libx265", args[args.IndexOf("-c:v") + 1]);+ Assert.Equal("18", args[args.IndexOf("-crf") + 1]);+ // Every tile an IDR picture of the Main profile (keyint=1 would make x265 signal "Main Intra").+ Assert.Equal(["-force_key_frames", "expr:1", "-forced-idr", "1"], args.SkipWhile(a => a != "-force_key_frames").Take(4));+ Assert.Contains("open-gop=0", args[args.IndexOf("-x265-params") + 1]);+ Assert.DoesNotContain("keyint", args[args.IndexOf("-x265-params") + 1]);++ var small = HeicWriter.Arguments("in.png", "out.hevc", 400, 300, 80);+ Assert.Equal("scale=out_color_matrix=bt601:out_range=pc,format=yuv420p", small[small.IndexOf("-vf") + 1]);+ Assert.Equal((14, 30, 10), (HeicWriter.Crf(90), HeicWriter.Crf(50), HeicWriter.Crf(100)));+ }++ [Fact]+ public void Annex_b_streams_are_split_into_nal_units()+ {+ byte[] stream = [0, 0, 0, 1, 0x40, 0x01, 0x0C, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 0, 1, 0x26, 0x01, 0xAF, 0x80];+ var units = HevcStream.Units(stream);+ Assert.Equal([[0x40, 0x01, 0x0C], [0x42, 0x01, 0x01], [0x26, 0x01, 0xAF, 0x80]], units);+ Assert.Throws<InvalidDataException>(() => HevcStream.Parse(stream[..10]));+ // 0x26 is a VCL unit of type 19 (IDR); a type 1 (trailing) picture cannot stand on its own as a tile.+ Assert.Contains("not an IDR", Assert.Throws<InvalidDataException>(() => HevcStream.Parse([0, 0, 1, 0x02, 0x01, 0x80])).Message);+ }++ [Fact]+ public async Task Tiles_are_main_profile_idr_pictures()+ {+ SkipUnlessInstalled();+ var folder = fx.NewFolder();+ var png = EngineFixture.MakeImage(folder, "tiles.png", MagickFormat.Png, 1100, 600);+ var stream = Path.Combine(folder, "tiles.hevc");+ var result = await Infrastructure.ProcessRunner.RunAsync(FfmpegConverter.Locate()!.Value.Ffmpeg,+ HeicWriter.Arguments(png, stream, 1100, 600, 80), TimeSpan.FromMinutes(1), CancellationToken.None);+ Assert.True(result.ExitCode == 0, result.StandardError);++ var hevc = HevcStream.Parse(await File.ReadAllBytesAsync(stream, TestContext.Current.CancellationToken)); // all IDR, same parameter sets+ Assert.Equal(6, hevc.Pictures.Count); // 3 × 2 tiles+ Assert.Equal(8, hevc.BitDepth);+ Assert.Equal(1, hevc.Configuration[1] & 0x1F); // general_profile_idc 1: Main+ }++ [Fact]+ public void Exif_items_point_at_the_tiff_header()+ {+ byte[] withPrefix = [.. "Exif\0\0"u8, .. "MM\0*"u8, 0, 0, 0, 8];+ var payload = HeifFile.ExifPayload(withPrefix)!;+ Assert.Equal([0, 0, 0, 6], payload[..4]);+ Assert.Equal(withPrefix, payload[4..]);+ Assert.Equal([0, 0, 0, 0], HeifFile.ExifPayload([.. "II*\0"u8, 8, 0, 0, 0])![..4]);+ Assert.Null(HeifFile.ExifPayload([1, 2, 3, 4, 5]));+ }++ // ───────────────────────── Real conversions ─────────────────────────++ private async Task<string> ConvertAsync(string input, ImageOptions? image = null)+ {+ var preset = new Preset { TargetFormat = "heic", Image = image ?? new ImageOptions { Quality = 80 } };+ var job = await fx.ConvertAsync([input], preset);+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));+ var output = Assert.Single(job.Outputs);+ Assert.Equal(".heic", Path.GetExtension(output));+ return output;+ }++ [Fact]+ public async Task A_small_odd_sized_png_keeps_its_size_and_colours()+ {+ SkipUnlessInstalled();+ // 301 × 201 gradient #7F77DD → #1D9E75 with a transparent 40 × 40 corner.+ var png = EngineFixture.MakeImage(fx.NewFolder(), "small.png", MagickFormat.Png, 301, 201);+ using var heic = new MagickImage(await ConvertAsync(png));++ Assert.Equal((301u, 201u), (heic.Width, heic.Height));+ Assert.False(heic.HasAlpha);+ using var pixels = heic.GetPixels();+ var middle = pixels.GetPixel(150, 100).ToColor()!;+ Assert.InRange(middle.R, 0x4E - 6, 0x4E + 6);+ Assert.InRange(middle.G, 0x8A - 6, 0x8A + 6);+ Assert.InRange(middle.B, 0xA9 - 6, 0xA9 + 6);+ var corner = pixels.GetPixel(10, 10).ToColor()!;+ Assert.True(corner.R > 245 && corner.G > 245 && corner.B > 245, "transparency is flattened onto white");+ }++ [Fact]+ public async Task A_rotated_photo_is_stored_upright_in_tiles_with_its_profile_and_exif()+ {+ SkipUnlessInstalled();+ var folder = fx.NewFolder();+ var jpg = Path.Combine(folder, "phone.jpg");+ using (var photo = new MagickImage("gradient:#FF8800-#0044AA", 1300, 900))+ {+ // Stored sideways, shown upright through Exif orientation 6 (turn 90° clockwise), like a phone photo.+ var exif = new ExifProfile();+ exif.SetValue(ExifTag.Orientation, (ushort)6);+ exif.SetValue(ExifTag.Make, "Filee test");+ photo.SetProfile(exif);+ photo.Orientation = OrientationType.RightTop; // ImageMagick writes this into the Exif orientation+ photo.SetProfile(ColorProfiles.AdobeRGB1998);+ photo.Quality = 95;+ photo.Write(jpg, MagickFormat.Jpeg);+ }++ var output = await ConvertAsync(jpg);+ using var heic = new MagickImage(output);+ Assert.Equal((900u, 1300u), (heic.Width, heic.Height)); // upright: 2 × 3 tiles of 512, cropped+ Assert.Equal(ColorProfiles.AdobeRGB1998.ToByteArray(), heic.GetColorProfile()?.ToByteArray());+ var exifBack = heic.GetExifProfile();+ Assert.NotNull(exifBack);+ Assert.Equal("Filee test", exifBack.GetValue(ExifTag.Make)?.Value);+ Assert.Equal((ushort)1, exifBack.GetValue(ExifTag.Orientation)?.Value);++ // The gradient runs from top to bottom in the stored pixels, so from right to left once upright. Tiles in+ // the wrong place would break it up.+ using var reference = new MagickImage(jpg);+ reference.AutoOrient();+ reference.Alpha(AlphaOption.Off);+ heic.Alpha(AlphaOption.Off);+ var rmse = heic.Compare(reference, ErrorMetric.RootMeanSquared);+ Assert.True(rmse < 0.01, $"RMSE {rmse}");+ }++ [Fact]+ public async Task Quality_and_metadata_options_apply()+ {+ SkipUnlessInstalled();+ var folder = fx.NewFolder();+ var source = Path.Combine(folder, "detail.png");+ using (var noise = new MagickImage("plasma:", 800, 600))+ {+ noise.SetProfile(ColorProfiles.AdobeRGB1998);+ noise.Write(source, MagickFormat.Png);+ }++ var high = new FileInfo(await ConvertAsync(source, new ImageOptions { Quality = 90 })).Length;+ File.Move(Path.Combine(folder, "detail.heic"), Path.Combine(folder, "high.heic"));+ var stripped = await ConvertAsync(source, new ImageOptions { Quality = 40, KeepMetadata = false, KeepColorProfile = false });+ Assert.True(new FileInfo(stripped).Length < high / 2, $"{new FileInfo(stripped).Length} vs {high}");+ using var image = new MagickImage(stripped);+ Assert.Null(image.GetColorProfile()); // declared sRGB (nclx) instead+ Assert.Null(image.GetExifProfile());+ }+}diff --git a/tests/Filee.Engines.Tests/MediaTests.cs b/tests/Filee.Engines.Tests/MediaTests.csindex e3827080..06fa6f0b 100644--- a/tests/Filee.Engines.Tests/MediaTests.cs+++ b/tests/Filee.Engines.Tests/MediaTests.cs@@ -49,6 +49,7 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>[InlineData("amr", "mp3")][InlineData("gif", "mp4")][InlineData("gif", "webm")]+ [InlineData("png", "mov")][InlineData("rm", "mp4")][InlineData("dss", "mp3")]public void Media_conversions_take_one_ffmpeg_step(string from, string to)@@ -70,6 +71,29 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.Equal([("ffmpeg", from, "png"), (imageEngine, "png", to)], route.Steps.Select(s => (s.Converter.Id, s.From, s.To)));}+ [Theory]+ [InlineData("heic", "mov", "magick")]+ [InlineData("jpg", "mp4", "magick")]+ [InlineData("avif", "webm", "magick")]+ [InlineData("svg", "mov", "vector")]+ 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);+ Assert.NotNull(route);+ Assert.Equal([(imageEngine, from, "png"), ("ffmpeg", "png", to)], route.Steps.Select(s => (s.Converter.Id, s.From, s.To)));+ }++ [Theory]+ [InlineData("pdf", "mp4", "pdfium")] // a slideshow of the pages+ [InlineData("webp", "mov", "magick")] // an animated WebP keeps moving+ [InlineData("tiff", "webm", "magick")]+ public void Animations_and_pages_still_reach_video_through_gif(string from, string to, string imageEngine)+ {+ var route = Planner().Plan(from, to);+ Assert.NotNull(route);+ Assert.Equal([(imageEngine, from, "gif"), ("ffmpeg", "gif", to)], route.Steps.Select(s => (s.Converter.Id, s.From, s.To)));+ }+[Fact]public void Every_writable_video_and_audio_format_is_a_target(){@@ -206,6 +230,36 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.Contains("paletteuse", After(second, "-filter_complex"));}+ [Fact]+ public void A_still_picture_is_shown_for_five_seconds_at_full_size()+ {+ var photo = new MediaInfo(null, new VideoStreamInfo(4033, 3025, 1, 0, 25), null, null);+ var mov = MediaEncoding.PlanStill("in.png", "out.mov", "mov", new MediaOptions(), photo).Single().Arguments;+ Assert.Equal(["-loop", "1", "-framerate", "30", "-i", "in.png"], mov.SkipWhile(a => a != "-loop").Take(6));+ Assert.Equal("+icc_profiles", After(mov, "-flags2"));+ Assert.Equal("5", After(mov, "-t"));+ Assert.Equal("premultiply=inplace=1,scale=4032:3024:flags=lanczos:out_color_matrix=bt709:out_range=tv,format=yuv420p", After(mov, "-vf"));+ Assert.Equal(("libx264", "18", "stillimage", "bt709"), (After(mov, "-c:v"), After(mov, "-crf"), After(mov, "-tune"), After(mov, "-colorspace")));+ Assert.Contains("-an", mov);+ Assert.Equal("mov", After(mov, "-f"));++ var webm = MediaEncoding.PlanStill("in.png", "out.webm", "webm", new MediaOptions { Quality = MediaQuality.Small }, photo).Single().Arguments;+ Assert.Equal(("libvpx-vp9", "32"), (After(webm, "-c:v"), After(webm, "-crf"))); // one step up: Small → Balanced+ Assert.DoesNotContain("-tune", webm);++ Assert.Throws<NotSupportedException>(() => MediaEncoding.PlanStill("in.png", "out.avi", "avi", new MediaOptions(), photo));+ }++ [Theory]+ [InlineData(4032, 3024, 0, "scale=4032:3024")]+ [InlineData(1001, 751, 0, "scale=1000:750")] // even sides for 4:2:0+ [InlineData(4032, 3024, 720, "scale=960:720")]+ [InlineData(8064, 6048, 0, "scale=6894:5170")] // 48 MP: down to the 35.6 MP H.264/VP9 level 6.2 limit+ [InlineData(30000, 2000, 0, "scale=16384:1092")] // panorama: at most 16384 wide+ [InlineData(0, 0, 0, "scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'")]+ public void Still_pictures_are_scaled_down_only_to_what_players_decode(int width, int height, int maxHeight, string expected) =>+ Assert.Equal(expected + ":flags=lanczos", MediaEncoding.StillScale(new VideoStreamInfo(width, height, 1, 0, 25), maxHeight));+[Fact]public void Missing_streams_are_reported_clearly(){@@ -413,6 +467,48 @@ public class MediaTests(EngineFixture fx) : IClassFixture<EngineFixture>Assert.InRange(mp4.Duration, 1.5, 2.5);}+ [Fact]+ public async Task A_photo_becomes_a_still_video_in_full_colour()+ {+ SkipUnlessInstalled();+ var folder = fx.NewFolder();+ // Odd-sized gradient with a transparent corner, as a JPG (→ PNG → MOV) and a PNG (→ WEBM).+ var png = EngineFixture.MakeImage(folder, "photo.png", ImageMagick.MagickFormat.Png, 1001, 751);+ var jpg = Path.Combine(folder, "photo.jpg");+ using (var source = new ImageMagick.MagickImage(png))+ source.Write(jpg, ImageMagick.MagickFormat.Jpeg);++ foreach (var (input, target, codec) in new[] { (jpg, "mov", "h264"), (png, "webm", "vp9") })+ {+ var video = await ConvertAsync(input, target);+ var probed = await ProbeAsync(video);+ Assert.Equal(codec, probed.Video?.Codec);+ Assert.Equal((1000, 750), (probed.Video!.Width, probed.Video.Height));+ Assert.InRange(probed.Duration, 4.9, 5.1);+ Assert.Null(probed.Audio);++ var frame = Path.Combine(folder, $"frame-{target}.png");+ await RunAsync(Tools!.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-i", video, "-frames:v", "1", frame]);+ using var picture = new ImageMagick.MagickImage(frame);+ // Colours stay put (BT.709 both ways): the middle is halfway between #7F77DD and #1D9E75.+ var middle = picture.GetPixels().GetPixel(500, 375).ToColor()!;+ Assert.InRange(middle.R, 0x4E - 6, 0x4E + 6);+ Assert.InRange(middle.G, 0x8A - 6, 0x8A + 6);+ Assert.InRange(middle.B, 0xA9 - 6, 0xA9 + 6);+ if (target == "webm")+ Assert.True(picture.GetPixels().GetPixel(10, 10).ToColor()!.R < 16, "the transparent corner turns black");+ }++ // Every colour of a 64-level colour cube: a GIF on the way would leave at most 256 of them.+ var cube = Path.Combine(folder, "cube.png");+ using (var colours = new ImageMagick.MagickImage("hald:8"))+ colours.Write(cube);+ var cubeFrame = Path.Combine(folder, "frame-cube.png");+ await RunAsync(Tools!.Value.Ffmpeg, ["-hide_banner", "-nostdin", "-v", "error", "-y", "-i", await ConvertAsync(cube, "mp4"), "-frames:v", "1", cubeFrame]);+ using var cubePicture = new ImageMagick.MagickImage(cubeFrame);+ Assert.True(cubePicture.TotalColors > 10_000, $"{cubePicture.TotalColors} colours");+ }+[Fact]public async Task Video_gives_a_still_frame_for_images(){