From fa47f5b81eed28502aa5952da47a2279eeae7686 Mon Sep 17 00:00:00 2001 From: FredApps Date: Sun, 8 Nov 2026 21:25:55 +0100 Subject: [PATCH 01/23] Naming: distinguish perspective controls from external feature names --- crates/engine/src/cmd.rs | 10 ++++++++++ crates/engine/src/cmd/develop.rs | 10 +++++----- crates/ui-egui/locales/cs.json | 6 +++--- crates/ui-egui/locales/de.json | 8 ++++---- crates/ui-egui/locales/es.json | 8 ++++---- crates/ui-egui/locales/fi.json | 6 +++--- crates/ui-egui/locales/fr.json | 8 ++++---- crates/ui-egui/locales/id.json | 6 +++--- crates/ui-egui/locales/it.json | 6 +++--- crates/ui-egui/locales/ja.json | 8 ++++---- crates/ui-egui/locales/ka.json | 8 ++++---- crates/ui-egui/locales/pl.json | 8 ++++---- crates/ui-egui/locales/pt-br.json | 6 +++--- crates/ui-egui/locales/ru.json | 8 ++++---- crates/ui-egui/locales/sv.json | 8 ++++---- crates/ui-egui/locales/uk.json | 8 ++++---- crates/ui-egui/locales/vi.json | 8 ++++---- crates/ui-egui/locales/zh-hans.json | 8 ++++---- crates/ui-egui/locales/zh-hant.json | 8 ++++---- crates/ui-egui/src/i18n/tests.rs | 10 ++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/right/crop.rs | 2 +- docs/feature-names.md | 11 +++++++++++ 23 files changed, 101 insertions(+), 70 deletions(-) create mode 100644 docs/feature-names.md diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d9e3466611..72b2dce09a 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -361,3 +361,13 @@ mod tests { } } } + +#[cfg(test)] +mod feature_name_tests { + #[test] + fn perspective_labels_keep_existing_command_ids() { + for (id, label) in [("geometry.upright", "Perspective Correction"), ("geometry.guides", "Perspective Guides")] { + assert_eq!(super::find_command(id).expect("existing command").label, label); + } + } +} diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 5403ad6eb2..3096466155 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -918,7 +918,7 @@ pub fn specs() -> Vec { // ---- geometry: Upright cmd!( "geometry.upright", - "Upright", + "Perspective Correction", [], None, "{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes", @@ -936,7 +936,7 @@ pub fn specs() -> Vec { Some(lightcraft_pipeline::upright::auto_transform(&src, &info, &d, m)) } }; - edit(s, "geometry.upright", "Upright", |d| { + edit(s, "geometry.upright", "Perspective Correction", |d| { d.geometry.upright = mode; d.geometry.upright_transform = transform; Ok(()) @@ -946,10 +946,10 @@ pub fn specs() -> Vec { ), cmd!( "geometry.guides", - "Guided Upright Guides", + "Perspective Guides", [], None, - "{guides: [[x0,y0,x1,y1], …] (≤ 4, normalized coords of the lens-corrected image), add?: bool (append one guide, dropping the oldest beyond 4)} — switches Upright to Guided", + "{guides: [[x0,y0,x1,y1], …] (≤ 4, normalized coords of the lens-corrected image), add?: bool (append one guide, dropping the oldest beyond 4)} — switches Perspective Correction to Guided", has_active, |s, p| { let parse = |v: &Value| -> Option<(Point, Point)> { @@ -959,7 +959,7 @@ pub fn specs() -> Vec { let guides: Vec<(Point, Point)> = p.get("guides").and_then(Value::as_array).map(|a| a.iter().filter_map(parse).collect()).unwrap_or_default(); let add = bool_or(p, "add", false); - edit(s, "geometry.guides", "Guided Upright", |d| { + edit(s, "geometry.guides", "Guided Perspective", |d| { if add { d.geometry.guides.extend(guides); } else { diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index ea10219217..acb38fb290 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -832,8 +832,8 @@ "Group into Stack": "Seskupit do sady", "Group name": "Název skupiny", "Guided": "S vodítky", - "Guided Upright": "Narovnání perspektivy s vodítky", - "Guided Upright Guides": "Vodítka narovnání perspektivy", + "Guided Perspective": "Perspektiva s vodítky", + "Perspective Guides": "Vodítka perspektivy", "HDR": "HDR", "HDR Merge": "Sloučit do HDR", "HDR Merge Preview": "Náhled sloučení do HDR", @@ -1998,7 +1998,7 @@ "Update Version with Current Settings": "Aktualizovat verzi podle aktuálního nastavení", "Update with Current Settings": "Aktualizovat podle aktuálního nastavení", "Updated the edits saved in the external editor": "Úpravy uložené v externím editoru byly aktualizovány", - "Upright": "Narovnání perspektivy", + "Perspective Correction": "Korekce perspektivy", "Urban": "Městská krajina", "Use": "Použít", "Use Keyword Set": "Použít sadu klíčových slov", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index bc67606eb6..a3eb73fca5 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -651,8 +651,8 @@ "Group into Stack": "Zu Stapel gruppieren", "Group name": "Gruppenname", "Guided": "Mit Hilfslinien", - "Guided Upright": "Perspektivkorrektur mit Hilfslinien", - "Guided Upright Guides": "Hilfslinien der Perspektivkorrektur", + "Guided Perspective": "Geführte Perspektive", + "Perspective Guides": "Perspektivhilfslinien", "HDR Merge": "Zu HDR zusammenfügen", "HDR Merge Preview": "Vorschau der HDR-Zusammenfügung", "HDR Panorama Merge": "Zu HDR-Panorama zusammenfügen", @@ -1611,7 +1611,7 @@ "Update Version with Current Settings": "Version mit aktuellen Einstellungen aktualisieren", "Update with Current Settings": "Mit aktuellen Einstellungen aktualisieren", "Updated the edits saved in the external editor": "Im externen Editor gespeicherte Bearbeitungen aktualisiert", - "Upright": "Perspektivkorrektur", + "Perspective Correction": "Perspektivkorrektur", "Urban": "Städtisch", "Use Keyword Set": "Stichwortsatz verwenden", "Use Library Folder": "Bibliotheksordner verwenden", @@ -1850,7 +1850,7 @@ "− harder border · + softer border": "− härterer Rand · + weicherer Rand", "≤ at most": "≤ höchstens", "≥ at least": "≥ mindestens", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-Ziehen zum Geraderichten, ⇧G für Perspektivkorrektur mit Hilfslinien und ein Raster beim Transformieren.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-Ziehen zum Geraderichten, ⇧G für Geführte Perspektive und ein Raster beim Transformieren.", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", "Any camera": "Jede Kamera", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index c34057bdfe..2d1d804559 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -657,8 +657,8 @@ "Group into Stack": "Agrupar en pila", "Group name": "Nombre del grupo", "Guided": "Guiado", - "Guided Upright": "Vertical guiado", - "Guided Upright Guides": "Guías de vertical guiado", + "Guided Perspective": "Perspectiva guiada", + "Perspective Guides": "Guías de perspectiva", "HDR Merge": "Combinación HDR", "HDR Merge Preview": "Vista previa de combinación HDR", "HDR Panorama Merge": "Combinación de panorámica HDR", @@ -1709,7 +1709,7 @@ "with a counterpart here come along, the rest is listed.": "con un equivalente aquí se incluyen, el resto se enumera.", "written by a newer LightCraft is refused with \"this library was written by a newer version of LightCraft\" and left": "escrita por un LightCraft más reciente se rechaza con «this library was written by a newer version of LightCraft» y se deja", "written by a newer LightCraft), LightCraft says so and why, and offers Try Again, Choose Another Library…, Continue": "escrita por un LightCraft más reciente), LightCraft lo indica con el motivo y ofrece Reintentar, Elegir otra biblioteca…, Continuar", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-arrastrar para enderezar, ⇧G Vertical guiado, una cuadrícula al transformar.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-arrastrar para enderezar, ⇧G Perspectiva guiada, una cuadrícula al transformar.", "Unrated": "Sin valorar", "Unreadable": "Ilegible", "Update": "Actualizar", @@ -1720,7 +1720,7 @@ "Update Version with Current Settings": "Actualizar versión con los ajustes actuales", "Update with Current Settings": "Actualizar con los ajustes actuales", "Updated the edits saved in the external editor": "Se actualizaron las ediciones guardadas en el editor externo", - "Upright": "Vertical", + "Perspective Correction": "Corrección de perspectiva", "Urban": "Urbano", "Use Keyword Set": "Usar conjunto de palabras clave", "Use Library Folder": "Usar carpeta de la biblioteca", diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index 59cc611cd6..ccf1c0df95 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -829,8 +829,8 @@ "Grouped by parent": "Ryhmitelty ylätason mukaan", "Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened.": "Ryhmitelty: saman avainsanan sisällä olevat avainsanat jakavat sen nimeävän rivin, ja pitkät luettelot ja ehdotukset lyhennetään.", "Guided": "Ohjattu", - "Guided Upright": "Ohjattu Upright", - "Guided Upright Guides": "Ohjatun Uprightin apuviivat", + "Guided Perspective": "Ohjattu perspektiivi", + "Perspective Guides": "Perspektiivin apuviivat", "HDR": "HDR", "HDR Headroom": "HDR-varakorkeus", "HDR Merge": "HDR-yhdistäminen", @@ -2117,7 +2117,7 @@ "Update to Current Process": "Päivitä nykyiseen prosessiin", "Update with Current Settings": "Päivitä nykyisillä asetuksilla", "Updated the edits saved in the external editor": "Ulkoisessa muokkausohjelmassa tallennetut muokkaukset päivitetty", - "Upright": "Upright", + "Perspective Correction": "Perspektiivin korjaus", "Urban": "Urbaani", "Use": "Käytä", "Use Keyword Set": "Käytä avainsanajoukkoa", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 31e6814b6d..aa2ce1508f 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -616,8 +616,8 @@ "Group into Stack": "Grouper en pile", "Group name": "Nom du groupe", "Guided": "Guidé", - "Guided Upright": "Upright guidé", - "Guided Upright Guides": "Repères de l'Upright guidé", + "Guided Perspective": "Perspective guidée", + "Perspective Guides": "Repères de perspective", "HDR Merge": "Fusion HDR", "HDR Merge Preview": "Aperçu de la fusion HDR", "HDR Panorama Merge": "Fusion de panorama HDR", @@ -1540,7 +1540,7 @@ "Update Version with Current Settings": "Mettre à jour la version avec les réglages actuels", "Update with Current Settings": "Mettre à jour avec les réglages actuels", "Updated the edits saved in the external editor": "Retouches enregistrées dans l'éditeur externe mises à jour", - "Upright": "Upright", + "Perspective Correction": "Correction de perspective", "Urban": "Urbain", "Use Keyword Set": "Utiliser le jeu de mots-clés", "Use Library Folder": "Utiliser le dossier de la bibliothèque", @@ -2209,7 +2209,7 @@ "with a counterpart here come along, the rest is listed.": "qui ont un équivalent ici suivent, le reste est listé.", "written by a newer LightCraft is refused with \"this library was written by a newer version of LightCraft\" and left": "écrite par une version plus récente de LightCraft est refusée avec « cette bibliothèque a été écrite par une version plus récente de LightCraft » et laissée", "written by a newer LightCraft), LightCraft says so and why, and offers Try Again, Choose Another Library…, Continue": "écrite par une version plus récente de LightCraft), LightCraft le signale avec la raison et propose Réessayer, Choisir une autre bibliothèque…, Continuer", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-glisser pour redresser, ⇧G Upright guidé, une grille pendant la transformation.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-glisser pour redresser, ⇧G Perspective guidée, une grille pendant la transformation.", "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "Aucun processeur graphique trouvé : LightCraft effectue le rendu sur le processeur, ce qui est beaucoup plus lent. Détails dans Aide → Informations système.", "On NixOS, start it from `nix develop`.": "Sous NixOS, lancez-le depuis `nix develop`.", "Files with the same content as another file in this import: only the first is imported.": "Fichiers au contenu identique à un autre fichier de cette importation : seul le premier est importé.", diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 52705328cc..344481eeb7 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -831,8 +831,8 @@ "Grouped by parent": "Dikelompokkan menurut induk", "Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened.": "Dikelompokkan: kata kunci di bawah induk yang sama ditampilkan dalam satu baris berlabel nama induknya; daftar panjang dan saran dipersingkat.", "Guided": "Terpandu", - "Guided Upright": "Tegakkan terpandu", - "Guided Upright Guides": "Garis panduan Tegakkan terpandu", + "Guided Perspective": "Perspektif Terpandu", + "Perspective Guides": "Garis Panduan Perspektif", "HDR": "HDR", "HDR Headroom": "Ruang HDR", "HDR Merge": "Gabung HDR", @@ -2111,7 +2111,7 @@ "Update to Current Process": "Perbarui ke versi proses terbaru", "Update with Current Settings": "Perbarui dengan pengaturan saat ini", "Updated the edits saved in the external editor": "Edit yang disimpan di editor eksternal diperbarui", - "Upright": "Tegakkan", + "Perspective Correction": "Koreksi Perspektif", "Urban": "Urban", "Use": "Gunakan", "Use Keyword Set": "Gunakan set kata kunci", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index 5b0ccc0cee..e6d7210b91 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -617,8 +617,8 @@ "Group into Stack": "Raggruppa in una pila", "Group name": "Nome gruppo", "Guided": "Guidato", - "Guided Upright": "Raddrizzamento guidato", - "Guided Upright Guides": "Guide del raddrizzamento guidato", + "Guided Perspective": "Prospettiva guidata", + "Perspective Guides": "Guide prospettiche", "HDR Merge": "Unione HDR", "HDR Merge Preview": "Anteprima unione HDR", "HDR Panorama Merge": "Unione panorama HDR", @@ -1571,7 +1571,7 @@ "Update Version with Current Settings": "Aggiorna la versione con le impostazioni correnti", "Update with Current Settings": "Aggiorna con le impostazioni correnti", "Updated the edits saved in the external editor": "Modifiche salvate nell'editor esterno aggiornate", - "Upright": "Raddrizzamento", + "Perspective Correction": "Correzione prospettica", "Urban": "Urbano", "Use Keyword Set": "Usa set di parole chiave", "Use Library Folder": "Usa la cartella della libreria", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index 97c15dd019..580c181c3f 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -523,7 +523,7 @@ "Gritty Street": "ざらついたストリート", "Group by Date: Automatic": "日付でグループ化:自動", "Group name": "グループ名", - "Guided Upright Guides": "ガイド付き遠近補正のガイド", + "Perspective Guides": "遠近補正ガイド", "HDR Merge Preview": "HDR合成のプレビュー", "HDR Panorama Merge Preview": "HDRパノラマ合成のプレビュー", "HDR Panorama with Last Settings": "前回の設定でHDRパノラマ合成", @@ -808,7 +808,7 @@ "Group by date": "日付でグループ化", "Group into Stack": "スタックにまとめる", "Guided": "ガイド付き", - "Guided Upright": "ガイド付き遠近補正", + "Guided Perspective": "ガイド付き遠近補正", "HDR Merge": "HDR合成", "HDR Panorama Merge": "HDRパノラマ合成", "HDR Panorama…": "HDRパノラマ合成…", @@ -1469,7 +1469,7 @@ "Update Version with Current Settings": "現在の設定でバージョンを更新", "Update with Current Settings": "現在の設定で更新", "Updated the edits saved in the external editor": "外部エディターで保存した編集内容を更新しました", - "Upright": "遠近補正", + "Perspective Correction": "遠近補正", "Urban": "アーバン", "Use Keyword Set": "キーワードセットを使用", "Use Library Folder": "ライブラリのフォルダを使用", @@ -2212,7 +2212,7 @@ "with a counterpart here come along, the rest is listed.": "対応するものがあれば取り込み、残りは一覧に表示します。", "written by a newer LightCraft is refused with \"this library was written by a newer version of LightCraft\" and left": "新しい LightCraft で書かれたものは「このライブラリは新しいバージョンの LightCraft で書かれました」として拒否され、", "written by a newer LightCraft), LightCraft says so and why, and offers Try Again, Choose Another Library…, Continue": "新しい LightCraft で書かれた)、LightCraft はその旨と理由を示し、「再試行」「別のライブラリを選択…」「続行」を提示します", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘ ドラッグで角度補正、⇧G ガイド付き遠近補正、変形中のグリッド。", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘ ドラッグで角度補正、⇧G ガイド付き遠近補正、変形中のグリッド。", "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "グラフィックプロセッサが見つかりません。LightCraftはCPUで描画するため、かなり遅くなります。詳細は「ヘルプ → システム情報」を参照してください。", "On NixOS, start it from `nix develop`.": "NixOSでは `nix develop` から起動してください。", "Files with the same content as another file in this import: only the first is imported.": "この読み込み内の別のファイルと内容が同じファイルです。最初のファイルだけが読み込まれます。", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 30769b60fa..9b6ee73096 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -900,8 +900,8 @@ "Group into Stack": "დასტაში გაერთიანება", "Group name": "ჯგუფის სახელი", "Guided": "მართვადი", - "Guided Upright": "მართვადი Upright", - "Guided Upright Guides": "მართვადი Upright-ის დამხმარე ხაზები", + "Guided Perspective": "მართვადი პერსპექტივა", + "Perspective Guides": "პერსპექტივის დამხმარე ხაზები", "HDR": "HDR", "HDR Headroom": "HDR მარაგი", "HDR Merge": "HDR გაერთიანება", @@ -2224,7 +2224,7 @@ "Update with Current Settings": "განახლება მიმდინარე პარამეტრებით", "Updated the edits saved in the external editor": "გარე რედაქტორში შენახული ცვლილებები განახლდა", "Upgrading from a Windows installer older than 0.6 (such as 0.5.0) keeps LightCraft in the folder it was installed": "0.6-ზე ძველი Windows-ის ინსტალერიდან (მაგ., 0.5.0) განახლებისას LightCraft რჩება იმ საქაღალდეში, სადაც", - "Upright": "Upright", + "Perspective Correction": "პერსპექტივის კორექცია", "Urban": "ქალაქური", "Use": "გამოყენება", "Use Keyword Set": "საკვანძო სიტყვების ნაკრების გამოყენება", @@ -2748,7 +2748,7 @@ "− harder border · + softer border": "− უფრო მკვეთრი საზღვარი · + უფრო რბილი საზღვარი", "≤ at most": "≤ არაუმეტეს", "≥ at least": "≥ არანაკლებ", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-გადათრევა გასასწორებლად, ⇧G მართვადი Upright, ბადე გარდაქმნისას.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-გადათრევა გასასწორებლად, ⇧G მართვადი პერსპექტივა, ბადე გარდაქმნისას.", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", "Focus Point": "ფოკუსის წერტილი", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index dbc29a1941..80b11bce5a 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -601,8 +601,8 @@ "Group into Stack": "Zgrupuj w stos", "Group name": "Nazwa grupy", "Guided": "Z prowadnicami", - "Guided Upright": "Korekcja perspektywy z prowadnicami", - "Guided Upright Guides": "Prowadnice korekcji perspektywy", + "Guided Perspective": "Perspektywa z prowadnicami", + "Perspective Guides": "Prowadnice perspektywy", "HDR Merge": "Scalanie HDR", "HDR Merge Preview": "Podgląd scalania HDR", "HDR Panorama Merge": "Scal panoramę HDR", @@ -1507,7 +1507,7 @@ "Update Version with Current Settings": "Zaktualizuj wersję bieżącymi ustawieniami", "Update with Current Settings": "Zaktualizuj bieżącymi ustawieniami", "Updated the edits saved in the external editor": "Zaktualizowano edycje zapisane w edytorze zewnętrznym", - "Upright": "Korekcja perspektywy", + "Perspective Correction": "Korekcja perspektywy", "Urban": "Miejski", "Use Keyword Set": "Użyj zestawu słów kluczowych", "Use Library Folder": "Użyj folderu biblioteki", @@ -1652,7 +1652,7 @@ "− harder border · + softer border": "− ostrzejsza krawędź · + bardziej miękka krawędź", "≤ at most": "≤ co najwyżej", "≥ at least": "≥ co najmniej", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘ i przeciągnij, aby wyprostować, ⇧G: korekcja perspektywy z liniami pomocniczymi; podczas przekształcania wyświetlana jest siatka.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘ i przeciągnij, aby wyprostować, ⇧G: korekcja perspektywy z liniami pomocniczymi; podczas przekształcania wyświetlana jest siatka.", "Any camera": "Dowolny aparat", "Any lens": "Dowolny obiektyw", "Any keyword": "Dowolne słowo kluczowe", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index 3aedd82906..f2a9a3c7b2 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -625,8 +625,8 @@ "Group into Stack": "Agrupar em pilha", "Group name": "Nome do grupo", "Guided": "Guiado", - "Guided Upright": "Vertical guiado", - "Guided Upright Guides": "Guias do vertical guiado", + "Guided Perspective": "Perspectiva guiada", + "Perspective Guides": "Guias de perspectiva", "HDR Merge": "Mesclagem HDR", "HDR Merge Preview": "Prévia da mesclagem HDR", "HDR Panorama Merge": "Mesclagem de panorama HDR", @@ -1564,7 +1564,7 @@ "Update Version with Current Settings": "Atualizar versão com as configurações atuais", "Update with Current Settings": "Atualizar com as configurações atuais", "Updated the edits saved in the external editor": "As edições salvas no editor externo foram atualizadas", - "Upright": "Vertical", + "Perspective Correction": "Correção de perspectiva", "Urban": "Urbano", "Use Keyword Set": "Usar conjunto de palavras-chave", "Use Library Folder": "Usar pasta da biblioteca", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index b3df02470e..7afde0167f 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -713,8 +713,8 @@ "Group by date": "Группировать по дате", "Group into Stack": "Сгруппировать в стопку", "Guided": "Направляемый", - "Guided Upright": "Направляемое выравнивание", - "Guided Upright Guides": "Направляющие выравнивания", + "Guided Perspective": "Перспектива по направляющим", + "Perspective Guides": "Направляющие перспективы", "HDR Merge": "Слияние HDR", "HDR Panorama Merge": "Слияние HDR-панорамы", "HDR Panorama with Last Settings": "HDR-панорама с последними настройками", @@ -1522,7 +1522,7 @@ "Update Version": "Обновить версию", "Update Version with Current Settings": "Обновить версию текущими настройками", "Update with Current Settings": "Обновить текущими настройками", - "Upright": "Выравнивание (Upright)", + "Perspective Correction": "Коррекция перспективы", "Urban": "Урбан", "Use Keyword Set": "Использовать набор ключевых слов", "Use Library Folder": "Использовать папку библиотеки", @@ -2415,7 +2415,7 @@ "© Your Name": "© Ваше имя", "≤ at most": "≤ не более", "≥ at least": "≥ не менее", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘+перетаскивание — выровнять, ⇧G — направляемое выравнивание, сетка при трансформации.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘+перетаскивание — выровнять, ⇧G — направляемое выравнивание, сетка при трансформации.", "Add to Apple Photos": "Добавить в Apple Фото", "Adding to Apple Photos…": "Добавление в Apple Фото…", "not added to Apple Photos (cancelled)": "не добавлено в Apple Фото (отменено)", diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 94b9e30333..226f702270 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -884,8 +884,8 @@ "Grouped by parent": "Grupperade efter överordnad", "Grouped: keywords inside the same keyword share a line naming it, and long lists and the suggestions are shortened.": "Grupperat: nyckelord inom samma nyckelord delar en rad som namnger det, och långa listor och förslagen förkortas.", "Guided": "Guidad", - "Guided Upright": "Guidad upprätning", - "Guided Upright Guides": "Stödlinjer för guidad upprätning", + "Guided Perspective": "Guidad perspektiv", + "Perspective Guides": "Perspektivstödlinjer", "Has Edits": "Har redigeringar", "Has GPS": "Har GPS", "has open — on this computer or another one sharing the folder — says who has it (\"already open in LightCraft (process": "har öppet – på den här datorn eller en annan som delar mappen – anger vem som har det (\"redan öppet i LightCraft (process", @@ -2297,7 +2297,7 @@ "Update Version with Current Settings": "Uppdatera version med aktuella inställningar", "Update with Current Settings": "Uppdatera med aktuella inställningar", "Updated the edits saved in the external editor": "Uppdaterade redigeringarna som sparats i den externa redigeraren", - "Upright": "Uppräta", + "Perspective Correction": "Perspektivkorrigering", "Urban": "Urban", "Use": "Använd", "Use camera-specific defaults": "Använd kameraspecifika standardvärden", @@ -2433,7 +2433,7 @@ "− harder border · + softer border": "− hårdare kant · + mjukare kant", "≤ at most": "≤ högst", "≥ at least": "≥ minst", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-dra för att räta upp, ⇧G guidad upprätning, ett rutnät under transformering.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-dra för att räta upp, ⇧G guidad upprätning, ett rutnät under transformering.", "★ Favorites": "★ Favoriter", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index 09b78fab1e..44c29c34c1 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -772,7 +772,7 @@ "Green label": "Зелена мітка", "Gritty Street": "Груба вулиця", "Group by Date: Automatic": "Групування за датою: автоматично", - "Guided Upright Guides": "Напрямні керованого випрямлення", + "Perspective Guides": "Напрямні перспективи", "HDR Merge Preview": "Попередній перегляд об’єднання HDR", "HDR Panorama Merge Preview": "Попередній перегляд об’єднання HDR-панорами", "HDR Panorama with Last Settings": "HDR-панорама з останніми налаштуваннями", @@ -998,7 +998,7 @@ "Group by date": "Групувати за датою", "Group into Stack": "Об’єднати в стос", "Guided": "Кероване", - "Guided Upright": "Кероване випрямлення", + "Guided Perspective": "Перспектива за напрямними", "HDR Merge": "Об’єднання HDR", "HDR Panorama Merge": "Об’єднання HDR-панорами", "HDR Panorama…": "HDR-панорама…", @@ -1509,7 +1509,7 @@ "Update Version with Current Settings": "Оновити версію поточними налаштуваннями", "Update with Current Settings": "Оновити поточними налаштуваннями", "Updated the edits saved in the external editor": "Зміни, збережені в зовнішньому редакторі, оновлено", - "Upright": "Випрямлення", + "Perspective Correction": "Корекція перспективи", "Urban": "Міське", "Use Keyword Set": "Використовувати набір ключових слів", "Use Library Folder": "Використовувати теку бібліотеки", @@ -1938,7 +1938,7 @@ "with a counterpart here come along, the rest is listed.": "з відповідником тут переносяться, решта перелічується.", "written by a newer LightCraft is refused with \"this library was written by a newer version of LightCraft\" and left": "створена новішим LightCraft, відхиляється з повідомленням «цю бібліотеку створено новішою версією LightCraft» і залишається", "written by a newer LightCraft), LightCraft says so and why, and offers Try Again, Choose Another Library…, Continue": "створена новішим LightCraft), LightCraft пояснює причину й пропонує Спробувати знову, Вибрати іншу бібліотеку…, Продовжити", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-перетягування для випрямлення, ⇧G для керованого випрямлення, сітка під час трансформування.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-перетягування для випрямлення, ⇧G для керованого випрямлення, сітка під час трансформування.", "Sort Albums A–Z": "Сортувати альбоми А–Я", "Go back to listing them by name": "Повернутися до списку за назвою", "Sort Contents A–Z": "Сортувати вміст А–Я", diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index af27e9aa0a..697040c368 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -761,8 +761,8 @@ "Group into Stack": "Gom thành chồng", "Group name": "Tên nhóm", "Guided": "Có hướng dẫn", - "Guided Upright": "Chỉnh thẳng có hướng dẫn", - "Guided Upright Guides": "Đường hướng dẫn chỉnh thẳng", + "Guided Perspective": "Phối cảnh có hướng dẫn", + "Perspective Guides": "Đường dẫn phối cảnh", "HDR": "HDR", "HDR Headroom": "Dự trữ HDR", "HDR Merge": "Ghép HDR", @@ -1929,7 +1929,7 @@ "Update to Current Process": "Cập nhật lên quy trình hiện tại", "Update with Current Settings": "Cập nhật bằng thiết lập hiện tại", "Updated the edits saved in the external editor": "Đã cập nhật chỉnh sửa lưu trong trình soạn ngoài", - "Upright": "Chỉnh thẳng", + "Perspective Correction": "Hiệu chỉnh phối cảnh", "Urban": "Đô thị", "Use": "Dùng", "Use Keyword Set": "Dùng bộ từ khóa", @@ -2243,7 +2243,7 @@ "− harder border · + softer border": "− viền cứng hơn · + viền mềm hơn", "≤ at most": "≤ tối đa", "≥ at least": "≥ tối thiểu", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Chỉnh thẳng có hướng dẫn, lưới khi biến đổi.", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-kéo để chỉnh thẳng, ⇧G Phối cảnh có hướng dẫn, lưới khi biến đổi.", "日本語": "日本語", "繁體中文(台灣)": "繁體中文(台灣)", "All Mask Overlays": "Mọi lớp phủ mặt nạ", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index ca13d782a5..401cef6d63 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -762,8 +762,8 @@ "Group by date": "按日期分组", "Group into Stack": "合并为堆叠", "Guided": "引导式", - "Guided Upright": "引导式透视校正", - "Guided Upright Guides": "引导式垂直校正参考线", + "Guided Perspective": "引导式透视", + "Perspective Guides": "透视辅助线", "HDR Merge": "HDR 合并", "HDR Panorama Merge": "HDR 全景合并", "HDR Panorama with Last Settings": "使用上次设置合并 HDR 全景", @@ -1540,7 +1540,7 @@ "Update Version with Current Settings": "使用当前设置更新版本", "Update with Current Settings": "使用当前设置更新", "Updated the edits saved in the external editor": "已更新在外部编辑器中保存的编辑", - "Upright": "垂直校正", + "Perspective Correction": "透视校正", "Urban": "都市", "Use Keyword Set": "使用关键字集", "Use Library Folder": "使用图库文件夹", @@ -2388,7 +2388,7 @@ "Without Saving and Quit (issue #100). It no longer quietly starts a demo session that looked like a reset library and": "不保存并退出(问题 #100)。它不再静默启动一个看似已重置图库的演示会话,", "written by a newer LightCraft is refused with \"this library was written by a newer version of LightCraft\" and left": "由更新版本 LightCraft 写入的目录会被拒绝,提示“此图库由更新版本的 LightCraft 写入”,并保持", "written by a newer LightCraft), LightCraft says so and why, and offers Try Again, Choose Another Library…, Continue": "由更新版本 LightCraft 写入),LightCraft 会说明情况和原因,并提供 重试、选择其他图库…、继续", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-拖拽进行拉直,⇧G 引导式垂直校正,变换时显示网格。", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-拖拽进行拉直,⇧G 引导式垂直校正,变换时显示网格。", "on the card after Review Import is reported instead of being imported with stale details. Checking an export path": "在“审阅导入”后在存储卡上发生的更改会被报告,而不会以过时信息导入。检查导出路径", "one by one — they can always be exported again, and on a USB drive or a NAS that per-file sync dominated a large": "逐个进行——它们随时可以重新导出,而在 USB 硬盘或 NAS 上,逐文件同步曾占用了大量", "over a same-name same-size look-alike, and skips (and reports) photos it can't tell apart instead of guessing.": "而不是同名同大小的相似文件,并且会跳过(并报告)无法区分的照片,而不是猜测。", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index f3dfc422ec..0f4f0f9a7a 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -763,8 +763,8 @@ "Group by date": "依日期分組", "Group into Stack": "分組為堆疊", "Guided": "引導式", - "Guided Upright": "引導式透視校正", - "Guided Upright Guides": "引導式透視校正參考線", + "Guided Perspective": "引導式透視", + "Perspective Guides": "透視輔助線", "HDR Merge": "HDR 合併", "HDR Panorama Merge": "HDR 全景合併", "HDR Panorama with Last Settings": "使用上次設定合併 HDR 全景", @@ -1546,7 +1546,7 @@ "Update Version with Current Settings": "以目前設定更新版本", "Update with Current Settings": "以目前設定更新", "Updated the edits saved in the external editor": "已更新在外部編輯器中儲存的編輯內容", - "Upright": "透視校正", + "Perspective Correction": "透視校正", "Urban": "城市", "Use Keyword Set": "使用關鍵字集", "Use Library Folder": "使用照片庫資料夾", @@ -2393,7 +2393,7 @@ "Without Saving and Quit (issue #100). It no longer quietly starts a demo session that looked like a reset library and": "不儲存並結束(問題 #100)。它不再靜默啟動一個看似已重設圖庫的示範工作階段,", "written by a newer LightCraft is refused with \"this library was written by a newer version of LightCraft\" and left": "由更新版本 LightCraft 寫入的目錄會被拒絕,提示「此圖庫由更新版本的 LightCraft 寫入」,並保持", "written by a newer LightCraft), LightCraft says so and why, and offers Try Again, Choose Another Library…, Continue": "由更新版本 LightCraft 寫入),LightCraft 會說明情況和原因,並提供 重試、選擇其他圖庫…、繼續", - "⌘-drag to straighten, ⇧G Guided Upright, a grid while transforming.": "⌘-拖曳進行拉直,⇧G 引導式垂直校正,變換時顯示網格。", + "⌘-drag to straighten, ⇧G Guided Perspective, a grid while transforming.": "⌘-拖曳進行拉直,⇧G 引導式垂直校正,變換時顯示網格。", "Face recognition is on": "臉部辨識已開啟", "Face recognition is off. Turn it on to get name suggestions and see look-alike faces together.": "臉部辨識已關閉。開啟後可取得姓名建議,並將相似的臉孔放在一起檢視。", "Turn on": "開啟", diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0b7f31cf9e..47af31e2c6 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1295,3 +1295,13 @@ fn polish_switches_formats_dates_and_reads_every_count() { assert_polish_glyphs(&ctx); set_language(Locale::En); } + +#[test] +fn perspective_labels_are_translated_in_every_shipped_locale() { + for locale in Locale::ALL.iter().filter(|locale| **locale != Locale::En) { + for source in ["Perspective Correction", "Guided Perspective", "Perspective Guides"] { + assert!(locale.catalog().contains_key(source), "{}: {source}", locale.code()); + assert!(!locale.tr(source).contains("Upright"), "{}: {source}", locale.code()); + } + } +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f4398d2842..de80d5581e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -65,7 +65,7 @@ pub const UI_COMMANDS: &[UiCommand] = &[ // G: Photo Grid ↔ Square Grid (from other views: the photo grid) ("view.gridToggle", "Grid", Some("G"), ""), ("library.selectOnlyActive", "Select Only Active Photo", Some("Cmd+Shift+D"), "Edit"), - ("tool.guidedUpright", "Guided Upright", Some("Shift+G"), "Window>Tools"), + ("tool.guidedUpright", "Guided Perspective", Some("Shift+G"), "Window>Tools"), ("view.detail", "Detail View", Some("D"), "View"), ("view.compare", "Compare", Some("Shift+C"), "View"), ("view.survey", "Survey", Some("N"), "View"), diff --git a/crates/ui-egui/src/panels/right/crop.rs b/crates/ui-egui/src/panels/right/crop.rs index 0b71fffe8a..f2e72be0cb 100644 --- a/crates/ui-egui/src/panels/right/crop.rs +++ b/crates/ui-egui/src/panels/right/crop.rs @@ -211,7 +211,7 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { divider(ui); header(ui, "Geometry"); padded(ui, |ui| { - ui.label(crate::i18n::tr("Upright")); + ui.label(crate::i18n::tr("Perspective Correction")); { use lightcraft_develop::Upright; let modes = [ diff --git a/docs/feature-names.md b/docs/feature-names.md new file mode 100644 index 0000000000..80ab49026b --- /dev/null +++ b/docs/feature-names.md @@ -0,0 +1,11 @@ +# Feature naming + +LightCraft uses **Perspective Correction**, **Guided Perspective**, and **Perspective Guides** for its own geometry controls. The section includes Off, Auto, Guided, Level, Vertical and Full modes, so its name does not imply every mode is automatic. + +The previous Upright terminology is a naming-review candidate, not a verified finding about trademark registration. These descriptive names are chosen to distinguish LightCraft's own implementation. + +## Compatibility boundary + +The `geometry.upright`, `geometry.guides` and `tool.guidedUpright` commands, saved tool keys, Rust enum variants and serialized settings remain stable. XMP `crs:PerspectiveUpright` and `UprightTransform_*` mappings and Lightroom import messages still describe the external format accurately. No rendering, import or export logic changes. + +All 17 shipped non-English catalogs contain the new labels. The normal CI, perspective-mode tests and a visual panel/tool check remain required before this draft is marked ready. From c137ffea8b07954d44001ddfd683d3ff3cd5bc53 Mon Sep 17 00:00:00 2001 From: FredApps Date: Sun, 8 Nov 2026 22:36:42 +0100 Subject: [PATCH 02/23] test(naming): guard neutral display labels --- crates/ui-egui/tests/display_names.rs | 178 ++++++++++++++++++++++++++ docs/feature-names.md | 4 + 2 files changed, 182 insertions(+) create mode 100644 crates/ui-egui/tests/display_names.rs diff --git a/crates/ui-egui/tests/display_names.rs b/crates/ui-egui/tests/display_names.rs new file mode 100644 index 0000000000..a1b312da96 --- /dev/null +++ b/crates/ui-egui/tests/display_names.rs @@ -0,0 +1,178 @@ +//! Guard the production display surfaces without banning compatibility identifiers or notices. +use std::path::{Path, PathBuf}; + +const BANNED: &[&str] = &["Upright"]; +const ALLOWED: &[&str] = &[]; +const ROOTS: &[&str] = &["src", "../engine/src/cmd"]; + +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn banned_display(text: &str) -> bool { + if ALLOWED.contains(&text) || text.starts_with("Lightroom geometry for {path} ") { + return false; + } + BANNED.iter().any(|banned| { + text.match_indices(banned) + .any(|(at, _)| !text[..at].chars().next_back().is_some_and(is_word) && !text[at + banned.len()..].chars().next().is_some_and(is_word)) + }) +} + +// Read ordinary and raw Rust string literals, ignoring comments. No compiler dependency is +// needed, so this guard can also run by itself when a full application build is unavailable. +#[allow(clippy::cognitive_complexity)] // This small test-only lexer keeps raw-string/comment state together. +fn literals(source: &str) -> Vec { + let chars: Vec = source.chars().collect(); + let mut out = Vec::new(); + let mut at = 0; + let mut test_module = false; + let mut test_depth = 0_usize; + while at < chars.len() { + if chars.get(at..at + 12) == Some(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) { + at += 12; + let rest: String = chars[at..].iter().collect(); + if rest.trim_start().starts_with("mod ") { + test_module = true; + } + } else if chars.get(at..at + 2) == Some(&['/', '/']) { + while at < chars.len() && chars[at] != '\n' { + at += 1; + } + } else if chars.get(at..at + 2) == Some(&['/', '*']) { + at += 2; + let mut depth = 1; + while at < chars.len() && depth > 0 { + if chars.get(at..at + 2) == Some(&['/', '*']) { + depth += 1; + at += 2; + } else if chars.get(at..at + 2) == Some(&['*', '/']) { + depth -= 1; + at += 2; + } else { + at += 1; + } + } + } else if chars[at] == 'r' && matches!(chars.get(at + 1), Some('"' | '#')) { + let start = at; + at += 1; + while chars.get(at) == Some(&'#') { + at += 1; + } + let hashes = at - start - 1; + if chars.get(at) != Some(&'"') { + continue; + } + at += 1; + let begin = at; + while at < chars.len() { + if chars[at] == '"' && (1..=hashes).all(|n| chars.get(at + n) == Some(&'#')) { + break; + } + at += 1; + } + if !test_module { + out.push(chars[begin..at].iter().collect()); + } + at += 1 + hashes; + } else if chars[at] == '"' { + at += 1; + let mut text = String::new(); + while at < chars.len() { + let c = chars[at]; + at += 1; + if c == '"' { + break; + } + if c == '\\' && at < chars.len() { + text.push(chars[at]); + at += 1; + } else { + text.push(c); + } + } + if !test_module { + out.push(text); + } + } else if chars[at] == '\'' && chars.get(at + 2) == Some(&'\'') { + at += 3; // A character literal such as '"', not the start of a string. + } else { + if test_module { + match chars[at] { + '{' => test_depth += 1, + '}' => { + test_depth = test_depth.saturating_sub(1); + if test_depth == 0 { + test_module = false; + } + } + ';' if test_depth == 0 => test_module = false, + _ => {} + } + } + at += 1; + } + } + out +} + +fn check_tree(path: &Path, failures: &mut Vec) { + if path.is_dir() { + for entry in std::fs::read_dir(path).expect("source directory") { + let path = entry.expect("source entry").path(); + if path.file_name().is_some_and(|name| name == "tests") { + continue; + } + check_tree(&path, failures); + } + } else if path.extension().is_some_and(|ext| ext == "rs") { + let name = path.file_name().expect("source filename").to_string_lossy(); + if name == "tests.rs" || name.ends_with("_tests.rs") { + return; + } + let source = std::fs::read_to_string(path).expect("UTF-8 Rust source"); + // Skip only inline test modules, not later production following test-only imports. + for text in literals(&source) { + if banned_display(&text) { + failures.push(format!("{}: {text:?}", path.display())); + } + } + } +} + +#[test] +fn production_display_names_stay_neutral() { + let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut failures = Vec::new(); + for root in ROOTS { + let root = base.join(root); + assert!(root.exists(), "missing display source: {}", root.display()); + check_tree(&root, &mut failures); + } + assert!(failures.is_empty(), "Banned display names:\n{}", failures.join("\n")); +} + +#[test] +fn guard_distinguishes_labels_from_identifiers_and_comments() { + for name in BANNED { + assert!(banned_display(name), "{name}"); + } + for name in ALLOWED { + assert!(!banned_display(name), "{name}"); + } + assert!(!banned_display("filter.cameraRaw")); + assert!(!banned_display("tool.guidedUpright")); + assert!(!banned_display("insert.smartArt")); + assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]); + assert_eq!(literals("r#\"raw label\"#"), ["raw label"]); +} + +#[test] +fn guard_scans_production_after_test_only_items() { + let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"live label"#; } + "###; + assert_eq!(literals(source), ["live label"]); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]); +} diff --git a/docs/feature-names.md b/docs/feature-names.md index 80ab49026b..532d0f7bcf 100644 --- a/docs/feature-names.md +++ b/docs/feature-names.md @@ -9,3 +9,7 @@ The previous Upright terminology is a naming-review candidate, not a verified fi The `geometry.upright`, `geometry.guides` and `tool.guidedUpright` commands, saved tool keys, Rust enum variants and serialized settings remain stable. XMP `crs:PerspectiveUpright` and `UprightTransform_*` mappings and Lightroom import messages still describe the external format accurately. No rendering, import or export logic changes. All 17 shipped non-English catalogs contain the new labels. The normal CI, perspective-mode tests and a visual panel/tool check remain required before this draft is marked ready. + +## Regression coverage + +The standard-library-only `display_names` integration tests scan production Rust string literals for the retired display names and preserve explicit compatibility exceptions. They also test identifier, comment and raw-string handling. These focused checks do not replace application or visual testing. From 34161c9a8c2011070b57b8786a7b6b5cb66d7cef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 23:56:56 +0000 Subject: [PATCH 03/23] Use craft-tiff from craft-libs; remove crates/tiff lightcraft-tiff moved to craft-libs unchanged as craft-tiff (storytold/craft-libs#783), the first step of sharing RAW support with PhotoCraft (storytold/craft-libs#587). The layer table drops tiff and its intra-layer ordering before raster. --- Cargo.lock | 24 +- Cargo.toml | 3 +- crates/codecs/README.md | 2 +- crates/codecs/src/encode.rs | 2 +- crates/engine/Cargo.toml | 2 +- crates/engine/src/files/tests.rs | 26 +- crates/engine/src/tests/face_tiles.rs | 2 +- crates/engine/src/tests/import.rs | 4 +- crates/engine/src/tests/xmp.rs | 4 +- crates/meta/Cargo.toml | 2 +- crates/meta/src/container.rs | 8 +- crates/meta/src/cr3.rs | 14 +- crates/meta/src/exif.rs | 26 +- crates/meta/src/focus.rs | 2 +- crates/meta/src/focus/tests.rs | 4 +- crates/meta/src/focus_read.rs | 7 +- crates/meta/src/heif.rs | 2 +- crates/meta/src/lib.rs | 30 +- crates/meta/src/psd.rs | 6 +- crates/meta/src/tags.rs | 6 +- crates/meta/src/xmp.rs | 4 +- crates/raw/Cargo.toml | 2 +- crates/raw/examples/rawinfo.rs | 2 +- crates/raw/examples/rawrender.rs | 2 +- crates/raw/src/dcp.rs | 6 +- crates/raw/src/dng.rs | 6 +- crates/raw/src/dngwrite.rs | 6 +- crates/raw/src/gaintable.rs | 2 +- crates/raw/src/lib.rs | 46 +- crates/raw/src/preview.rs | 10 +- crates/raw/src/preview/tests.rs | 9 +- crates/raw/src/semantic.rs | 6 +- crates/raw/src/sparse.rs | 6 +- crates/raw/src/tests.rs | 4 +- crates/raw/src/tiffraw.rs | 6 +- crates/raw/src/unpack.rs | 2 +- crates/raw/src/vendor.rs | 4 +- crates/raw/src/vendor/arw.rs | 54 +-- crates/raw/src/vendor/arw6.rs | 6 +- crates/raw/src/vendor/arw6_testenc.rs | 4 +- crates/raw/src/vendor/arw_lens.rs | 6 +- crates/raw/src/vendor/arw_lens_rm6.rs | 4 +- crates/raw/src/vendor/cr2.rs | 10 +- crates/raw/src/vendor/cr2/sraw.rs | 8 +- crates/raw/src/vendor/cr3.rs | 12 +- crates/raw/src/vendor/erf.rs | 12 +- crates/raw/src/vendor/hasselblad.rs | 6 +- crates/raw/src/vendor/kodak.rs | 10 +- crates/raw/src/vendor/mef.rs | 6 +- crates/raw/src/vendor/mrw.rs | 12 +- crates/raw/src/vendor/nef.rs | 18 +- crates/raw/src/vendor/nef_lens.rs | 6 +- crates/raw/src/vendor/nefc.rs | 6 +- crates/raw/src/vendor/orf.rs | 12 +- crates/raw/src/vendor/pef.rs | 8 +- crates/raw/src/vendor/raf.rs | 4 +- crates/raw/src/vendor/raf_lens.rs | 4 +- crates/raw/src/vendor/rw2.rs | 4 +- crates/raw/src/vendor/sr2.rs | 10 +- crates/raw/src/vendor/srw.rs | 12 +- crates/raw/tests/it/corpus.rs | 2 +- crates/raw/tests/it/dng.rs | 6 +- crates/raw/tests/it/robust.rs | 8 +- crates/raw/tests/it/sony_lens_inventory.rs | 2 +- crates/raw/tests/it/vendor_robust.rs | 4 +- crates/raw/tests/sr2_heap.rs | 2 +- crates/tiff/Cargo.toml | 16 - crates/tiff/README.md | 45 -- crates/tiff/src/image.rs | 248 ---------- crates/tiff/src/lib.rs | 468 ------------------ crates/tiff/src/makernote.rs | 235 --------- crates/tiff/src/reader.rs | 536 --------------------- crates/tiff/src/tags.rs | 226 --------- crates/tiff/src/writer.rs | 293 ----------- crates/tiff/tests/it/main.rs | 3 - crates/tiff/tests/it/roundtrip.rs | 429 ----------------- xtask/src/layers.rs | 2 - 77 files changed, 278 insertions(+), 2780 deletions(-) delete mode 100644 crates/tiff/Cargo.toml delete mode 100644 crates/tiff/README.md delete mode 100644 crates/tiff/src/image.rs delete mode 100644 crates/tiff/src/lib.rs delete mode 100644 crates/tiff/src/makernote.rs delete mode 100644 crates/tiff/src/reader.rs delete mode 100644 crates/tiff/src/tags.rs delete mode 100644 crates/tiff/src/writer.rs delete mode 100644 crates/tiff/tests/it/main.rs delete mode 100644 crates/tiff/tests/it/roundtrip.rs diff --git a/Cargo.lock b/Cargo.lock index 1d824dde9d..992d833789 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1222,6 +1222,15 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6595c432463d456cf91361d1cab1a4416661a006#6595c432463d456cf91361d1cab1a4416661a006" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -3744,6 +3753,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "craft-tiff", "crc32fast", "fs4", "harfrust 0.13.3", @@ -3772,7 +3782,6 @@ dependencies = [ "lightcraft-segment", "lightcraft-slideshow", "lightcraft-testkit", - "lightcraft-tiff", "log", "miniz_oxide 0.9.1", "rayon", @@ -3909,9 +3918,9 @@ name = "lightcraft-meta" version = "0.18.0" dependencies = [ "chrono", + "craft-tiff", "lightcraft-geom", "lightcraft-heif", - "lightcraft-tiff", "proptest", "quick-xml 0.41.0", "serde", @@ -3967,6 +3976,7 @@ version = "0.18.0" dependencies = [ "chrono", "craft-crw", + "craft-tiff", "dhat", "jpeg-encoder", "jxl-oxide", @@ -3975,7 +3985,6 @@ dependencies = [ "lightcraft-meta", "lightcraft-raster", "lightcraft-testkit", - "lightcraft-tiff", "miniz_oxide 0.9.1", "proptest", "rayon", @@ -4029,15 +4038,6 @@ version = "0.18.0" name = "lightcraft-testkit" version = "0.18.0" -[[package]] -name = "lightcraft-tiff" -version = "0.18.0" -dependencies = [ - "proptest", - "serde", - "thiserror 2.0.21", -] - [[package]] name = "lightcraft-ui-egui" version = "0.18.0" diff --git a/Cargo.toml b/Cargo.toml index 2215751be9..5fae7a219e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,8 @@ lightcraft-sysmem = { path = "crates/sysmem" } lightcraft-wincolor = { path = "crates/wincolor" } lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } -lightcraft-tiff = { path = "crates/tiff" } +# TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783). +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6595c432463d456cf91361d1cab1a4416661a006" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } diff --git a/crates/codecs/README.md b/crates/codecs/README.md index b993c52efe..7df71c9a11 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -48,7 +48,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d |---|---|---|---| | JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews | | PNG | yes, 1–16-bit, palette, tRNS, interlaced | 8/16-bit, gray/GA/RGB/RGBA | iCCP, eXIf, iTXt XMP; sRGB/cICP/cHRM/gAMA honoured when no ICC | -| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `lightcraft-tiff`) | +| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `craft-tiff`) | | WebP | lossy + lossless, alpha, first frame of animations | lossless only | ICCP/EXIF/XMP chunks | | GIF / BMP | yes (first GIF frame) | — | via `image` | | PSD / PSB | merged composite: 8/16/32-bit gray, RGB, CMYK, indexed, duotone (as gray); raw/RLE | — | ICC (1039), EXIF (1058), XMP (1060); ZIP-compressed composite, Lab and 1-bit unsupported | diff --git a/crates/codecs/src/encode.rs b/crates/codecs/src/encode.rs index 82f654adf2..18e8be64aa 100644 --- a/crates/codecs/src/encode.rs +++ b/crates/codecs/src/encode.rs @@ -229,7 +229,7 @@ pub enum TiffCompression { } /// Encode TIFF: 8/16-bit integer or 32-bit float, gray/RGB with optional (unassociated) alpha. -/// ICC and XMP are embedded; EXIF is not (write it through the TIFF writer in `lightcraft-tiff`). +/// ICC and XMP are embedded; EXIF is not (write it through the TIFF writer in `craft-tiff`). pub fn encode_tiff(img: &EncodeImage, compression: TiffCompression, meta: &EncodeMeta) -> Result> { use tiff::encoder::{Compression, DeflateLevel, TiffEncoder}; use tiff::tags::Predictor; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 895ef52126..ab73adb42e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -68,4 +68,4 @@ jxl-oxide = { workspace = true } # Lossless synthetic HEIC files (the import test; decoded when the codecs' `heif` feature is on). lightcraft-heif = { workspace = true, features = ["testdata"] } libc = { workspace = true } -lightcraft-tiff = { workspace = true } +craft-tiff = { workspace = true } diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 599d173f7d..b60e9bb932 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -281,7 +281,7 @@ fn tiff_with_preview_strip(strip: &[u8], tail: usize, what: Fixture) -> Vec /// [`tiff_with_preview_strip`] that also keeps the `smaller` JPEGs in sub-IFDs of IFD0, as an ARW keeps its /// 1616 px preview beside the full-size one. fn tiff_with_preview_strips(strip: &[u8], smaller: &[&[u8]], tail: usize, what: Fixture) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let mut preview = IfdBuilder::new(); if what.dng { preview.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0])); @@ -656,7 +656,7 @@ fn corpus_a7cr_warp_keeps_coordinates_after_orientation_and_resizing() { let Ok(mut bytes) = std::fs::read(root.join("raw").join(name)) else { continue }; let off = lightcraft_raw::probe_info(&bytes).unwrap(); assert!(embedded_lens(&off).is_none()); - let tiff = lightcraft_tiff::Tiff::parse(&bytes).unwrap(); + let tiff = craft_tiff::Tiff::parse(&bytes).unwrap(); let at = tiff.find(0x7036).unwrap().offset as usize; let mut enabled = Vec::new(); tiff.order.put_u16(&mut enabled, 17); @@ -1214,8 +1214,8 @@ fn corpus_clipped_sky_beside_a_tree_has_no_coloured_halo() { /// copy's samples are much brighter than the image's here, so a picture says which one it came from. #[test] fn exports_never_develop_a_dngs_reduced_copy() { - use lightcraft_tiff::tags::{self as t, photometric}; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::tags::{self as t, photometric}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; use serde_json::json; let linear = |subfile: u32, w: u32, h: u32, sample: u16| { let mut ifd = IfdBuilder::new(); @@ -1292,10 +1292,10 @@ fn exports_never_develop_a_dngs_reduced_copy() { /// heuristic would never look) is used; a matte with an unknown name is ignored. #[test] fn dng_sky_matte_drives_the_sky_mask() { + use craft_tiff::tags::{self as t, photometric}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; use lightcraft_develop::{DevelopSettings, LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape}; use lightcraft_pipeline::{RenderRequest, render}; - use lightcraft_tiff::tags::{self as t, photometric}; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; let (w, h) = (16u32, 8u32); let image = |ifd: &mut IfdBuilder, w: u32, h: u32, cpp: u16, bits: u16, data: Vec| { ifd.set(t::IMAGE_WIDTH, Value::Long(vec![w])); @@ -1530,7 +1530,7 @@ fn unsupported_raw_imports_as_preview_only_and_survives_reopen() { /// A raw whose TIFF shell holds only a small RGB image (IFD0) next to a private block, as Exif /// declares a picture 25x its size. fn tiff_shell(w: u32, h: u32, shell: bool) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let mut ifd0 = IfdBuilder::new(); ifd0.set(t::IMAGE_WIDTH, Value::Long(vec![w])); ifd0.set(t::IMAGE_LENGTH, Value::Long(vec![h])); @@ -1571,7 +1571,7 @@ fn thumbnail_only_tiff_raw_is_preview_only_not_a_plain_image() { // TIFFs preserving camera Make tags (SONY, NIKON, etc.) are ordinary images, not raws (#281) for make in ["SONY", "NIKON CORPORATION", "PENTAX", "RICOH", "SAMSUNG"] { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let mut ifd0 = IfdBuilder::new(); ifd0.set(t::IMAGE_WIDTH, Value::Long(vec![24])); ifd0.set(t::IMAGE_LENGTH, Value::Long(vec![16])); @@ -1615,7 +1615,7 @@ fn undecodable_container_with_a_preview_imports_as_preview_only() { /// holds the preview) imports as a raw shown from its preview, not as a greyscale image of the mosaic. #[test] fn uncompressed_leaf_mos_imports_as_a_preview_only_raw() { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let px: Vec = (0..40 * 30).flat_map(|i| [(i % 251) as u8, 128, 200]).collect(); let jpeg = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap(); let mos = |leaf_data: bool| { @@ -1646,7 +1646,7 @@ fn uncompressed_leaf_mos_imports_as_a_preview_only_raw() { /// headers; loading it says what is wrong instead of naming a bare TIFF compression number. #[test] fn gopro_vc5_dng_imports_and_fails_to_load_with_a_clear_reason() { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let mut ifd = IfdBuilder::new(); ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); ifd.set(t::IMAGE_WIDTH, Value::Long(vec![32])); @@ -1675,7 +1675,7 @@ fn decode_failures_of_recognised_raws_may_fall_back_to_the_preview() { assert_eq!(preview_reason(b"x", RawError::Unsupported("x".into())), Ok("x".to_string())); assert!(preview_reason(b"x", RawError::Corrupt("bad strip".into())).is_ok_and(|w| w.contains("bad strip"))); assert!(preview_reason(b"x", RawError::Limit("too big")).is_ok()); - assert!(preview_reason(b"x", RawError::Tiff(lightcraft_tiff::TiffError::MissingTag(256))).is_ok()); + assert!(preview_reason(b"x", RawError::Tiff(craft_tiff::TiffError::MissingTag(256))).is_ok()); assert!(preview_reason(b"x", RawError::NotRaw).is_err()); assert!(preview_reason(cr3, RawError::Corrupt("bad".into())).is_ok_and(|w| w.starts_with("CR3 "))); } @@ -1740,8 +1740,8 @@ fn a_quick_thumbnail_without_an_embedded_preview_renders_the_raw() { /// A Sony ARW of `model`: a 64 × 48 uncompressed 14-bit CFA strip in a SubIFD (as `crates/raw/tests/it/vendor_robust.rs` /// lays it out) whose IFD carries the full-frame 16–35 mm distortion table (tag 0x7037). fn sony_arw(model: &str) -> Vec { - use lightcraft_tiff::tags::{self as t, photometric}; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::tags::{self as t, photometric}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; // 3:2, the aspect Sony's lens opcodes are limited to let (w, h) = (72u32, 48u32); let mut raw = IfdBuilder::new(); diff --git a/crates/engine/src/tests/face_tiles.rs b/crates/engine/src/tests/face_tiles.rs index d3b50aefc4..37d20b58b0 100644 --- a/crates/engine/src/tests/face_tiles.rs +++ b/crates/engine/src/tests/face_tiles.rs @@ -46,7 +46,7 @@ fn jpeg(w: u32, h: u32, px: impl Fn(u32, u32) -> [u8; 3]) -> Vec { /// photo by its largest preview (600 × 400) and the develop path renders from it, after reading /// the whole file. fn raw_with_two_previews(tail: usize) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let preview = |w: u32, h: u32, bytes: Vec, first: bool| { let mut ifd = IfdBuilder::new(); if first { diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 4885b5d30b..95be627fc5 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -34,7 +34,7 @@ fn write_png(path: &Path, seed: u8) { } fn exif_clock_block(original: Option<&str>, digitized: Option<&str>) -> Vec { - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; let mut exif = IfdBuilder::new(); if let Some(value) = original { @@ -2857,8 +2857,8 @@ fn heic_imports_as_a_normal_photo_or_says_why_not() { /// writes as UTC: an iPhone photo landed five hours late and after 19:00 on the wrong day. #[test] fn a_heic_is_dated_by_its_exif_and_not_by_the_file() { + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; use lightcraft_heif::testdata::{Spec, build}; - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; let src = temp_dir("heic-capture-time"); let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150]; let mut exif = IfdBuilder::new(); diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index 0d27be67c9..006a0a488a 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -638,7 +638,7 @@ fn an_orientation_only_the_xmp_states_leaves_stored_frame_regions_as_written() { let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]); // an Exif that states the size as stored (32 × 24, as cameras do) and no orientation let exif = { - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; let mut sub = IfdBuilder::new(); sub.set(t::PIXEL_X_DIMENSION, Value::Long(vec![32])); sub.set(t::PIXEL_Y_DIMENSION, Value::Long(vec![24])); @@ -681,7 +681,7 @@ fn a_raws_decoder_orientation_turns_stored_frame_regions_on_import_and_reread() let px: Vec = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); let strip: Vec = px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect(); { - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let mut raw = IfdBuilder::new(); raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); raw.set(t::IMAGE_WIDTH, Value::Long(vec![16])); diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index 4f2fad315e..e570fe21de 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -9,7 +9,7 @@ description = "LightCraft metadata: EXIF, XMP, IPTC (L1)" workspace = true [dependencies] -lightcraft-tiff = { workspace = true } +craft-tiff = { workspace = true } lightcraft-geom = { workspace = true } serde = { workspace = true } quick-xml = { workspace = true } diff --git a/crates/meta/src/container.rs b/crates/meta/src/container.rs index 0136bf6846..5b4242bfff 100644 --- a/crates/meta/src/container.rs +++ b/crates/meta/src/container.rs @@ -14,7 +14,7 @@ //! - HEIF/HEIC/AVIF (ISO base media file, see [`crate::heif`]): the `Exif` item's TIFF stream and the XMP //! `mime` item. -use lightcraft_tiff::{Tiff, tags}; +use craft_tiff::{Tiff, tags}; /// Metadata blocks found in a file. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -71,8 +71,8 @@ pub fn embedded(bytes: &[u8]) -> Embedded { xmp_extended: None, icc: ifd0.bytes(tags::ICC_PROFILE).map(|b| b.to_vec()), iptc: ifd0.value(tags::IPTC_NAA).map(|v| match v { - lightcraft_tiff::Value::Byte(b) | lightcraft_tiff::Value::Undefined(b) => b.clone(), - other => lightcraft_tiff::writer::encode(t.order, other), + craft_tiff::Value::Byte(b) | craft_tiff::Value::Undefined(b) => b.clone(), + other => craft_tiff::writer::encode(t.order, other), }), } } else { @@ -275,7 +275,7 @@ pub fn webp_chunks(b: &[u8]) -> Embedded { mod tests { use super::*; use crate::exif::tests::sample_exif; - use lightcraft_tiff::ByteOrder; + use craft_tiff::ByteOrder; fn seg(marker: u8, payload: &[u8]) -> Vec { let mut v = vec![0xff, marker]; diff --git a/crates/meta/src/cr3.rs b/crates/meta/src/cr3.rs index a95b8baada..0a90f733e9 100644 --- a/crates/meta/src/cr3.rs +++ b/crates/meta/src/cr3.rs @@ -436,13 +436,13 @@ fn le32(b: &[u8], at: usize) -> Option { /// Merge `CMT1` (IFD0), `CMT2` (Exif) and `CMT4` (GPS) into one TIFF stream, so the Exif readers see a CR3 /// like any TIFF-based raw. The maker note (`CMT3`) is left out: its offsets are relative to its own block. pub fn merged_exif(c: &Cr3<'_>) -> Option> { - use lightcraft_tiff::{IfdBuilder, Tiff, TiffWriter, tags as t}; + use craft_tiff::{IfdBuilder, Tiff, TiffWriter, tags as t}; let ifd0 = Tiff::parse(c.cmt[0]?).ok()?; let order = ifd0.order; let first = |i: usize| c.cmt[i].and_then(|b| Tiff::parse(b).ok()).and_then(|t| t.ifds.into_iter().next()); // pointers and offsets that would dangle once the IFDs move const SKIP: [u16; 9] = [t::EXIF_IFD, t::GPS_IFD, t::INTEROP_IFD, t::SUB_IFDS, t::MAKER_NOTE, 273, 279, 513, 514]; - let build = |ifd: &lightcraft_tiff::Ifd| { + let build = |ifd: &craft_tiff::Ifd| { let mut b = IfdBuilder::new(); for e in ifd.entries.iter().filter(|e| !SKIP.contains(&e.tag)) { b.set(e.tag, e.value.clone()); @@ -497,14 +497,14 @@ mod tests { let stbl = [full(b"stsd", &stsd), full(b"stsz", &stsz), full(b"co64", &co64)].concat(); bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl)))) } - fn tiff_with(tag: u16, v: lightcraft_tiff::Value) -> Vec { - let b = lightcraft_tiff::IfdBuilder::new().with(tag, v); - lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[b]).unwrap() + fn tiff_with(tag: u16, v: craft_tiff::Value) -> Vec { + let b = craft_tiff::IfdBuilder::new().with(tag, v); + craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[b]).unwrap() } /// A small synthetic CR3: Canon uuid with CMT1/CMT2/CMT4, a JPEG track, a raw track, XMP. pub(crate) fn sample() -> Vec { - use lightcraft_tiff::{Value, tags as t}; + use craft_tiff::{Value, tags as t}; let cmt1 = tiff_with(t::MODEL, Value::Ascii("Canon EOS Test".into())); let cmt2 = tiff_with(t::ISO_SPEED, Value::Short(vec![400])); let cmt4 = tiff_with(1, Value::Ascii("N".into())); @@ -689,7 +689,7 @@ mod tests { #[test] fn timed_metadata_exposes_the_dynamic_maker_note() { - use lightcraft_tiff::{Value, tags as t}; + use craft_tiff::{Value, tags as t}; let exif = tiff_with(t::ISO_SPEED, Value::Short(vec![800])); let maker = tiff_with(0x4001, Value::Short(vec![48, 100, 200])); let item = |tag: u32, data: &[u8]| { diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index 9894f016ba..7602e115de 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -1,7 +1,7 @@ //! Exif / TIFF tags → [`Metadata`] (CIPA DC-008 Exif 2.32, TIFF 6.0, DNG 1.7 tag semantics). use crate::{DateTime, Flash, Gps, Metadata, Orientation}; -use lightcraft_tiff::{Ifd, ParseOptions, Tiff, TiffError, tags as t}; +use craft_tiff::{Ifd, ParseOptions, Tiff, TiffError, tags as t}; /// Strip an `Exif\0\0` (or `Exif\0\xff`) prefix as found in JPEG APP1 and some WebP `EXIF` chunks. pub fn strip_exif_header(b: &[u8]) -> &[u8] { @@ -129,8 +129,8 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata { if let Some(iptc) = ifd0.and_then(|i| i.value(t::IPTC_NAA)) { // IPTC-NAA is often typed LONG; re-serialise to bytes in file order. let bytes = match iptc { - lightcraft_tiff::Value::Byte(b) | lightcraft_tiff::Value::Undefined(b) => b.clone(), - other => lightcraft_tiff::writer::encode(tiff.order, other), + craft_tiff::Value::Byte(b) | craft_tiff::Value::Undefined(b) => b.clone(), + other => craft_tiff::writer::encode(tiff.order, other), }; m.fill_missing(&crate::parse_iptc(&bytes)); } @@ -200,7 +200,7 @@ fn panasonic_lens(data: &[u8], tiff: &Tiff) -> Option { } let e = exif.get(t::MAKER_NOTE)?; let make = tiff.ifds.first().and_then(|i| i.string(t::MAKE)).unwrap_or_default(); - let mn = lightcraft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?; + let mn = craft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?; text(Some(&mn.ifd), PANASONIC_LENS_TYPE) } @@ -225,7 +225,7 @@ fn canon_maker_note_lens(data: &[u8], tiff: &Tiff) -> Option { } let exif = tiff.exif()?; let e = exif.get(t::MAKER_NOTE)?; - let mn = lightcraft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?; + let mn = craft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?; text(Some(&mn.ifd), CANON_LENS_MODEL) } @@ -234,13 +234,13 @@ fn canon_maker_note_lens(data: &[u8], tiff: &Tiff) -> Option { const NIKON_LENS: u16 = 0x0084; /// The lens a Nikon camera records in its maker note, when it's plausible. -fn nikon_lens_spec(exif: Option<&Ifd>, make: Option<&str>, order: lightcraft_tiff::ByteOrder) -> Option<[f64; 4]> { +fn nikon_lens_spec(exif: Option<&Ifd>, make: Option<&str>, order: craft_tiff::ByteOrder) -> Option<[f64; 4]> { let make = make?; if !make.trim().to_ascii_uppercase().starts_with("NIKON") { return None; } let note = exif?.bytes(t::MAKER_NOTE)?; - let mn = lightcraft_tiff::makernote::parse_makernote(note, 0, note.len() as u64, order, make)?; + let mn = craft_tiff::makernote::parse_makernote(note, 0, note.len() as u64, order, make)?; let s = mn.ifd.f64s(NIKON_LENS)?; let [short, long, wide, narrow] = s.as_slice() else { return None }; let focal = |f: f64| f.is_finite() && f > 0.0 && f < 10_000.0; @@ -251,7 +251,7 @@ fn nikon_lens_spec(exif: Option<&Ifd>, make: Option<&str>, order: lightcraft_tif #[cfg(test)] pub(crate) mod tests { use super::*; - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; fn capture_time_tiff(original: Option<&str>, digitized: Option<&str>, ifd0_time: Option<&str>, xmp: Option<&str>) -> Vec { let mut exif = IfdBuilder::new(); @@ -602,19 +602,19 @@ pub(crate) mod tests { } /// An exact `1/N` rational for a sub-second value whose reciprocal is a whole number (shutter speeds such as -/// 1/12800 s, which [`lightcraft_tiff::writer::rational`]'s decimal denominators cannot represent). -fn reciprocal(v: Option) -> Option { +/// 1/12800 s, which [`craft_tiff::writer::rational`]'s decimal denominators cannot represent). +fn reciprocal(v: Option) -> Option { let v = v.filter(|v| v.is_finite() && *v > 0.0 && *v < 1.0)?; let inv = 1.0 / v; - ((inv - inv.round()).abs() < 1e-6 && inv.round() <= u32::MAX as f64).then(|| lightcraft_tiff::Value::Rational(vec![(1, inv.round() as u32)])) + ((inv - inv.round()).abs() < 1e-6 && inv.round() <= u32::MAX as f64).then(|| craft_tiff::Value::Rational(vec![(1, inv.round() as u32)])) } /// Serialise the interchange subset of `meta` as a TIFF-structured Exif block (little-endian, no /// `Exif\0\0` prefix): IFD0 (make, model, software, artist, copyright, description, orientation, /// date), the Exif IFD (capture settings, lens) and, when present, the GPS IFD. pub fn write_exif(meta: &Metadata) -> Vec { - use lightcraft_tiff::writer::{rational, srational}; - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + use craft_tiff::writer::{rational, srational}; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; let ascii = |s: &Option| s.as_ref().filter(|v| !v.is_empty()).map(|v| Value::Ascii(v.clone())); let mut ifd0 = IfdBuilder::new(); for (tag, v) in [ diff --git a/crates/meta/src/focus.rs b/crates/meta/src/focus.rs index 5107829989..b956e667ed 100644 --- a/crates/meta/src/focus.rs +++ b/crates/meta/src/focus.rs @@ -31,7 +31,7 @@ pub use crate::focus_read::{HEADER_PREFIX, HeaderRead, MAX_HEADER_BYTES, read_header}; use crate::{Orientation, Rect}; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t}; +use craft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t}; use serde::{Deserialize, Serialize}; /// Where the camera focused, on the upright photo. diff --git a/crates/meta/src/focus/tests.rs b/crates/meta/src/focus/tests.rs index e5f79fbfe5..148f5ed999 100644 --- a/crates/meta/src/focus/tests.rs +++ b/crates/meta/src/focus/tests.rs @@ -1,5 +1,5 @@ use super::*; -use lightcraft_tiff::{Entry, IfdBuilder, TiffWriter, Value}; +use craft_tiff::{Entry, IfdBuilder, TiffWriter, Value}; fn encipher(p: u8) -> u8 { if p >= 249 { p } else { ((u32::from(p).pow(3)) % 249) as u8 } @@ -206,7 +206,7 @@ fn sony_file_with(make: &str, model: &str, orientation: u16, note_entries: &[(u1 let mut outside: Vec = Vec::new(); order.put_u16(&mut note, note_entries.len() as u16); for (tag, v) in note_entries { - let raw = lightcraft_tiff::writer::encode(order, v); + let raw = craft_tiff::writer::encode(order, v); order.put_u16(&mut note, *tag); order.put_u16(&mut note, v.field_type() as u16); order.put_u32(&mut note, v.count() as u32); diff --git a/crates/meta/src/focus_read.rs b/crates/meta/src/focus_read.rs index 65adbee754..14547b051e 100644 --- a/crates/meta/src/focus_read.rs +++ b/crates/meta/src/focus_read.rs @@ -14,7 +14,7 @@ use std::io; use crate::focus::FocusPoint; -use lightcraft_tiff::{ByteOrder, FieldType, Tiff, tags as t}; +use craft_tiff::{ByteOrder, FieldType, Tiff, tags as t}; /// Bytes read first: the α1's and A7S III's focus data ends before 16 KB, so one read covers it. pub const HEADER_PREFIX: u64 = 32 * 1024; @@ -176,8 +176,7 @@ fn tiff(r: &mut Reader, head: Vec) -> io::Result> { // file length: only the loaded ranges are data, and an unrelated entry that claims a // huge value must be cut by what leaving it cost, not by what the buffer claims to hold. // The same 8 × / + 1 MiB shape the general TIFF reader uses, over `reader.bytes` instead. - let opts = - lightcraft_tiff::ParseOptions { value_budget: Some(r.bytes.saturating_mul(8).saturating_add(1 << 20)), ..Default::default() }; + let opts = craft_tiff::ParseOptions { value_budget: Some(r.bytes.saturating_mul(8).saturating_add(1 << 20)), ..Default::default() }; return Ok(crate::try_read_exif_with(&buf, &opts).ok().and_then(|m| m.focus)); } Step::Nothing => return Ok(None), @@ -354,7 +353,7 @@ impl Want<'_> { /// What of a classic TIFF the focus decoder still needs, given what is `loaded`: IFD0 (Make, Model, /// the Exif pointer), the Exif IFD (the maker-note entry), the maker note's header and IFD as -/// `lightcraft_tiff::makernote` locates it, and the focus tags' values. +/// `craft_tiff::makernote` locates it, and the focus tags' values. fn plan(buf: &[u8], loaded: &Loaded) -> Step { let Some((order, false)) = Tiff::sniff(buf) else { return Step::Nothing }; let mut w = Want { buf, order, loaded, need: Vec::new() }; diff --git a/crates/meta/src/heif.rs b/crates/meta/src/heif.rs index 1d768f7a69..ce3a133831 100644 --- a/crates/meta/src/heif.rs +++ b/crates/meta/src/heif.rs @@ -198,7 +198,7 @@ mod tests { use super::*; // the whole routing, not just this module: a HEIC must reach the HEIF branch of `embedded` use crate::embedded; - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; /// One box: its own size, its four-letter kind, then its payload. fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 91186e3d8c..4844168119 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -555,7 +555,7 @@ mod tests { j.extend(payload); }; // orientation 6, 6000 × 4000 as stored - seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(lightcraft_tiff::ByteOrder::Little)].concat()); + seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(craft_tiff::ByteOrder::Little)].concat()); seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat()); j.extend([0xff, 0xd9]); j @@ -600,10 +600,10 @@ mod tests { assert!(near(m.regions[0].rect, DRAWN), "{:?}", m.regions[0].rect); assert_eq!(try_extract(&j).unwrap().regions, m.regions); // a TIFF-based file: the whole file is the Exif block, with the XMP in its first IFD - let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); - ifd0.set(lightcraft_tiff::tags::ORIENTATION, lightcraft_tiff::Value::Short(vec![6])); - ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes())); - let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); + let mut ifd0 = craft_tiff::IfdBuilder::new(); + ifd0.set(craft_tiff::tags::ORIENTATION, craft_tiff::Value::Short(vec![6])); + ifd0.set(craft_tiff::tags::XMP, craft_tiff::Value::Byte(packet.into_bytes())); + let m = extract(&craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000))); assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect); } @@ -615,14 +615,14 @@ mod tests { fn an_orientation_only_the_xmp_states_turns_no_regions() { // 6000 × 4000 in the Exif, and no orientation let size_ifd = || { - let mut sub = lightcraft_tiff::IfdBuilder::new(); - sub.set(lightcraft_tiff::tags::PIXEL_X_DIMENSION, lightcraft_tiff::Value::Long(vec![6000])); - sub.set(lightcraft_tiff::tags::PIXEL_Y_DIMENSION, lightcraft_tiff::Value::Long(vec![4000])); + let mut sub = craft_tiff::IfdBuilder::new(); + sub.set(craft_tiff::tags::PIXEL_X_DIMENSION, craft_tiff::Value::Long(vec![6000])); + sub.set(craft_tiff::tags::PIXEL_Y_DIMENSION, craft_tiff::Value::Long(vec![4000])); sub }; - let mut exif_ifd0 = lightcraft_tiff::IfdBuilder::new(); - exif_ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd()); - let exif = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[exif_ifd0]).unwrap(); + let mut exif_ifd0 = craft_tiff::IfdBuilder::new(); + exif_ifd0.set_child(craft_tiff::tags::EXIF_IFD, size_ifd()); + let exif = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[exif_ifd0]).unwrap(); let packet = regions_packet(6000, 4000, "") .replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#); let mut j = vec![0xff, 0xd8]; @@ -641,10 +641,10 @@ mod tests { assert!(near(m.regions[0].rect, DRAWN), "turned by an orientation the Exif doesn't state: {:?}", m.regions[0].rect); assert_eq!(try_extract(&j).unwrap().regions, m.regions); // a TIFF-based file: the first IFD has no orientation, its XMP (tag 700) has - let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); - ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes())); - ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd()); - let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); + let mut ifd0 = craft_tiff::IfdBuilder::new(); + ifd0.set(craft_tiff::tags::XMP, craft_tiff::Value::Byte(packet.into_bytes())); + ifd0.set_child(craft_tiff::tags::EXIF_IFD, size_ifd()); + let m = extract(&craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap()); assert_eq!(m.orientation, Some(Orientation::Rotate90)); assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect); } diff --git a/crates/meta/src/psd.rs b/crates/meta/src/psd.rs index bda16d9602..ebdbdaf723 100644 --- a/crates/meta/src/psd.rs +++ b/crates/meta/src/psd.rs @@ -177,9 +177,9 @@ mod tests { #[test] fn try_extract_accepts_unknown_exif_tags_in_psd() { - let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); - ifd0.set(0xc001, lightcraft_tiff::Value::Ascii("vendor metadata".into())); - let exif = lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap(); + let mut ifd0 = craft_tiff::IfdBuilder::new(); + ifd0.set(0xc001, craft_tiff::Value::Ascii("vendor metadata".into())); + let exif = craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap(); let file = image(1, &[], &resource(1058, b"", &exif)); assert!(crate::try_extract(&file).is_ok()); } diff --git a/crates/meta/src/tags.rs b/crates/meta/src/tags.rs index 643d0fb28d..e16e5663a4 100644 --- a/crates/meta/src/tags.rs +++ b/crates/meta/src/tags.rs @@ -4,7 +4,7 @@ //! binary blobs are summarised by size; of a maker note only the lens name is listed (the //! Panasonic one, as Panasonic writes no Exif LensModel). -use lightcraft_tiff::{Ifd, Tiff, Value}; +use craft_tiff::{Ifd, Tiff, Value}; /// One metadata row. #[derive(Clone, Debug, PartialEq)] @@ -318,7 +318,7 @@ fn nikon_nef_compression(tiff: &Tiff, bytes: &[u8]) -> Option<&'static str> { return None; } let e = ifd0.exif.as_ref()?.get(0x927c)?; - let mn = lightcraft_tiff::makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)?; + let mn = craft_tiff::makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)?; nef_compression(mn.ifd.u32(0x0093)?) } @@ -516,7 +516,7 @@ mod tests { let rw2 = crate::exif::tests::panasonic_rw2("LUMIX S 85/F1.8"); assert_eq!(lens(&file_tag_rows(&rw2)), ["LUMIX S 85/F1.8"]); // a JPEG: the note is in its own Exif - let exif = crate::exif::tests::panasonic_exif(lightcraft_tiff::ByteOrder::Big, Some("LUMIX G 25/F1.7"), None); + let exif = crate::exif::tests::panasonic_exif(craft_tiff::ByteOrder::Big, Some("LUMIX G 25/F1.7"), None); let mut jpg = vec![0xff, 0xd8, 0xff, 0xe1]; jpg.extend_from_slice(&((exif.len() + 8) as u16).to_be_bytes()); jpg.extend(b"Exif\0\0"); diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 958abed653..705c8ee29b 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -633,12 +633,12 @@ fn frac(v: f64) -> String { return format!("1/{}", inv.round() as u64); } } - let (n, d) = lightcraft_tiff::writer::rational(v); + let (n, d) = craft_tiff::writer::rational(v); format!("{n}/{d}") } fn sfrac(v: f64) -> String { - let (n, d) = lightcraft_tiff::writer::srational(v); + let (n, d) = craft_tiff::writer::srational(v); format!("{n}/{d}") } diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml index 50ecfc3719..18bf6d76c2 100644 --- a/crates/raw/Cargo.toml +++ b/crates/raw/Cargo.toml @@ -9,7 +9,7 @@ description = "LightCraft RAW decoding, demosaicing and DNG colour model (L1)" workspace = true [dependencies] -lightcraft-tiff = { workspace = true } +craft-tiff = { workspace = true } lightcraft-meta = { workspace = true } lightcraft-raster = { workspace = true } lightcraft-color = { workspace = true } diff --git a/crates/raw/examples/rawinfo.rs b/crates/raw/examples/rawinfo.rs index 23e540b965..2271aa0bd2 100644 --- a/crates/raw/examples/rawinfo.rs +++ b/crates/raw/examples/rawinfo.rs @@ -3,8 +3,8 @@ //! Prints the TIFF structure (with `--tree`), decode result, timings (MP/s) and basic statistics. //! Exits unsuccessfully if any input cannot be read, decoded or developed, while inspecting the remaining files. +use craft_tiff::{Ifd, Tiff, Value}; use lightcraft_raw::{Method, RawData, decode, embedded_preview, probe}; -use lightcraft_tiff::{Ifd, Tiff, Value}; use std::process::ExitCode; use std::time::Instant; diff --git a/crates/raw/examples/rawrender.rs b/crates/raw/examples/rawrender.rs index abb1fe7c94..c1715a9ced 100644 --- a/crates/raw/examples/rawrender.rs +++ b/crates/raw/examples/rawrender.rs @@ -2,9 +2,9 @@ //! //! Quick visual check: develop → as-shot WB + camera matrix → sRGB, oriented, box-downscaled, 8-bit TIFF. +use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags}; use lightcraft_color::{REC2020, SRGB, transfer::encode_srgb8}; use lightcraft_raw::{Method, color, decode}; -use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags}; fn main() { let a: Vec = std::env::args().skip(1).collect(); diff --git a/crates/raw/src/dcp.rs b/crates/raw/src/dcp.rs index 774b1ceab1..a577fbe4e5 100644 --- a/crates/raw/src/dcp.rs +++ b/crates/raw/src/dcp.rs @@ -4,7 +4,7 @@ //! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the //! hue/saturation map, look table and tone curve. Nothing here ships a profile. -use lightcraft_tiff::{Ifd, ParseOptions, Tiff, tags as t}; +use craft_tiff::{Ifd, ParseOptions, Tiff, tags as t}; use crate::ColorData; use crate::dng::color_data; @@ -118,8 +118,8 @@ pub fn parse_dcp(bytes: &[u8]) -> Result { /// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation /// map, look table, tone curve and baseline exposure offset. pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { - use lightcraft_tiff::writer::srational; - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + use craft_tiff::writer::srational; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; let c = &p.color; let mut ifd = IfdBuilder::new(); ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone())); diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs index bbea2c8c1a..c156e8f4cb 100644 --- a/crates/raw/src/dng.rs +++ b/crates/raw/src/dng.rs @@ -5,10 +5,10 @@ use crate::gaintable::GainTableMap; use crate::profile::{HsvTable, ProfileLook, ToneCurve}; use crate::tiffraw::{Packing, read_image_in}; use crate::{BlackLevel, Cfa, ColorData, Mat3, Mode, RawData, RawError, RawFormat, RawImage, Rect, Result, opcodes}; +use craft_tiff::tags::{self as t, photometric}; +use craft_tiff::{ByteOrder, Ifd, Tiff}; use lightcraft_color::Xy; use lightcraft_geom::Orientation; -use lightcraft_tiff::tags::{self as t, photometric}; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff}; /// The main raw IFD: full-resolution (NewSubfileType 0) CFA or LinearRaw image with the most pixels. pub(crate) fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> { @@ -183,7 +183,7 @@ pub(crate) fn is_plain_cfa_tiff(tiff: &Tiff, bytes: &[u8]) -> bool { t::compression::JPEG => info .chunks(bytes.len() as u64) .first() - .and_then(|c| lightcraft_tiff::image::chunk_bytes(bytes, c)) + .and_then(|c| craft_tiff::image::chunk_bytes(bytes, c)) .is_some_and(|src| crate::ljpeg::frame_info(src).is_ok()), _ => false, } diff --git a/crates/raw/src/dngwrite.rs b/crates/raw/src/dngwrite.rs index bdafb58658..9ab24b5cdb 100644 --- a/crates/raw/src/dngwrite.rs +++ b/crates/raw/src/dngwrite.rs @@ -2,10 +2,10 @@ //! bit-exact decoder round-trip tests. The raw image is stored in IFD0 (allowed by DNG 1.7 §"File Structure"). use crate::{RawData, RawError, RawImage, Result, ljpeg, opcodes}; +use craft_tiff::tags::{self as t, compression, photometric}; +use craft_tiff::writer::{rational, srational}; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; use lightcraft_color::Mat3; -use lightcraft_tiff::tags::{self as t, compression, photometric}; -use lightcraft_tiff::writer::{rational, srational}; -use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; use rayon::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/raw/src/gaintable.rs b/crates/raw/src/gaintable.rs index cec1d6828d..c6a1b4c91e 100644 --- a/crates/raw/src/gaintable.rs +++ b/crates/raw/src/gaintable.rs @@ -40,7 +40,7 @@ //! `MapPointsV` / `MapPointsH` is below 256 (their product is at most [`MAX_TABLES`]), so swapped //! it is at least 2^24 and the size checks reject it. We write in the file's byte order. -use lightcraft_tiff::ByteOrder; +use craft_tiff::ByteOrder; use serde::{Deserialize, Serialize}; /// Upper bound on `MapPointsV × MapPointsH` (Apple uses 6 × 8). diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index ff9ee048b7..f246612cae 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -70,8 +70,8 @@ pub use preview::{ }; pub use semantic::{SemanticMask, semantic_masks}; +use craft_tiff::{Tiff, TiffError}; use lightcraft_color::Xy; -use lightcraft_tiff::{Tiff, TiffError}; use serde::{Deserialize, Serialize}; /// Upper bound on decoded samples (guards allocations driven by header values). @@ -189,28 +189,28 @@ pub fn probe(bytes: &[u8]) -> Option { return Some(RawFormat::Cr2); } let (_, _) = Tiff::sniff(bytes)?; - let opts = lightcraft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }; + let opts = craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }; let t = Tiff::parse_with(bytes, &opts).ok()?; let ifd0 = t.ifds.first()?; - if ifd0.contains(lightcraft_tiff::tags::DNG_VERSION) { + if ifd0.contains(craft_tiff::tags::DNG_VERSION) { return Some(RawFormat::Dng); } - let make = t.find(lightcraft_tiff::tags::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default().to_ascii_uppercase(); + let make = t.find(craft_tiff::tags::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default().to_ascii_uppercase(); let has_cfa = has_raw_ifd(&t); // Pentax's reader takes the layout from the Exif `CFAPattern` when no IFD has a CFA photometric (uncompressed // and PackBits PEFs), so for the Pentax family that tag counts as raw evidence too let pentax_raw = has_cfa || t.exif().is_some_and(|e| e.contains(vendor::EXIF_CFA_PATTERN)); // Samsung's raw IFD uses private compressions 32769..=32773 (`vendor::srw`), 32773 being PackBits elsewhere - let samsung_raw = has_cfa || t.all_ifds().iter().any(|i| i.u16(lightcraft_tiff::tags::COMPRESSION).is_some_and(|c| (32769..=32773).contains(&c))); + let samsung_raw = has_cfa || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| (32769..=32773).contains(&c))); // Sony raws without a CFA IFD (#702): SRF (DSC-F828), whose IFD0 looks like RGB but holds 14-bit samples (12 or // 14 count: raw sensor depths; the raw is in Sony's SRF blocks), and the DSLR-A100, whose IFD0 is an old-style // JPEG thumbnail (compression 6, which today's TIFF writers don't produce) and whose `SubIFDs` tag addresses its // raw data. A camera-authored or exported TIFF has 8- or 16-bit samples, and its SubIFDs hold ordinary images - let model = t.find(lightcraft_tiff::tags::MODEL).and_then(|e| e.value.as_str()).unwrap_or_default().trim().to_ascii_uppercase(); + let model = t.find(craft_tiff::tags::MODEL).and_then(|e| e.value.as_str()).unwrap_or_default().trim().to_ascii_uppercase(); let sony_raw = has_cfa - || ifd0.u64s(lightcraft_tiff::tags::BITS_PER_SAMPLE).is_some_and(|b| b.iter().any(|v| matches!(v, 12 | 14))) - || (model == "DSLR-A100" && ifd0.u16(lightcraft_tiff::tags::COMPRESSION) == Some(6) && ifd0.contains(lightcraft_tiff::tags::SUB_IFDS)); - if make.starts_with("CANON") && t.ifds.len() >= 4 && t.ifds[3].u16(lightcraft_tiff::tags::COMPRESSION) == Some(6) { + || ifd0.u64s(craft_tiff::tags::BITS_PER_SAMPLE).is_some_and(|b| b.iter().any(|v| matches!(v, 12 | 14))) + || (model == "DSLR-A100" && ifd0.u16(craft_tiff::tags::COMPRESSION) == Some(6) && ifd0.contains(craft_tiff::tags::SUB_IFDS)); + if make.starts_with("CANON") && t.ifds.len() >= 4 && t.ifds[3].u16(craft_tiff::tags::COMPRESSION) == Some(6) { return Some(RawFormat::Cr2); } if make.starts_with("NIKON") && has_cfa { @@ -218,7 +218,7 @@ pub fn probe(bytes: &[u8]) -> Option { } // Hasselblad's Sony-built bodies (the Lunar is a NEX-7 inside) write a Sony ARW under their own Make. Sony's // raw coding gives them away: compression 32767 or the raw IFD's tone-curve tag 0x7010, which no 3FR / FFF has - let sony_coded = || t.all_ifds().iter().any(|i| i.u16(lightcraft_tiff::tags::COMPRESSION) == Some(32767) || i.contains(0x7010)); + let sony_coded = || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION) == Some(32767) || i.contains(0x7010)); if (make.starts_with("SONY") && sony_raw) || (make.starts_with("HASSELBLAD") && sony_coded()) { return Some(RawFormat::Arw); } @@ -257,13 +257,13 @@ const LEAF_DATA: u16 = 0x8606; /// An uncompressed Leaf MOS: IFD0 is the 16-bit mosaic itself (compression 1, BlackIsZero, one sample per pixel), /// with no Make tag and no CFA photometric, so only Leaf's data block marks it as a raw (issue #1275). A rendered /// RGB image that kept the block stays an ordinary image. -fn is_leaf_mosaic(ifd0: &lightcraft_tiff::Ifd) -> bool { - ifd0.contains(LEAF_DATA) && ifd0.u16(lightcraft_tiff::tags::SAMPLES_PER_PIXEL).unwrap_or(1) == 1 +fn is_leaf_mosaic(ifd0: &craft_tiff::Ifd) -> bool { + ifd0.contains(LEAF_DATA) && ifd0.u16(craft_tiff::tags::SAMPLES_PER_PIXEL).unwrap_or(1) == 1 } /// Whether the Exif maker note starts with the signature of the Pentax layouts (`AOC\0` or `PENTAX \0`). fn has_pentax_maker_note(t: &Tiff, bytes: &[u8]) -> bool { - let Some(e) = t.exif().and_then(|e| e.get(lightcraft_tiff::tags::MAKER_NOTE)) else { return false }; + let Some(e) = t.exif().and_then(|e| e.get(craft_tiff::tags::MAKER_NOTE)) else { return false }; bytes.get(e.offset as usize..).is_some_and(|n| n.starts_with(b"AOC\0") || n.starts_with(b"PENTAX \0")) } @@ -272,19 +272,19 @@ fn has_pentax_maker_note(t: &Tiff, bytes: &[u8]) -> bool { /// or vendor-specific raw tags (Sony tone curve, CFA pattern, or Pentax compression 65535). fn has_raw_ifd(t: &Tiff) -> bool { t.all_ifds().iter().any(|i| { - i.u16(lightcraft_tiff::tags::PHOTOMETRIC) == Some(lightcraft_tiff::tags::photometric::CFA) - || i.u16(lightcraft_tiff::tags::COMPRESSION).is_some_and(|c| matches!(c, 34713 | 32767 | 32769 | 32770 | 99 | 65535)) + i.u16(craft_tiff::tags::PHOTOMETRIC) == Some(craft_tiff::tags::photometric::CFA) + || i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| matches!(c, 34713 | 32767 | 32769 | 32770 | 99 | 65535)) || i.contains(0x7010) - || i.contains(lightcraft_tiff::tags::CFA_PATTERN_EP) - || i.contains(lightcraft_tiff::tags::CFA_REPEAT_PATTERN_DIM) + || i.contains(craft_tiff::tags::CFA_PATTERN_EP) + || i.contains(craft_tiff::tags::CFA_REPEAT_PATTERN_DIM) }) } /// IFD0 that is not an image at all: no `ImageWidth` / `ImageLength`, but a JPEG preview pointer or /// `SubIFDs` (the layout of Kodak KDC files, whose pictures sit in private tags). A plain TIFF reader /// rejects such a file as malformed even though it carries a preview. -fn is_preview_container(ifd0: &lightcraft_tiff::Ifd) -> bool { - use lightcraft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, JPEG_INTERCHANGE_FORMAT, SUB_IFDS}; +fn is_preview_container(ifd0: &craft_tiff::Ifd) -> bool { + use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, JPEG_INTERCHANGE_FORMAT, SUB_IFDS}; !ifd0.contains(IMAGE_WIDTH) && !ifd0.contains(IMAGE_LENGTH) && (ifd0.contains(JPEG_INTERCHANGE_FORMAT) || ifd0.contains(SUB_IFDS)) } @@ -309,7 +309,7 @@ pub(crate) struct ThumbnailShell { /// A multi-page TIFF is not caught (its pages are the IFD chain, not `SubIFDs`), nor a pyramid whose /// IFD0 is the full image. fn thumbnail_shell(t: &Tiff, len: usize) -> Option { - use lightcraft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, PIXEL_X_DIMENSION, PIXEL_Y_DIMENSION}; + use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, PIXEL_X_DIMENSION, PIXEL_Y_DIMENSION}; let ifd0 = t.ifds.first()?; let (w0, h0) = (ifd0.u32(IMAGE_WIDTH)?, ifd0.u32(IMAGE_LENGTH)?); if w0 == 0 || h0 == 0 { @@ -352,12 +352,12 @@ fn thumbnail_shell(t: &Tiff, len: usize) -> Option { /// Why [`decode`] gives up on a file [`probe`] called [`RawFormat::OtherTiff`]. fn other_tiff_reason(bytes: &[u8]) -> String { - let t = Tiff::parse_with(bytes, &lightcraft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }).ok(); + let t = Tiff::parse_with(bytes, &craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }).ok(); // a DNG-style CFA IFD whose lossless JPEG the lossless decoder rejects: say why if let Some(t) = &t && let Some(info) = dng::raw_ifd(t).and_then(|i| i.image().ok()) - && info.compression == lightcraft_tiff::tags::compression::JPEG - && let Some(src) = info.chunks(bytes.len() as u64).first().and_then(|c| lightcraft_tiff::image::chunk_bytes(bytes, c)) + && info.compression == craft_tiff::tags::compression::JPEG + && let Some(src) = info.chunks(bytes.len() as u64).first().and_then(|c| craft_tiff::image::chunk_bytes(bytes, c)) && let Err(e) = ljpeg::frame_info(src) { return format!("raw image coded as lossless JPEG that is not decoded yet ({e})"); diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index d661439780..85c257f162 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -3,9 +3,9 @@ //! or a DNG 1.7 JPEG XL preview IFD stored as a single tile/strip (a standalone `.jxl` file, as the spec //! recommends for previews). -use lightcraft_tiff::image::chunk_bytes; -use lightcraft_tiff::tags as t; -use lightcraft_tiff::{Ifd, Tiff, makernote}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::tags as t; +use craft_tiff::{Ifd, Tiff, makernote}; /// Colour space of an embedded JPEG when the enclosing raw supplies it instead of the JPEG. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -197,7 +197,7 @@ fn jpeg_end(s: &[u8], budget: &mut usize) -> Option { fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>, budget: &mut usize) { // whole JPEG files stored as an undefined-type tag value (e.g. Panasonic `JpgFromRaw` 0x002e) for e in &ifd.entries { - if matches!(e.value, lightcraft_tiff::Value::Undefined(_)) + if matches!(e.value, craft_tiff::Value::Undefined(_)) && e.count() > 1024 && let Some(s) = file_span(data, e.offset, e.count() as u64, budget) && s.starts_with(&[0xff, 0xd8]) @@ -304,7 +304,7 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { if let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make) { candidates(bytes, &mn.ifd, mn.base, &mut found, &mut budget); if let Some(off) = mn.ifd.u64(0x0011) - && let Ok((pifd, _)) = lightcraft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default()) + && let Ok((pifd, _)) = craft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default()) { candidates(bytes, &pifd, mn.base, &mut found, &mut budget); } diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index 561d39645d..924c4b4213 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -1,5 +1,5 @@ use super::*; -use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; +use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; fn fake_jpeg(n: usize) -> Vec { let mut j = vec![0xff, 0xd8, 0xff, 0xc0, 0x00, 0x0b, 8, 0, 1, 0, 1, 1, 1, 0x11, 0]; @@ -394,10 +394,9 @@ fn cr3_with_color_space(exif: Option, note: Option) -> Vec { let block = |tag: u16, v: Option| { let ifd = v.map_or_else(|| IfdBuilder::new().with(t::ISO_SPEED, Value::Short(vec![100])), |v| IfdBuilder::new().with(tag, Value::Short(vec![v]))); - TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap() + TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap() }; - let cmt1 = - TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[IfdBuilder::new().with(t::MAKE, Value::Ascii("Canon".into()))]).unwrap(); + let cmt1 = TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[IfdBuilder::new().with(t::MAKE, Value::Ascii("Canon".into()))]).unwrap(); let canon_uuid = [0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48]; let boxes = [bx(b"CMT1", &cmt1), bx(b"CMT2", &block(0xA001, exif)), bx(b"CMT3", &block(0x00b4, note))].concat(); let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); @@ -444,7 +443,7 @@ fn cr2_preview_colour_space_comes_from_the_canon_maker_note() { } let mut ifd0 = IfdBuilder::new().with(t::MAKE, Value::Ascii(make.into())); ifd0.set_child(t::EXIF_IFD, exif); - TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[ifd0]).unwrap() + TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd0]).unwrap() }; assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, Some(2))), Some(AdobeRgb)); assert_eq!(embedded_preview_color_space(&cr2("Canon", 1, Some(1))), Some(Srgb)); diff --git a/crates/raw/src/semantic.rs b/crates/raw/src/semantic.rs index e9af87c08a..fba28596e1 100644 --- a/crates/raw/src/semantic.rs +++ b/crates/raw/src/semantic.rs @@ -9,9 +9,9 @@ use crate::Rect; use crate::tiffraw::{Packing, read_image}; use crate::{RawData, Result}; +use craft_tiff::Tiff; +use craft_tiff::tags::{self as t, photometric}; use lightcraft_raster::Image; -use lightcraft_tiff::Tiff; -use lightcraft_tiff::tags::{self as t, photometric}; /// At most this many mask IFDs are read from one file. pub const MAX_MASKS: usize = 16; @@ -55,7 +55,7 @@ pub fn semantic_masks(bytes: &[u8]) -> Vec { .collect() } -fn read_mask(bytes: &[u8], tiff: &Tiff, ifd: &lightcraft_tiff::Ifd) -> Result> { +fn read_mask(bytes: &[u8], tiff: &Tiff, ifd: &craft_tiff::Ifd) -> Result> { let Some(name) = ifd.string(t::SEMANTIC_NAME).filter(|n| !n.is_empty()) else { return Ok(None) }; let info = ifd.image()?; let (w, h) = (info.width as usize, info.height as usize); diff --git a/crates/raw/src/sparse.rs b/crates/raw/src/sparse.rs index 893ba79b20..dd81263e58 100644 --- a/crates/raw/src/sparse.rs +++ b/crates/raw/src/sparse.rs @@ -19,8 +19,8 @@ use std::collections::HashSet; +use craft_tiff::{ByteOrder, FieldType, Tiff, tags as t}; use lightcraft_meta::cr3::{Cr3TrackKind, XMP_UUID, is_cr3, parse_cr3}; -use lightcraft_tiff::{ByteOrder, FieldType, Tiff, tags as t}; use crate::RawFormat; @@ -29,7 +29,7 @@ use crate::RawFormat; const HEAD: u64 = 64 * 1024; /// An image whose chunks hold fewer bytes than this is read (thumbnails, small previews). const BULK: u64 = 256 * 1024; -/// The same bounds as `lightcraft_tiff`'s reader. +/// The same bounds as `craft_tiff`'s reader. const MAX_IFDS: usize = 1024; const MAX_ENTRIES: u64 = 8192; const MAX_BOXES: usize = 4096; @@ -301,7 +301,7 @@ fn tiff_plan(bytes: &[u8], loaded: &Ranges, preview: bool) -> HeaderPlan { }) } -/// Walk the IFDs of the TIFF in `data` (which starts at `origin` in the file) as `lightcraft_tiff`'s +/// Walk the IFDs of the TIFF in `data` (which starts at `origin` in the file) as `craft_tiff`'s /// reader does — the chain, `SubIFDs`, Exif, GPS and Interop, plus the `extra` pointer tags — /// asking for every IFD table and for the values that locate IFDs and image chunks. Returns the IFD /// tables and out-of-line values found (absolute ranges); incomplete while `w` needs more. diff --git a/crates/raw/src/tests.rs b/crates/raw/src/tests.rs index e58991ccc8..0cff6f2006 100644 --- a/crates/raw/src/tests.rs +++ b/crates/raw/src/tests.rs @@ -120,7 +120,7 @@ fn black_levels() { // --- TIFF shells around a private raw block (thumbnail-only IFD0) --- -use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; +use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; /// An uncompressed 8-bit RGB image IFD. fn rgb_ifd(w: u32, h: u32) -> IfdBuilder { @@ -408,7 +408,7 @@ fn uncompressed_leaf_mos_is_a_raw() { } ifd }; - let bytes = TiffWriter::new(lightcraft_tiff::ByteOrder::Big, false).write(&[mosaic(true)]).unwrap(); + let bytes = TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[mosaic(true)]).unwrap(); assert_eq!(probe(&bytes), Some(RawFormat::OtherTiff)); assert!(matches!(decode(&bytes), Err(RawError::Unsupported(_)))); assert!(matches!(probe_info(&bytes), Err(RawError::Unsupported(_)))); diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index deb64ea595..50c13dae4f 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -2,8 +2,8 @@ use crate::unpack::{f16_to_f32, f24_to_f32, inflate, read_u16s, undo_diff_u16, undo_float_predictor, unpack_lsb, unpack_msb, unpack_words32_msb}; use crate::{MAX_SAMPLES, RawData, RawError, Result, ljpeg}; -use lightcraft_tiff::image::{Chunk, ImageInfo, chunk_bytes}; -use lightcraft_tiff::{ByteOrder, tags::compression as comp}; +use craft_tiff::image::{Chunk, ImageInfo, chunk_bytes}; +use craft_tiff::{ByteOrder, tags::compression as comp}; use rayon::prelude::*; /// Bit packing for uncompressed integer data with bit depths other than 8/16. @@ -439,7 +439,7 @@ fn unpack_chunk( #[cfg(test)] mod lossy_tests { use super::*; - use lightcraft_tiff::image::Layout; + use craft_tiff::image::Layout; /// 65 536 tiles all pointing at the same 256 bytes: the image's samples can't come from them, /// and nothing of its size is allocated to find that out. diff --git a/crates/raw/src/unpack.rs b/crates/raw/src/unpack.rs index 77c69c00d5..bf7040a8a7 100644 --- a/crates/raw/src/unpack.rs +++ b/crates/raw/src/unpack.rs @@ -4,7 +4,7 @@ //! predictor), DNG 1.7 (predictors 34892–34895, bit packing, 16/24-bit floats), RFC 1950/1951 (zlib/deflate). use crate::{RawError, Result}; -use lightcraft_tiff::ByteOrder; +use craft_tiff::ByteOrder; /// Unpack `out.len()` MSB-first packed samples of `bits` (1..=16) from `src` (TIFF bit order). pub fn unpack_msb(src: &[u8], bits: u32, out: &mut [u16]) { diff --git a/crates/raw/src/vendor.rs b/crates/raw/src/vendor.rs index a44262a2c4..dea94043e5 100644 --- a/crates/raw/src/vendor.rs +++ b/crates/raw/src/vendor.rs @@ -30,7 +30,7 @@ mod sr2; pub mod srw; use crate::{BlackLevel, Cfa, Rect}; -use lightcraft_tiff::Tiff; +use craft_tiff::Tiff; use std::ops::Range; /// Exif `CFAPattern`. @@ -247,7 +247,7 @@ pub(crate) fn declare_strip_len(file: &mut [u8], len: u32, declared: u32) { #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::tags as t; + use craft_tiff::tags as t; /// `file`, whose image IFD holds one strip, as two strips at the same offset whose StripByteCounts are LONG8 (which /// classic TIFF readers accept) `[u64::MAX, 1]`: their sum is past `u64::MAX`. diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index e260415648..950e3bec47 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -48,10 +48,10 @@ use super::arw6; use crate::lens_metadata::SonyLensGeometry; use crate::tiffraw::{Packing, check_image, read_image_in}; use crate::{BlackLevel, Cfa, ColorData, LensMetadata, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; +use craft_tiff::image::{Chunk, ImageInfo, Layout, chunk_bytes}; +use craft_tiff::tags::{self as t, photometric}; +use craft_tiff::{Ifd, Tiff, makernote}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::{Chunk, ImageInfo, Layout, chunk_bytes}; -use lightcraft_tiff::tags::{self as t, photometric}; -use lightcraft_tiff::{Ifd, Tiff, makernote}; use rayon::prelude::*; const TONE_CURVE: u16 = 0x7010; @@ -226,7 +226,7 @@ fn sony_body<'a>(make: &str, model: &'a str, mn: Option<&makernote::MakerNote>) /// White balance from the maker note's enciphered `Tag2010` block, the fallback described at [`TAG2010_WB`]. /// `model` is the Sony body ([`sony_body`]); Sony appends a regional "V" to some names (SLT-A77V), which the /// documented lists omit. -fn tag2010_wb(model: &str, block: &[u8], order: lightcraft_tiff::ByteOrder) -> Option<[f32; 3]> { +fn tag2010_wb(model: &str, block: &[u8], order: craft_tiff::ByteOrder) -> Option<[f32; 3]> { let model = model.trim(); let &(_, offset) = TAG2010_WB.iter().find(|(models, _)| models.iter().any(|m| model == *m || model.strip_suffix('V') == Some(*m)))?; let bytes: Vec = block.get(offset..offset + 6)?.iter().map(|&b| DECIPHER[b as usize]).collect(); @@ -523,7 +523,7 @@ fn sr2_old_crop(sr2: &super::sr2::SubIfd, w: usize, h: usize) -> Option { } /// One black level from the four deciphered per-channel levels (their mean), when they are near-equal and plausible. -fn sr2_black_levels(plain: &[u8], order: lightcraft_tiff::ByteOrder) -> Option { +fn sr2_black_levels(plain: &[u8], order: craft_tiff::ByteOrder) -> Option { let levels: Vec = (0..4).filter_map(|i| order.read_u16(plain, 2 * i)).collect(); let (&lo, &hi) = (levels.iter().min()?, levels.iter().max()?); (levels.len() == 4 && (64..=4096).contains(&lo) && hi - lo <= 64).then(|| levels.iter().map(|&v| f32::from(v)).sum::() / 4.0) @@ -532,8 +532,8 @@ fn sr2_black_levels(plain: &[u8], order: lightcraft_tiff::ByteOrder) -> Option lightcraft_tiff::ByteOrder { - use lightcraft_tiff::ByteOrder::{Big, Little}; +fn word16_order(strip: &[u8], bits: u32, file: craft_tiff::ByteOrder) -> craft_tiff::ByteOrder { + use craft_tiff::ByteOrder::{Big, Little}; let other = if file == Little { Big } else { Little }; let limit = 1u32 << bits.clamp(14, 16); let (mut n, mut over_file, mut over_other) = (0usize, 0usize, 0usize); @@ -836,7 +836,7 @@ mod tests { #[test] fn downsized_lossless_is_linear_rgb_not_cfa() { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let mut raw = IfdBuilder::new(); raw.set(t::MAKE, Value::Ascii("SONY".into())); raw.set(t::MODEL, Value::Ascii("ILCE-7M4".into())); @@ -894,7 +894,7 @@ mod tests { /// A 32767-compressed ARW whose single strip is `strip` bytes for a 32 x 4 image. fn arw_with_strip(strip: usize) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let mut raw = IfdBuilder::new(); raw.set(t::MAKE, Value::Ascii("SONY".into())); raw.set(t::MODEL, Value::Ascii("DSLR-A200".into())); @@ -923,7 +923,7 @@ mod tests { /// [`super::super::arw_lens_rm6`]). #[test] fn lens_tables_reach_opcode_list3() { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let file = |model: &str, ca: bool| { let mut raw = IfdBuilder::new(); raw.set(t::MAKE, Value::Ascii("SONY".into())); @@ -974,7 +974,7 @@ mod tests { /// A 32767-compressed, 12-bit ARW of `w` x `h` whose single strip is `strip`. fn packed_arw(w: u32, h: u32, strip: Vec) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let mut raw = IfdBuilder::new(); raw.set(t::MAKE, Value::Ascii("SONY".into())); raw.set(t::MODEL, Value::Ascii("DSLR-A900".into())); @@ -1111,7 +1111,7 @@ mod tests { #[test] fn tag2010_white_balance_by_model() { - use lightcraft_tiff::ByteOrder::Little; + use craft_tiff::ByteOrder::Little; let mut plain = vec![0u8; 700]; for (i, v) in [669u16, 256, 441].iter().enumerate() { plain[612 + 2 * i..614 + 2 * i].copy_from_slice(&v.to_le_bytes()); @@ -1134,8 +1134,8 @@ mod tests { /// A Sony-style file: IFD0 (`make`) → Exif → maker note `SONY DSC \0\0\0` + an IFD of `entries` (tag, type, /// count, inline value bytes), the layout of the camera's own notes; `count` overrides the entry count. - fn sony_file(order: lightcraft_tiff::ByteOrder, make: &str, entries: &[(u16, u16, u32, [u8; 4])], count: Option) -> Vec { - use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + fn sony_file(order: craft_tiff::ByteOrder, make: &str, entries: &[(u16, u16, u32, [u8; 4])], count: Option) -> Vec { + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; let (u16b, u32b) = match order { ByteOrder::Little => (u16::to_le_bytes as fn(u16) -> [u8; 2], u32::to_le_bytes as fn(u32) -> [u8; 4]), ByteOrder::Big => (u16::to_be_bytes as fn(u16) -> [u8; 2], u32::to_be_bytes as fn(u32) -> [u8; 4]), @@ -1160,7 +1160,7 @@ mod tests { #[test] fn dynamic_range_optimizer_is_read_from_the_sony_note() { - use lightcraft_tiff::ByteOrder::{Big, Little}; + use craft_tiff::ByteOrder::{Big, Little}; let long = |order, v: u32| match order { Little => v.to_le_bytes(), Big => v.to_be_bytes(), @@ -1195,7 +1195,7 @@ mod tests { #[test] fn hostile_sony_notes_are_read_safely() { - use lightcraft_tiff::ByteOrder::Little; + use craft_tiff::ByteOrder::Little; let entry = [(MN_DYNAMIC_RANGE_OPTIMIZER, 4, 1, 3u32.to_le_bytes())]; let good = sony_file(Little, "SONY", &entry, None); assert_eq!(crate::embedded_preview_dynamic_range_optimized(&good), Some(true)); @@ -1211,9 +1211,9 @@ mod tests { assert_eq!(crate::embedded_preview_dynamic_range_optimized(b"not a TIFF"), None); assert_eq!(crate::embedded_preview_dynamic_range_optimized(&[]), None); // a Sony file without a maker note - let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); - ifd0.set(t::MAKE, lightcraft_tiff::Value::Ascii("SONY".into())); - assert_eq!(crate::embedded_preview_dynamic_range_optimized(&lightcraft_tiff::TiffWriter::new(Little, false).write(&[ifd0]).unwrap()), None); + let mut ifd0 = craft_tiff::IfdBuilder::new(); + ifd0.set(t::MAKE, craft_tiff::Value::Ascii("SONY".into())); + assert_eq!(crate::embedded_preview_dynamic_range_optimized(&craft_tiff::TiffWriter::new(Little, false).write(&[ifd0]).unwrap()), None); } #[test] @@ -1238,7 +1238,7 @@ mod tests { /// (reached through `DNGPrivateData` and the `SR2Private` IFD, as Sony stores it, with `key`; black level 800) /// and a maker note whose `Tag2010` block (RX100 III layout) holds `WB_RGBLevels`. fn arw_with_wb(plain: Option<[u16; 4]>, sr2: Option<[u16; 4]>, tag2010: Option<[u16; 3]>, key: [u8; 4]) -> Vec { - use lightcraft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value}; let mut tag2010_block = vec![0u8; 700]; for (i, v) in tag2010.unwrap_or([0; 3]).iter().enumerate() { tag2010_block[612 + 2 * i..614 + 2 * i].copy_from_slice(&v.to_le_bytes()); @@ -1307,7 +1307,7 @@ mod tests { /// balance; without the ID, or with one that isn't listed, there is no layout to read. #[test] fn rebadged_body_takes_its_tag2010_layout_from_the_sony_model_id() { - use lightcraft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value}; let file = |make: &str, model: &str, id: Option| { let mut block = vec![0u8; 4600]; for (i, v) in [639u16, 256, 368].iter().enumerate() { @@ -1371,7 +1371,7 @@ mod tests { #[test] fn dsc_r1_sr2_subifd_gives_black_wb_and_crop() { - use lightcraft_tiff::ByteOrder::Little; + use craft_tiff::ByteOrder::Little; let key = [0x63, 0xbe, 0x01, 0x3e]; let enc = |crop: [u16; 4], wb: [u16; 4]| { let b = super::super::sr2::tests::block_keyed( @@ -1453,7 +1453,7 @@ mod tests { #[test] fn sr2_black_level_decodes_and_rejects_garbage() { - use lightcraft_tiff::ByteOrder::Little; + use craft_tiff::ByteOrder::Little; let plain = |levels: [u16; 4]| -> Vec { levels.iter().flat_map(|v| v.to_le_bytes()).collect() }; assert_eq!(sr2_black_levels(&plain([800; 4]), Little), Some(800.0)); assert_eq!(sr2_black_levels(&plain([512, 512, 514, 512]), Little), Some(512.5)); @@ -1486,13 +1486,13 @@ mod tests { } /// [`sr2_black`] on the encrypted `SR2SubIFD` bytes `block`, which start at file offset `start`. - fn sr2_black_in(block: &[u8], start: usize, order: lightcraft_tiff::ByteOrder) -> Option { + fn sr2_black_in(block: &[u8], start: usize, order: craft_tiff::ByteOrder) -> Option { sr2_black(&super::super::sr2::SubIfd::decrypt(block, start, order)) } #[test] fn sr2_black_level_follows_the_first_entry_to_its_layout() { - use lightcraft_tiff::ByteOrder::Little; + use craft_tiff::ByteOrder::Little; let start = 37584; // the value position of every layout seen, e.g. the DSLR-A700's (62112 bytes, value at 1638) and the // DSLR-A450/A500/A550's (27152 bytes, value at 2166); the first four are those of bodies without a plain 0x7310 @@ -1521,7 +1521,7 @@ mod tests { #[test] fn word16_byte_order_follows_the_sample_range() { - use lightcraft_tiff::ByteOrder::{Big, Little}; + use craft_tiff::ByteOrder::{Big, Little}; let be: Vec = (0..4096u16).flat_map(|i| (512 + i * 3).to_be_bytes()).collect(); // 512..12800 big-endian words assert_eq!(word16_order(&be, 14, Little), Big); let le: Vec = (0..4096u16).flat_map(|i| (512 + i * 3).to_le_bytes()).collect(); @@ -1584,7 +1584,7 @@ mod tests { /// decode allocates the frame. #[test] fn a_strip_cut_short_is_refused_before_allocating() { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let (w, h) = (3000u32, 2000u32); for declared in [w * h, w * h / 2 * 3] { let mut raw = IfdBuilder::new(); diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index 9837f3e7be..b8ee711732 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -543,9 +543,9 @@ mod tests { use super::*; use crate::vendor::arw6_testenc::*; use crate::vendor::pef::Bits; - use lightcraft_tiff::Tiff; - use lightcraft_tiff::image::chunk_bytes; - use lightcraft_tiff::tags as t; + use craft_tiff::Tiff; + use craft_tiff::image::chunk_bytes; + use craft_tiff::tags as t; fn planes(w2: usize, h2: usize, seed: u64) -> (Plane, Plane, Plane, Plane) { let mut x = seed.max(1); diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rs index 5493311237..47d93a5639 100644 --- a/crates/raw/src/vendor/arw6_testenc.rs +++ b/crates/raw/src/vendor/arw6_testenc.rs @@ -2,8 +2,8 @@ //! Section names in italics refer to `docs/arw6-compression.md`. use crate::llvc::{Bands3, Plane, band_rows}; -use lightcraft_tiff::tags as t; -use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; +use craft_tiff::tags as t; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; /// Exact inverse of `dequant` on representable values: `sign(v) * (|v| >> qi)`. pub(crate) fn quantize(v: i32, qi: u32) -> i32 { diff --git a/crates/raw/src/vendor/arw_lens.rs b/crates/raw/src/vendor/arw_lens.rs index 4cebf221ec..94f1b67883 100644 --- a/crates/raw/src/vendor/arw_lens.rs +++ b/crates/raw/src/vendor/arw_lens.rs @@ -25,7 +25,7 @@ use crate::lens_metadata::{ SonySource, }; use crate::{Opcode, Rect}; -use lightcraft_tiff::{ByteOrder, FieldType, Ifd, Value}; +use craft_tiff::{ByteOrder, FieldType, Ifd, Value}; /// Each component's setting and table tags, `(raw IFD, SR2SubIFD)`. const SHADING: Tags = Tags { setting: (0x7031, 0x797c), table: (0x7032, 0x797d) }; @@ -545,8 +545,8 @@ mod tests { use crate::lens_metadata::SonyCopy::{Absent, Rejected, Valid}; use crate::lens_metadata::SonyFieldError::*; use crate::{LensMetadata, Mode, RawImage}; - use lightcraft_tiff::ByteOrder::{Big, Little}; - use lightcraft_tiff::{IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t}; + use craft_tiff::ByteOrder::{Big, Little}; + use craft_tiff::{IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t}; const TELE: [i16; 16] = [-2, 1, 7, 17, 31, 48, 68, 93, 120, 152, 187, 225, 265, 309, 356, 403]; const WIDE: [i16; 16] = [14, 0, -27, -59, -106, -158, -223, -291, -367, -440, -519, -593, -667, -731, -792, -839]; diff --git a/crates/raw/src/vendor/arw_lens_rm6.rs b/crates/raw/src/vendor/arw_lens_rm6.rs index 5a215ef7a2..e537e009ea 100644 --- a/crates/raw/src/vendor/arw_lens_rm6.rs +++ b/crates/raw/src/vendor/arw_lens_rm6.rs @@ -47,7 +47,7 @@ use super::fit_radial_warp; use crate::opcodes::max_radius; use crate::{Opcode, Rect}; -use lightcraft_tiff::Ifd; +use craft_tiff::Ifd; use std::ops::RangeInclusive; pub(crate) const DISTORTION_PARAMS: u16 = 0x7037; @@ -272,7 +272,7 @@ pub(crate) fn lens_opcodes(raw: &Ifd, model: &str, lens: Option<&str>, focal_mm: #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{Entry, Value}; + use craft_tiff::{Entry, Value}; /// The FF 16–35 mm example (corpus `arw-sony-ilce7rm6-ff-land-lossless.arw`, docs/sony-ilce7rm6-lens-corrections.md). const FF_DISTORTION: [i16; 17] = [16, 0, 2, 7, 16, 28, 43, 61, 83, 109, 139, 175, 217, 267, 325, 395, 479]; diff --git a/crates/raw/src/vendor/cr2.rs b/crates/raw/src/vendor/cr2.rs index 6cab70d2fa..83367e2324 100644 --- a/crates/raw/src/vendor/cr2.rs +++ b/crates/raw/src/vendor/cr2.rs @@ -27,9 +27,9 @@ mod sraw; use super::{active_rows, black_from_columns, white_from_data}; use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{ByteOrder, Ifd, Tiff, Value, makernote, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::chunk_bytes; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff, Value, makernote, tags as t}; use std::ops::Range; const CR2_SLICE: u16 = 0xc640; @@ -192,9 +192,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { Some(v) if v != 1 => return Err(RawError::Unsupported(format!("Canon raw type {v}"))), _ => {} } - let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(lightcraft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?; + let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(craft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?; let len = raw.u64(t::STRIP_BYTE_COUNTS).unwrap_or(bytes.len() as u64 - off.min(bytes.len() as u64)); - let chunk = lightcraft_tiff::image::Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len }; + let chunk = craft_tiff::image::Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len }; let src = chunk_bytes(bytes, &chunk).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; let (fw, fh, nc, prec) = ljpeg::frame_info(src)?; let frame = match mode { @@ -306,7 +306,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { #[cfg(test)] pub(crate) mod tests { use super::*; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; /// Build a synthetic CR2: IFD0..IFD2 placeholders + IFD3 holding a sliced 2-component LJ92 frame. pub(crate) fn synthetic_cr2(w: usize, h: usize, slices: Option<[u16; 3]>) -> (Vec, Vec) { diff --git a/crates/raw/src/vendor/cr2/sraw.rs b/crates/raw/src/vendor/cr2/sraw.rs index 6a37d627e5..742ce3a58a 100644 --- a/crates/raw/src/vendor/cr2/sraw.rs +++ b/crates/raw/src/vendor/cr2/sraw.rs @@ -28,9 +28,9 @@ use super::{COLOR_BALANCE, CR2_SLICE, SENSOR_INFO, words}; use crate::{BlackLevel, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; +use craft_tiff::image::{Chunk, chunk_bytes}; +use craft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::{Chunk, chunk_bytes}; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t}; use rayon::prelude::*; /// Chroma samples are centred on this value. @@ -335,7 +335,7 @@ fn colour_data_black(words: &[u64]) -> Option { /// Decode a Canon sRAW / mRAW CR2 into linear white-balanced camera RGB (`cpp` 3). pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode) -> Result { let ifd0 = &tiff.ifds[0]; - let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(lightcraft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?; + let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(craft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?; let len = raw.u64(t::STRIP_BYTE_COUNTS).unwrap_or(bytes.len() as u64 - off.min(bytes.len() as u64)); let chunk = Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len }; let src = chunk_bytes(bytes, &chunk).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; @@ -403,7 +403,7 @@ pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode) -> Result #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; const SRAW_TYPE_TAG: u16 = 0xc6c5; diff --git a/crates/raw/src/vendor/cr3.rs b/crates/raw/src/vendor/cr3.rs index ba526b6e56..8a0a54c8c6 100644 --- a/crates/raw/src/vendor/cr3.rs +++ b/crates/raw/src/vendor/cr3.rs @@ -20,8 +20,8 @@ use super::{black_from_columns, crx, white_from_data}; use crate::{BlackLevel, Cfa, ColorData, MAX_SAMPLES, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::{Ifd, Tiff}; use lightcraft_meta::cr3::{Cr3ImageArea, Cr3Track, Cr3TrackKind, parse_cr3}; -use lightcraft_tiff::{Ifd, Tiff}; const SENSOR_INFO: u16 = 0x00e0; const COLOR_DATA: u16 = 0x4001; @@ -282,7 +282,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{IfdBuilder, Value}; + use craft_tiff::{IfdBuilder, Value}; fn maker(version: u16, wb_at: usize, black_at: usize, white_at: usize) -> Ifd { let mut words = vec![0u16; white_at + 1]; @@ -291,7 +291,7 @@ mod tests { words[black_at..black_at + 4].copy_from_slice(&[100, 101, 102, 103]); words[white_at] = 15000; let b = IfdBuilder::new().with(COLOR_DATA, Value::Short(words)); - let bytes = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[b]).unwrap(); + let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[b]).unwrap(); Tiff::parse(&bytes).unwrap().ifds.remove(0) } @@ -321,7 +321,7 @@ mod tests { } fn synthetic_header_with(aspect: Option<[u32; 5]>) -> Vec { - use lightcraft_tiff::{ByteOrder, TiffWriter, tags as t}; + use craft_tiff::{ByteOrder, TiffWriter, tags as t}; let tiff = |b: IfdBuilder| TiffWriter::new(ByteOrder::Little, false).write(&[b]).unwrap(); let cmt1 = tiff( IfdBuilder::new() @@ -460,8 +460,8 @@ mod tests { /// and `AspectInfo` applies from its origin. #[test] fn aspect_info_needs_a_consistent_recommended_crop() { - let aspect = lightcraft_tiff::IfdBuilder::new().with(ASPECT_INFO, Value::Long(vec![13, 5088, 3392, 0, 0])); - let bytes = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[aspect]).unwrap(); + let aspect = craft_tiff::IfdBuilder::new().with(ASPECT_INFO, Value::Long(vec![13, 5088, 3392, 0, 0])); + let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[aspect]).unwrap(); let maker = Tiff::parse(&bytes).unwrap().ifds.remove(0); let area = |crop| Cr3ImageArea { width: 5376, height: 3574, crop, active: Some([132, 160, 5243, 3567]), masked_left: [0; 4], masked_top: None }; diff --git a/crates/raw/src/vendor/erf.rs b/crates/raw/src/vendor/erf.rs index 7f88dae2af..0a1316448b 100644 --- a/crates/raw/src/vendor/erf.rs +++ b/crates/raw/src/vendor/erf.rs @@ -20,9 +20,9 @@ //! - The preview is the maker note's tag `0x0280`, a JPEG whose first byte is stored as `ee` (found by the //! structural scan in `preview::scan_for_jpeg`). use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{Ifd, Tiff, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::chunk_bytes; -use lightcraft_tiff::{Ifd, Tiff, tags as t}; /// Epson's private compression code for the 16-byte block layout. const BLOCKS16: u16 = 32769; @@ -58,8 +58,8 @@ fn maker_note(bytes: &[u8], tiff: &Tiff) -> Option { if !bytes.get(start..)?.starts_with(b"EPSON\0") { return None; } - let opts = lightcraft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() }; - lightcraft_tiff::parse_ifd_at(bytes, e.offset.checked_add(8)?, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) + let opts = craft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() }; + craft_tiff::parse_ifd_at(bytes, e.offset.checked_add(8)?, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) } /// Unpack a strip of 16-byte blocks (15 bytes of ten MSB-first 12-bit samples, one pad byte). @@ -137,7 +137,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; /// Pack ten-sample groups into 16-byte blocks, MSB first, zero pad. fn pack(px: &[u16]) -> Vec { @@ -168,7 +168,7 @@ mod tests { ifd0.set(t::MODEL, Value::Ascii("R-D1".into())); ifd0.set(t::ORIENTATION, Value::Short(vec![1])); ifd0.add_sub_ifd(raw); - TiffWriter::new(lightcraft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() + TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() } #[test] diff --git a/crates/raw/src/vendor/hasselblad.rs b/crates/raw/src/vendor/hasselblad.rs index 5f3342f9ff..9ec21d85c9 100644 --- a/crates/raw/src/vendor/hasselblad.rs +++ b/crates/raw/src/vendor/hasselblad.rs @@ -25,8 +25,8 @@ //! [`rgb_preview`] hands the largest 8-bit one on as a small baseline TIFF. use crate::dng; use crate::{ColorData, Mode, RawFormat, RawImage, Result}; -use lightcraft_tiff::image::{Layout, chunk_bytes}; -use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, ParseOptions, Tiff, TiffWriter, Value, tags as t}; +use craft_tiff::image::{Layout, chunk_bytes}; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, ParseOptions, Tiff, TiffWriter, Value, tags as t}; /// Private IFD0 tag holding the original 3FR header (a complete TIFF) inside an FFF. pub(crate) const ORIGINAL_HEADER: u16 = 0xc51b; @@ -124,7 +124,7 @@ fn adopt_matrices(color: &mut ColorData, from: &ColorData) { mod tests { use super::*; use crate::{RawData, RawError, decode as decode_file, probe, probe_info}; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t}; const MATRIX: [(i32, i32); 9] = [(686, 1000), (-196, 1000), (-32, 1000), (-437, 1000), (1228, 1000), (235, 1000), (-165, 1000), (317, 1000), (675, 1000)]; diff --git a/crates/raw/src/vendor/kodak.rs b/crates/raw/src/vendor/kodak.rs index 1e972873e5..5d77108ffc 100644 --- a/crates/raw/src/vendor/kodak.rs +++ b/crates/raw/src/vendor/kodak.rs @@ -24,9 +24,9 @@ //! each other) the raw G/R is 0.94 and G/B 1.96; `0x848` (1913, 1834, 921) gives 0.96 and 1.99, the others //! 0.77..1.25 and 2.08..2.96, so its green over red and over blue are the gains. use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{Ifd, Tiff, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::chunk_bytes; -use lightcraft_tiff::{Ifd, Tiff, tags as t}; /// The vendor IFD pointer (`KodakIFD`). const KODAK_IFD: u16 = 0x8290; @@ -127,8 +127,8 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { /// The vendor IFD (`KodakIFD`): a plain IFD with absolute value offsets. fn kodak_ifd(bytes: &[u8], tiff: &Tiff, ifd0: &Ifd) -> Option { let off = u64::from(ifd0.u32(KODAK_IFD)?); - let opts = lightcraft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; - lightcraft_tiff::parse_ifd_at(bytes, off, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) + let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; + craft_tiff::parse_ifd_at(bytes, off, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) } /// Black level per CFA position (the mosaic's first sample is position 0): the value below which only 0.01% of that @@ -167,7 +167,7 @@ fn measured_black(d: &[u16], w: usize) -> BlackLevel { mod tests { use super::*; use crate::{decode, probe, probe_info}; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; const W: usize = 16; const H: usize = 8; diff --git a/crates/raw/src/vendor/mef.rs b/crates/raw/src/vendor/mef.rs index d1c9a7754d..8755e9e06c 100644 --- a/crates/raw/src/vendor/mef.rs +++ b/crates/raw/src/vendor/mef.rs @@ -16,9 +16,9 @@ //! - No white-balance tag was found (the maker note holds an ICC-like profile), so the as-shot gains are measured //! from that preview's neutral pixels ([`crate::wb_estimate`]). use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{Ifd, Tiff, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::chunk_bytes; -use lightcraft_tiff::{Ifd, Tiff, tags as t}; /// Where the preview's window starts in the sensor frame, and how many sensor pixels one preview pixel covers. const CROP_ORIGIN: (usize, usize) = (24, 12); @@ -142,7 +142,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; fn pack(px: &[u16]) -> Vec { px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect() diff --git a/crates/raw/src/vendor/mrw.rs b/crates/raw/src/vendor/mrw.rs index 6404ec9aa2..a59de3d3ef 100644 --- a/crates/raw/src/vendor/mrw.rs +++ b/crates/raw/src/vendor/mrw.rs @@ -24,8 +24,8 @@ //! - `TTW` is a TIFF with IFD0 (orientation), Exif and the maker note; the preview JPEG sits in it with its first //! byte overwritten (see `preview::scan_for_jpeg`). use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, unpack}; +use craft_tiff::{Tiff, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::{Tiff, tags as t}; /// Storage method codes in `PRD`. const PACKED_12: u8 = 0x59; @@ -80,7 +80,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { if p.packed { unpack::unpack_msb(src, 12, &mut d); } else { - unpack::read_u16s(src, lightcraft_tiff::ByteOrder::Big, &mut d); + unpack::read_u16s(src, craft_tiff::ByteOrder::Big, &mut d); for v in &mut d { *v = (*v).min(4095); } @@ -154,10 +154,10 @@ pub(crate) mod tests { for v in wbg { wb.extend_from_slice(&v.to_be_bytes()); } - let mut ifd0 = lightcraft_tiff::IfdBuilder::new(); - ifd0.set(t::MAKE, lightcraft_tiff::Value::Ascii("Minolta Co., Ltd.".into())); - ifd0.set(t::ORIENTATION, lightcraft_tiff::Value::Short(vec![6])); - let ttw = lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap(); + let mut ifd0 = craft_tiff::IfdBuilder::new(); + ifd0.set(t::MAKE, craft_tiff::Value::Ascii("Minolta Co., Ltd.".into())); + ifd0.set(t::ORIENTATION, craft_tiff::Value::Short(vec![6])); + let ttw = craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap(); let mut body = Vec::new(); for (name, data) in [(b"PRD", &prd), (b"WBG", &wb), (b"TTW", &ttw)] { body.push(0); diff --git a/crates/raw/src/vendor/nef.rs b/crates/raw/src/vendor/nef.rs index 10bb24d501..916acae60f 100644 --- a/crates/raw/src/vendor/nef.rs +++ b/crates/raw/src/vendor/nef.rs @@ -15,10 +15,10 @@ use super::{nefc, white_from_data}; use crate::tiffraw::{Packing, check_image, read_image}; use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::ImageInfo; +use craft_tiff::tags::{self as t, photometric}; +use craft_tiff::{ByteOrder, Ifd, Tiff, makernote}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::ImageInfo; -use lightcraft_tiff::tags::{self as t, photometric}; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff, makernote}; const WB_RB_LEVELS: u16 = 0x000c; const BLACK_LEVEL: u16 = 0x003d; @@ -500,7 +500,7 @@ fn packed(bytes: &[u8], info: &ImageInfo, rows: usize) -> Result { let (Some(layout), [c]) = (layout, chunks.as_slice()) else { return Err(RawError::Unsupported("Nikon compressed NEF without a linearization table (maker note 0x96)".into())); }; - let src = lightcraft_tiff::image::chunk_bytes(bytes, c) + let src = craft_tiff::image::chunk_bytes(bytes, c) .filter(|src| u64::try_from(src.len()).ok() == Some(c.len)) .ok_or_else(|| RawError::Corrupt("NEF: incomplete image strip".into()))?; if (w as u64).saturating_mul(h as u64) > crate::MAX_SAMPLES as u64 { @@ -538,7 +538,7 @@ const SMALL_RAW_B_GAIN: f32 = 4.4; /// The strip of a small raw: compression 34713, 12 bits, no maker note `0x0096`, one strip of exactly /// `3 * width * height` bytes (even width). -fn small_raw_strip(info: &ImageInfo, file_len: usize, mn: Option<&makernote::MakerNote>) -> Option { +fn small_raw_strip(info: &ImageInfo, file_len: usize, mn: Option<&makernote::MakerNote>) -> Option { if info.compression != t::compression::NIKON || info.bits() != 12 || info.samples_per_pixel != 1 { return None; } @@ -584,12 +584,12 @@ fn small_raw_row(src: &[u8], w: usize, out: &mut [u16]) { } } -fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: lightcraft_tiff::image::Chunk, mode: Mode) -> Result { +fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: craft_tiff::image::Chunk, mode: Mode) -> Result { use rayon::prelude::*; let (w, h) = (info.width as usize, info.height as usize); let stride = w.checked_mul(3).ok_or(RawError::Limit("image too large"))?; let count = stride.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; - let src = lightcraft_tiff::image::chunk_bytes(bytes, &strip) + let src = craft_tiff::image::chunk_bytes(bytes, &strip) .filter(|src| u64::try_from(src.len()).ok() == Some(strip.len)) .ok_or_else(|| RawError::Corrupt("NEF: incomplete image strip".into()))?; let data = match mode { @@ -634,7 +634,7 @@ fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: lightcraft_tiff #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; fn nef(compression: u16, bits: u16, strips: Vec>, w: u32, h: u32, rps: u32) -> Vec { nef_with_note(compression, bits, strips, w, h, rps, None) @@ -1397,7 +1397,7 @@ mod tests { let raw = raw_ifd(&tiff).unwrap(); let info = raw.image().unwrap(); let chunk = info.chunks(bytes.len() as u64)[0]; - let data = lightcraft_tiff::image::chunk_bytes(&bytes, &chunk).unwrap().to_vec(); + let data = craft_tiff::image::chunk_bytes(&bytes, &chunk).unwrap().to_vec(); let offset_entry = raw.get(t::STRIP_OFFSETS).unwrap().offset as usize; let start = bytes.len() as u32; bytes[offset_entry..offset_entry + 4].copy_from_slice(&start.to_be_bytes()); diff --git a/crates/raw/src/vendor/nef_lens.rs b/crates/raw/src/vendor/nef_lens.rs index c5e9490ebd..ee320c36d1 100644 --- a/crates/raw/src/vendor/nef_lens.rs +++ b/crates/raw/src/vendor/nef_lens.rs @@ -8,7 +8,7 @@ //! No lens database or external decoder code. use crate::{Opcode, Rect}; -use lightcraft_tiff::{ByteOrder, Ifd, ParseOptions, parse_ifd_at}; +use craft_tiff::{ByteOrder, Ifd, ParseOptions, parse_ifd_at}; const NEF_INFO: u16 = 0xc7d5; const DISTORTION_INFO: u16 = 0x0005; @@ -38,7 +38,7 @@ fn rational(b: &[u8], at: usize, order: ByteOrder) -> Option { /// The NikonNEFInfo entries: the blob is `"Nikon\0"`, a 4-byte version, then a little TIFF stream. fn nef_info(raw: &Ifd) -> Option<(Ifd, ByteOrder)> { let tiff = raw.bytes(NEF_INFO)?.strip_prefix(b"Nikon\0")?.get(4..)?; - let (order, false) = lightcraft_tiff::Tiff::sniff(tiff)? else { return None }; + let (order, false) = craft_tiff::Tiff::sniff(tiff)? else { return None }; let first = order.u32(tiff.get(4..8)?.try_into().ok()?); let opts = ParseOptions { follow_children: false, ..Default::default() }; let (ifd, _) = parse_ifd_at(tiff, u64::from(first), order, 0, false, &opts).ok()?; @@ -121,7 +121,7 @@ pub(super) fn distortion(model: &str, raw: &Ifd, active: Rect, crop: Rect) -> Op #[cfg(test)] pub(in crate::vendor) mod tests { use super::*; - use lightcraft_tiff::{Entry, IfdBuilder, TiffWriter, Value}; + use craft_tiff::{Entry, IfdBuilder, TiffWriter, Value}; const AREA: Rect = Rect { x: 0, y: 0, width: 6064, height: 4040 }; const CROP: Rect = Rect { x: 8, y: 8, width: 6048, height: 4024 }; diff --git a/crates/raw/src/vendor/nefc.rs b/crates/raw/src/vendor/nefc.rs index fd8e964b7f..27c7467f9b 100644 --- a/crates/raw/src/vendor/nefc.rs +++ b/crates/raw/src/vendor/nefc.rs @@ -58,7 +58,7 @@ use super::pef::{Bits, Huffman, diff}; use crate::{MAX_SAMPLES, RawError, Result}; -use lightcraft_tiff::ByteOrder; +use craft_tiff::ByteOrder; /// A table code word whose symbol was never observed (see the module docs). const UNSEEN: u8 = u8::MAX; @@ -633,8 +633,8 @@ mod tests { /// A minimal NEF: CFA SubIFD with one compressed strip, Exif maker note (`Nikon\0` v2 header + embedded TIFF in /// `mn_order`) holding the linearization table. fn nef_file(strip: Vec, w: u32, h: u32, bits: u16, table: Vec, mn_order: ByteOrder) -> Vec { - use lightcraft_tiff::tags::{self as t, photometric}; - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::tags::{self as t, photometric}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let mut mn = IfdBuilder::new(); mn.set(0x0096, Value::Undefined(table)); let mut note = b"Nikon\0\x02\x10\0\0".to_vec(); diff --git a/crates/raw/src/vendor/orf.rs b/crates/raw/src/vendor/orf.rs index 8c2bd28398..78cfdbe54b 100644 --- a/crates/raw/src/vendor/orf.rs +++ b/crates/raw/src/vendor/orf.rs @@ -40,10 +40,10 @@ use super::{cfa_from_exif, white_from_data}; use crate::tiffraw::{Packing, read_image}; use crate::unpack::unpack_msb; use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::makernote::MakerNote; +use craft_tiff::{Ifd, Tiff, Value, makernote, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::chunk_bytes; -use lightcraft_tiff::makernote::MakerNote; -use lightcraft_tiff::{Ifd, Tiff, Value, makernote, tags as t}; use rayon::prelude::*; pub(crate) const CAMERA_SETTINGS: u16 = 0x2020; @@ -73,8 +73,8 @@ pub(crate) fn sub_ifd(bytes: &[u8], mn: &MakerNote, tag: u16) -> Option { Value::Undefined(_) | Value::Byte(_) => e.offset, _ => mn.base.checked_add(mn.ifd.u64(tag)?)?, }; - let opts = lightcraft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; - lightcraft_tiff::parse_ifd_at(bytes, at, mn.order, mn.base, false, &opts).ok().map(|(i, _)| i) + let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; + craft_tiff::parse_ifd_at(bytes, at, mn.order, mn.base, false, &opts).ok().map(|(i, _)| i) } /// Black level of a body without ImageProcessing: the main note's `0x1012` BlackLevel (the mean of its four values) @@ -365,7 +365,7 @@ pub(crate) fn preview(bytes: &[u8]) -> Option<&[u8]> { mod tests { use super::*; use crate::vendor::EXIF_CFA_PATTERN; - use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter}; + use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter}; fn orf(w: u32, h: u32, bits: u16, strip: Vec) -> Vec { orf_with(w, h, bits, strip, None) diff --git a/crates/raw/src/vendor/pef.rs b/crates/raw/src/vendor/pef.rs index 45efeec685..466ccdd023 100644 --- a/crates/raw/src/vendor/pef.rs +++ b/crates/raw/src/vendor/pef.rs @@ -19,9 +19,9 @@ use super::{black_from_columns, cfa_from_exif, white_from_data}; use crate::tiffraw::{Packing, read_image_in}; use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::{ImageInfo, chunk_bytes}; +use craft_tiff::{ByteOrder, Tiff, makernote, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::{ImageInfo, chunk_bytes}; -use lightcraft_tiff::{ByteOrder, Tiff, makernote, tags as t}; const CROP_ORIGIN: u16 = 0x0038; const CROP_SIZE: u16 = 0x0039; @@ -523,7 +523,7 @@ mod tests { /// `CFAPattern` `pattern` and an AOC maker note with the area tags (and, for 65535, a Huffman table). The samples /// are plain 16-bit words (1), packed 12-bit (32773) or Huffman coded (65535). fn pef_with_pattern(compression: u16, pattern: [u8; 4]) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let (w, h) = (16usize, 8usize); let px: Vec = (0..w * h).map(|i| ((i * 37) % 900 + 100) as u16).collect(); let (tb, codes) = test_table(); @@ -589,7 +589,7 @@ mod tests { /// A `w x h` big-endian 14-bit PEF of plain 16-bit words without area tags, whose maker note has only a /// BlackPoint of `black`, with `px(x, y)` as the samples. fn pef_with_black_point(w: usize, h: usize, black: u16, px: impl Fn(usize, usize) -> u16) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let strip: Vec = (0..w * h).flat_map(|i| px(i % w, i / w).to_be_bytes()).collect(); let build = |levels_at: u32| { let mut ifd = IfdBuilder::new(); diff --git a/crates/raw/src/vendor/raf.rs b/crates/raw/src/vendor/raf.rs index b60a742660..e485931114 100644 --- a/crates/raw/src/vendor/raf.rs +++ b/crates/raw/src/vendor/raf.rs @@ -24,8 +24,8 @@ use super::white_from_data; use crate::unpack::{unpack_lsb, unpack_words32_msb}; use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::{ByteOrder, Ifd, Tiff}; use lightcraft_geom::Orientation; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff}; use rayon::prelude::*; const CROP_TOP_LEFT: u16 = 0x0110; @@ -88,7 +88,7 @@ fn pair(h: &Header, tag: u16) -> Option<(usize, usize)> { pub(crate) fn raw_ifd(raw: &[u8]) -> Result { let tiff = Tiff::parse(raw).map_err(|_| RawError::Unsupported("RAF without a raw IFD (older FinePix layout)".into()))?; let off = tiff.ifds.first().and_then(|i| i.u64(0xf000)).ok_or_else(|| RawError::Unsupported("RAF without a raw IFD".into()))?; - let (ifd, _) = lightcraft_tiff::parse_ifd_at(raw, off, ByteOrder::Little, 0, false, &Default::default())?; + let (ifd, _) = craft_tiff::parse_ifd_at(raw, off, ByteOrder::Little, 0, false, &Default::default())?; Ok(ifd) } diff --git a/crates/raw/src/vendor/raf_lens.rs b/crates/raw/src/vendor/raf_lens.rs index 283a3d0ea3..60275cd0d8 100644 --- a/crates/raw/src/vendor/raf_lens.rs +++ b/crates/raw/src/vendor/raf_lens.rs @@ -18,7 +18,7 @@ //! - vignette: relative illumination in percent at the source radius; the correction is the gain `100 / V`. use crate::{Opcode, Rect}; -use lightcraft_tiff::Ifd; +use craft_tiff::Ifd; const DISTORTION: u16 = 0xf00b; const VIGNETTING: u16 = 0xf010; @@ -334,7 +334,7 @@ pub(super) fn corrections(model: &str, raw: &Ifd, active: Rect) -> Vec { #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{Entry, Value}; + use craft_tiff::{Entry, Value}; pub(crate) const KNOTS9: [f64; 9] = [0.3535211268, 0.5, 0.6126760563, 0.7070422535, 0.7908450704, 0.8661971831, 0.9352112676, 1.0, 1.06056338]; /// X-T4 with the XF16-55 at 16 mm (3913): the tables as ExifTool prints them. diff --git a/crates/raw/src/vendor/rw2.rs b/crates/raw/src/vendor/rw2.rs index 4acd53a020..7938da9d8e 100644 --- a/crates/raw/src/vendor/rw2.rs +++ b/crates/raw/src/vendor/rw2.rs @@ -105,8 +105,8 @@ use super::pef::{Bits, Huffman, diff}; use super::{active_rows, white_from_data}; use crate::{BlackLevel, Cfa, ColorData, MAX_SAMPLES, Mode, Opcode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::{ByteOrder, Ifd, Tiff, Value, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff, Value, tags as t}; use rayon::prelude::*; const SENSOR_WIDTH: u16 = 0x0002; @@ -698,7 +698,7 @@ fn distortion(ifd: &Ifd, active: Rect) -> Option { #[cfg(test)] mod tests { use super::*; - use lightcraft_tiff::{IfdBuilder, TiffWriter}; + use craft_tiff::{IfdBuilder, TiffWriter}; /// Writes bit fields into a 16-byte block from bit 127 down (the inverse of [`Fields`]). struct FieldWriter { diff --git a/crates/raw/src/vendor/sr2.rs b/crates/raw/src/vendor/sr2.rs index 10fc15074b..01535a228e 100644 --- a/crates/raw/src/vendor/sr2.rs +++ b/crates/raw/src/vendor/sr2.rs @@ -45,7 +45,7 @@ //! of an accident 2⁻⁴⁰⁶⁴). For the DSC-R1's key `63 be 01 3e` the 11932-byte block becomes a well-formed 101-entry //! directory (black `0x7300`, white balance `0x7303`, crop `0x74c3`). -use lightcraft_tiff::{ByteOrder, EntrySpan, Ifd, ParseOptions, decode_value, directory_entries, entry_span, tags as t}; +use craft_tiff::{ByteOrder, EntrySpan, Ifd, ParseOptions, decode_value, directory_entries, entry_span, tags as t}; /// `SR2Private` tags. const SUBIFD_OFFSET: u16 = 0x7200; @@ -260,7 +260,7 @@ pub(crate) mod tests { const LONG: u16 = 4; const UNDEFINED: u16 = 7; const IFD: u16 = 13; - use lightcraft_tiff::ByteOrder::{Big, Little}; + use craft_tiff::ByteOrder::{Big, Little}; /// An `SR2SubIFD` block for file offset `start`, encrypted: SHORT/SSHORT entries `(tag, type, values)`, values /// of more than two shorts stored after the table at file offsets, as Sony does. @@ -429,8 +429,8 @@ pub(crate) mod tests { /// What `SubIfd::read` on main selects: the TIFF reader's parse of the directory with main's options, then the /// directory's `u64` and `bytes` lookups. fn reader_selects(bytes: &[u8], at: usize, order: ByteOrder) -> Selected { - let opts = lightcraft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() }; - let Ok((private, _)) = lightcraft_tiff::parse_ifd_at(bytes, at as u64, order, 0, false, &opts) else { return (None, None, None) }; + let opts = craft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() }; + let Ok((private, _)) = craft_tiff::parse_ifd_at(bytes, at as u64, order, 0, false, &opts) else { return (None, None, None) }; let n = |tag: u16| private.u64(tag).and_then(|v| usize::try_from(v).ok()); (n(SUBIFD_OFFSET), n(SUBIFD_LENGTH), private.bytes(SUBIFD_KEY).and_then(|b| <[u8; 4]>::try_from(b).ok())) } @@ -594,7 +594,7 @@ pub(crate) mod tests { let mut pointer = Vec::new(); order.put_u32(&mut pointer, 0); let ifd0 = Ifd { - entries: vec![lightcraft_tiff::Entry { tag: t::DNG_PRIVATE_DATA, value: lightcraft_tiff::Value::Byte(pointer), offset: 0 }], + entries: vec![craft_tiff::Entry { tag: t::DNG_PRIVATE_DATA, value: craft_tiff::Value::Byte(pointer), offset: 0 }], ..Default::default() }; let black = SubIfd::read(&file, &ifd0, order).and_then(|s| s.shorts(0x7310)); diff --git a/crates/raw/src/vendor/srw.rs b/crates/raw/src/vendor/srw.rs index dbdb21b52f..298aeed238 100644 --- a/crates/raw/src/vendor/srw.rs +++ b/crates/raw/src/vendor/srw.rs @@ -36,9 +36,9 @@ use super::{black_from_columns, white_from_data}; use crate::unpack::{read_u16s, unpack_lsb, unpack_msb}; use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; +use craft_tiff::image::chunk_bytes; +use craft_tiff::{ByteOrder, Ifd, Tiff, tags as t}; use lightcraft_geom::Orientation; -use lightcraft_tiff::image::chunk_bytes; -use lightcraft_tiff::{ByteOrder, Ifd, Tiff, tags as t}; use rayon::prelude::*; const SENSOR_AREAS: u16 = 0xa010; @@ -53,8 +53,8 @@ const COMPRESSIONS: std::ops::RangeInclusive = 32769..=32773; /// The maker-note IFD (offsets relative to the note's own start). fn maker_note(bytes: &[u8], tiff: &Tiff) -> Option { let e = tiff.exif()?.get(t::MAKER_NOTE)?; - let opts = lightcraft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; - lightcraft_tiff::parse_ifd_at(bytes, e.offset, tiff.order, e.offset, false, &opts).ok().map(|(i, _)| i) + let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; + craft_tiff::parse_ifd_at(bytes, e.offset, tiff.order, e.offset, false, &opts).ok().map(|(i, _)| i) } /// A key-offset vector: the entries of `tag` shifted by the maker note's key (`sign` is +1 or -1 times the key). @@ -281,7 +281,7 @@ fn masked_black(d: &[u16], w: usize, h: usize, a: Rect, white: f32) -> BlackLeve mod tests { use super::*; use crate::{decode, probe, probe_info}; - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; const KEY: [u32; 11] = [305, 72, 737, 456, 282, 307, 519, 724, 13, 505, 193]; @@ -362,7 +362,7 @@ mod tests { } ifd0.set_child(t::EXIF_IFD, exif); ifd0.add_sub_ifd(raw); - TiffWriter::new(lightcraft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() + TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() } /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. diff --git a/crates/raw/tests/it/corpus.rs b/crates/raw/tests/it/corpus.rs index 0be98991de..44ac741076 100644 --- a/crates/raw/tests/it/corpus.rs +++ b/crates/raw/tests/it/corpus.rs @@ -1378,7 +1378,7 @@ fn a7cr_enabled_distortion_agrees_in_header_full_and_dng() { let Some(mut bytes) = pinned_sony(&root, name) else { continue }; let original = probe_info(&bytes).unwrap(); assert!(original.opcodes.list3.is_empty(), "Off files must remain uncorrected"); - let tiff = lightcraft_tiff::Tiff::parse(&bytes).unwrap(); + let tiff = craft_tiff::Tiff::parse(&bytes).unwrap(); let at = tiff.find(0x7036).unwrap().offset as usize; let mut enabled = Vec::new(); tiff.order.put_u16(&mut enabled, 17); diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index dddafd5d0d..e8e5185374 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -1,14 +1,14 @@ //! Synthetic DNG round trips: every storage variant we decode is written with our own TIFF writer (and LJ92 //! encoder) and must decode bit-exactly. +use craft_tiff::tags::{self as t, compression, photometric}; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; use lightcraft_color::{D65, Mat3, Xy}; use lightcraft_raw::opcodes::{Area, Opcode}; use lightcraft_raw::{ BlackLevel, Cfa, ColorData, DngCompression, DngWriteOptions, Method, OpcodeLists, Orientation, RawData, RawFormat, RawImage, Rect, decode, embedded_preview, probe, write_dng, }; -use lightcraft_tiff::tags::{self as t, compression, photometric}; -use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; fn scene_value(x: usize, y: usize, c: u8, max: f32) -> f32 { let base = [0.55, 0.8, 0.4][c as usize]; @@ -120,7 +120,7 @@ fn writer_camera_identity_tags_roundtrip() { raw.metadata.model = model.map(str::to_owned); for order in [ByteOrder::Little, ByteOrder::Big] { let bytes = write_dng(&raw, &DngWriteOptions { compression: DngCompression::Uncompressed, order, xmp: None }).unwrap(); - let tiff = lightcraft_tiff::Tiff::parse(&bytes).unwrap(); + let tiff = craft_tiff::Tiff::parse(&bytes).unwrap(); let ifd = &tiff.ifds[0]; assert_eq!(ifd.value(t::UNIQUE_CAMERA_MODEL), Some(&Value::Ascii(unique.into())), "{make:?} / {model:?}, {order:?}"); for (tag, original) in [(t::MAKE, make), (t::MODEL, model)] { diff --git a/crates/raw/tests/it/robust.rs b/crates/raw/tests/it/robust.rs index ce41c1710c..3cd54e47e9 100644 --- a/crates/raw/tests/it/robust.rs +++ b/crates/raw/tests/it/robust.rs @@ -97,8 +97,8 @@ fn truncation_at_every_length() { #[test] fn hostile_dimensions_are_rejected_quickly() { // a DNG claiming a 60000 × 60000 16-bit image with 10 bytes of data - use lightcraft_tiff::tags as t; - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::tags as t; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let mut ifd = IfdBuilder::new(); ifd.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0])); ifd.set(t::IMAGE_WIDTH, Value::Long(vec![60000])); @@ -120,8 +120,8 @@ fn hostile_dimensions_are_rejected_quickly() { /// read as 0 and non-finite samples as black: the photo develops to finite numbers. #[test] fn non_finite_black_levels_and_samples_develop() { - use lightcraft_tiff::tags as t; - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; + use craft_tiff::tags as t; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let (w, h) = (32u32, 16u32); for black in [Value::Float(vec![f32::NAN]), Value::Double(vec![f64::INFINITY]), Value::Float(vec![64.0, f32::NAN, 64.0, 64.0])] { let mut ifd = IfdBuilder::new(); diff --git a/crates/raw/tests/it/sony_lens_inventory.rs b/crates/raw/tests/it/sony_lens_inventory.rs index 3eda884187..bea6dfde48 100644 --- a/crates/raw/tests/it/sony_lens_inventory.rs +++ b/crates/raw/tests/it/sony_lens_inventory.rs @@ -292,7 +292,7 @@ impl Drop for Scratch { /// A small Sony CFA file with a distortion setting (a lens record), or, `unsupported`, the packed 12-bit ARW variant /// the decoder refuses as unsupported. fn synthetic_arw(unsupported: bool) -> Vec { - use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; let mut raw = IfdBuilder::new(); raw.set(t::MAKE, Value::Ascii("SONY".into())); raw.set(t::MODEL, Value::Ascii("ILCE-7CR".into())); diff --git a/crates/raw/tests/it/vendor_robust.rs b/crates/raw/tests/it/vendor_robust.rs index 446c1fb60a..1ebbae6633 100644 --- a/crates/raw/tests/it/vendor_robust.rs +++ b/crates/raw/tests/it/vendor_robust.rs @@ -1,7 +1,7 @@ //! Malformed vendor raw files (NEF, ARW, PEF, ORF, RW2 of every raw format, CR2, RAF, CRW) must decode to an error, never panic. -use lightcraft_tiff::tags as t; -use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; +use craft_tiff::tags as t; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; use proptest::prelude::*; const W: u32 = 32; diff --git a/crates/raw/tests/sr2_heap.rs b/crates/raw/tests/sr2_heap.rs index 2b936d18c2..8839e66c8d 100644 --- a/crates/raw/tests/sr2_heap.rs +++ b/crates/raw/tests/sr2_heap.rs @@ -3,7 +3,7 @@ //! it must not cost memory sized by its other entries: a hostile file can give it fields that each alias most of the //! file. Only the block's offset, length and key may be read. One test per binary (dhat's profiler is global). -use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t}; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t}; #[global_allocator] static ALLOC: dhat::Alloc = dhat::Alloc; diff --git a/crates/tiff/Cargo.toml b/crates/tiff/Cargo.toml deleted file mode 100644 index 74919c6928..0000000000 --- a/crates/tiff/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "lightcraft-tiff" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "LightCraft TIFF/IFD reader and writer (L0)" - -[lints] -workspace = true - -[dependencies] -serde = { workspace = true } -thiserror = { workspace = true } - -[dev-dependencies] -proptest = { workspace = true } diff --git a/crates/tiff/README.md b/crates/tiff/README.md deleted file mode 100644 index 2436b0d311..0000000000 --- a/crates/tiff/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# lightcraft-tiff (L0) - -TIFF / IFD reader and writer. Used by `lightcraft-raw` (DNG, CR2, NEF, ARW…), `lightcraft-meta` (Exif) and -later the TIFF/DNG exporters. - -## Features - -- Classic TIFF and BigTIFF, little- and big-endian (`II`/`MM`). Also accepts the TIFF-like magic numbers of - some raw formats (ORF `IIRO`/`IIRS`, RW2 `IIU`) when `ParseOptions::accept_raw_magic` is set (default). -- Every field type: BYTE, ASCII, SHORT, LONG, RATIONAL, SBYTE, UNDEFINED, SSHORT, SLONG, SRATIONAL, FLOAT, - DOUBLE, IFD, LONG8, SLONG8, IFD8. -- IFD chain + `SubIFDs` (330) + Exif (34665) / GPS (34853) / Interoperability (40965) pointer IFDs, resolved - into a tree (`Ifd::sub_ifds`, `exif`, `gps`, `interop`). `Entry::offset` records the absolute position of - each value (needed for maker notes and embedded blobs). -- `parse_ifd_at(data, offset, order, base, bigtiff, opts)` parses an IFD whose offsets are relative to an - arbitrary base; `makernote::parse_makernote` knows the header / byte-order / offset-base conventions of - Canon, Nikon (types 1 and 3), Sony, Fujifilm, Olympus (old and new), Panasonic and Pentax notes. -- `image::ImageInfo` — width/height, bits, samples, compression, photometric, planar config, predictor, - sample format and the strip or tile chunk list (`chunks()`, `chunk_bytes()`); missing byte counts are - inferred. -- `directory_entries`, `entry_span`, `ParseOptions::budget_for` and `decode_value` are the reader's own rules - (directory layout and entry limit, which entries it reads, its value budget, value decoding), for callers that - must select entries exactly as `parse_ifd_at` would without decoding the whole directory (`lightcraft-raw`'s - Sony `SR2Private` lookup). -- `TiffWriter` writes IFD chains with strips or tiles, `SubIFDs` and pointer IFDs, in either byte order, - classic or BigTIFF; `writer::rational` / `srational` approximate floats as rationals. - -## Robustness - -The reader never panics on malformed input (proptests feed random and mutated files): offsets are -bounds-checked; out-of-range or unknown-type entries are skipped; IFD loops are detected; IFD count, -nesting depth and entries per IFD are limited; at most 65,536 directory entry slots -(`ParseOptions::max_entries_total`) are accepted across the main IFD chain and all child IFDs, even when tables -overlap at distinct offsets, and an IFD past that bound ends the chain or is skipped like any other bad IFD after -the first; a next-IFD pointer is followed only when every declared entry was read, with the counts compared as -64-bit numbers (a BigTIFF declaring 4,294,967,297 entries but holding one can't pass for a whole directory on a -32-bit target); the total bytes of decoded values are capped at -`8 × input + 1 MiB` so a file cannot make us allocate far more than its own size. - -## Sources - -Public specifications only: TIFF 6.0 (Adobe, 1992), the TIFF 6.0 supplements (IFD type, SubIFDs), the -BigTIFF format description (AWare Systems), Adobe DNG Specification 1.7 (tag numbers), CIPA DC-008 Exif 2.32, -and the ExifTool tag-name documentation (maker-note header conventions, prose only). No third-party code -was consulted. diff --git a/crates/tiff/src/image.rs b/crates/tiff/src/image.rs deleted file mode 100644 index 16e24f3676..0000000000 --- a/crates/tiff/src/image.rs +++ /dev/null @@ -1,248 +0,0 @@ -//! Image layout of an IFD: dimensions, sample format and the strip / tile chunks holding the pixels. - -use crate::{Ifd, Result, TiffError, tags}; -use serde::{Deserialize, Serialize}; - -/// How pixel data is split into chunks. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum Layout { - Strips { rows_per_strip: u32 }, - Tiles { tile_width: u32, tile_height: u32 }, -} - -/// Pixel layout description of an IFD (TIFF 6.0 §3–§8, §15). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ImageInfo { - pub width: u32, - pub height: u32, - pub bits_per_sample: Vec, - pub samples_per_pixel: u16, - pub compression: u16, - pub photometric: u16, - /// 1 = chunky (interleaved), 2 = planar. - pub planar: u16, - pub predictor: u16, - /// 1 = unsigned int, 2 = signed int, 3 = IEEE float. - pub sample_format: u16, - pub new_subfile_type: u32, - pub layout: Layout, - pub offsets: Vec, - pub byte_counts: Vec, -} - -/// One strip or tile. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Chunk { - pub index: usize, - /// Top-left pixel of the chunk. - pub x: u32, - pub y: u32, - /// Nominal chunk size (tiles may extend past the image; strips are clipped to the image height). - pub width: u32, - pub height: u32, - /// Plane index for planar configuration 2 (else 0). - pub plane: u16, - pub offset: u64, - pub len: u64, -} - -impl ImageInfo { - pub fn from_ifd(ifd: &Ifd) -> Result { - let width = ifd.u32(tags::IMAGE_WIDTH).ok_or(TiffError::MissingTag(tags::IMAGE_WIDTH))?; - let height = ifd.u32(tags::IMAGE_LENGTH).ok_or(TiffError::MissingTag(tags::IMAGE_LENGTH))?; - if width == 0 || height == 0 { - return Err(TiffError::Invalid("zero image dimension".into())); - } - let samples_per_pixel = ifd.u16(tags::SAMPLES_PER_PIXEL).unwrap_or(1).max(1); - let bits_per_sample: Vec = - ifd.u64s(tags::BITS_PER_SAMPLE).map(|v| v.into_iter().map(|b| b.min(u16::MAX as u64) as u16).collect()).unwrap_or_else(|| vec![1]); - let bits_per_sample = if bits_per_sample.is_empty() { vec![1] } else { bits_per_sample }; - let planar = ifd.u16(tags::PLANAR_CONFIGURATION).unwrap_or(1); - let (layout, offsets, byte_counts) = if let Some(tw) = ifd.u32(tags::TILE_WIDTH) { - let th = ifd.u32(tags::TILE_LENGTH).ok_or(TiffError::MissingTag(tags::TILE_LENGTH))?; - if tw == 0 || th == 0 { - return Err(TiffError::Invalid("zero tile size".into())); - } - let offs = ifd.u64s(tags::TILE_OFFSETS).or_else(|| ifd.u64s(tags::STRIP_OFFSETS)).ok_or(TiffError::MissingTag(tags::TILE_OFFSETS))?; - let cnts = ifd - .u64s(tags::TILE_BYTE_COUNTS) - .or_else(|| ifd.u64s(tags::STRIP_BYTE_COUNTS)) - .ok_or(TiffError::MissingTag(tags::TILE_BYTE_COUNTS))?; - (Layout::Tiles { tile_width: tw, tile_height: th }, offs, cnts) - } else { - let offs = ifd.u64s(tags::STRIP_OFFSETS).ok_or(TiffError::MissingTag(tags::STRIP_OFFSETS))?; - let cnts = ifd.u64s(tags::STRIP_BYTE_COUNTS).unwrap_or_default(); - let rps = ifd.u32(tags::ROWS_PER_STRIP).unwrap_or(height).clamp(1, height); - (Layout::Strips { rows_per_strip: rps }, offs, cnts) - }; - Ok(ImageInfo { - width, - height, - bits_per_sample, - samples_per_pixel, - compression: ifd.u16(tags::COMPRESSION).unwrap_or(1), - photometric: ifd.u16(tags::PHOTOMETRIC).unwrap_or(1), - planar, - predictor: ifd.u16(tags::PREDICTOR).unwrap_or(1), - sample_format: ifd.u16(tags::SAMPLE_FORMAT).unwrap_or(1), - new_subfile_type: ifd.u32(tags::NEW_SUBFILE_TYPE).unwrap_or(0), - layout, - offsets, - byte_counts, - }) - } - - /// Bits of the first sample. - pub fn bits(&self) -> u16 { - self.bits_per_sample[0] - } - - /// Whether this IFD is a reduced-resolution image (NewSubfileType bit 0). - pub fn is_reduced(&self) -> bool { - self.new_subfile_type & 1 != 0 - } - - /// Number of chunks across and down per plane. - pub fn grid(&self) -> (u32, u32) { - match self.layout { - Layout::Strips { rows_per_strip } => (1, self.height.div_ceil(rows_per_strip)), - Layout::Tiles { tile_width, tile_height } => (self.width.div_ceil(tile_width), self.height.div_ceil(tile_height)), - } - } - - /// Nominal chunk dimensions. - pub fn chunk_size(&self) -> (u32, u32) { - match self.layout { - Layout::Strips { rows_per_strip } => (self.width, rows_per_strip), - Layout::Tiles { tile_width, tile_height } => (tile_width, tile_height), - } - } - - /// The chunk count the image declares (offsets present, cut to the layout's plane capacity) with the - /// geometry `chunks` needs to place each one. No descriptors are built, so a pathological strip array - /// costs it a length check. - fn chunk_grid(&self) -> (usize, u32, usize) { - let (across, down) = self.grid(); - let per_plane = across as usize * down as usize; - let planes = if self.planar == 2 { self.samples_per_pixel as usize } else { 1 }; - (self.offsets.len().min(per_plane.saturating_mul(planes)), across, per_plane) - } - - fn declared_chunk_count(&self) -> usize { - self.chunk_grid().0 - } - - /// The one chunk when the image has exactly one, else `None` — and no descriptor vector beyond it. Preview - /// extraction only serves single-chunk images, so it asks here before serving a hostile multi-strip layout. - pub fn single_chunk(&self, data_len: u64) -> Option { - if self.declared_chunk_count() != 1 { - return None; - } - self.chunks(data_len).into_iter().next() - } - - /// All chunks that have an offset. Missing byte counts are inferred as "to the next offset / end of data" - /// using `data_len`. - pub fn chunks(&self, data_len: u64) -> Vec { - let (n, across, per_plane) = self.chunk_grid(); - let (cw, ch) = self.chunk_size(); - let mut out = Vec::with_capacity(n); - // the distinct offsets in order, for chunks without a byte count (sorted once, not scanned per chunk) - let mut sorted: Vec = Vec::new(); - if (0..n).any(|i| self.byte_counts.get(i).is_none_or(|&l| l == 0)) { - sorted = self.offsets.clone(); - sorted.sort_unstable(); - sorted.dedup(); - } - for i in 0..n { - let plane = i / per_plane.max(1); - let j = i % per_plane.max(1); - let (cx, cy) = (j as u32 % across, j as u32 / across); - let x = cx * cw; - let y = cy * ch; - let height = match self.layout { - Layout::Strips { .. } => ch.min(self.height - y), - Layout::Tiles { .. } => ch, - }; - let offset = self.offsets[i]; - let len = match self.byte_counts.get(i) { - Some(&l) if l > 0 => l, - _ => { - // infer: up to the next larger offset, else end of data - let next = sorted.get(sorted.partition_point(|&o| o <= offset)).copied().unwrap_or(data_len); - next.saturating_sub(offset) - } - }; - out.push(Chunk { index: i, x, y, width: cw, height, plane: plane as u16, offset, len }); - } - out - } -} - -/// The bytes of a chunk, clipped to the available data (truncated files yield a shorter slice). -/// Returns `None` only when the chunk starts past the end of `data`. -pub fn chunk_bytes<'a>(data: &'a [u8], c: &Chunk) -> Option<&'a [u8]> { - let start = usize::try_from(c.offset).ok()?; - if start >= data.len() { - return None; - } - let end = (c.offset.saturating_add(c.len)).min(data.len() as u64) as usize; - Some(&data[start..end]) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn strips(offsets: Vec, byte_counts: Vec) -> ImageInfo { - ImageInfo { - width: 1, - height: offsets.len() as u32, - bits_per_sample: vec![8], - samples_per_pixel: 1, - compression: 1, - photometric: 1, - planar: 1, - predictor: 1, - sample_format: 1, - new_subfile_type: 0, - layout: Layout::Strips { rows_per_strip: 1 }, - offsets, - byte_counts, - } - } - - /// One offset is one chunk, and `single_chunk` refuses to build descriptors when the image declares more. - #[test] - fn single_chunk_is_the_only_chunk() { - let one = strips(vec![50], vec![10]); - assert_eq!(one.single_chunk(100).map(|c| (c.index, c.offset, c.len)), one.chunks(100).first().map(|c| (c.index, c.offset, c.len))); - // the inferred length matches too, and never falls back past the data - let inferred = strips(vec![70], vec![]); - assert_eq!(inferred.single_chunk(100).map(|c| c.len), Some(30)); - assert!(strips(vec![50, 10], vec![10, 5]).single_chunk(100).is_none(), "a multi-chunk image has no single chunk"); - assert!(strips(Vec::new(), Vec::new()).single_chunk(100).is_none()); - } - - #[test] - fn missing_byte_counts_run_to_the_next_larger_offset() { - let info = strips(vec![50, 10, 30, 10, 70], vec![0, 0, 5]); - let lens: Vec = info.chunks(100).iter().map(|c| c.len).collect(); - assert_eq!(lens, vec![20, 20, 5, 20, 30]); - } - - /// A million strips without byte counts (offsets in descending order) are measured in one sort, not one - /// scan of all offsets per strip. - #[test] - fn many_strips_without_byte_counts_are_fast() { - let n = 1_000_000u64; - let info = strips((0..n).rev().map(|i| 1000 + i * 2).collect(), Vec::new()); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let chunks = info.chunks(1000 + n * 2); - let _ = tx.send(chunks.iter().map(|c| c.len).collect::>()); - }); - let lens = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("chunks() took longer than 20 s"); - assert!(lens.iter().all(|&l| l == 2)); - } -} diff --git a/crates/tiff/src/lib.rs b/crates/tiff/src/lib.rs deleted file mode 100644 index 2072c4936e..0000000000 --- a/crates/tiff/src/lib.rs +++ /dev/null @@ -1,468 +0,0 @@ -//! TIFF / IFD reading and writing for LightCraft. -//! -//! - [`Tiff::parse`] reads classic TIFF and BigTIFF in both byte orders, following the IFD chain, -//! `SubIFDs`, and the Exif / GPS / Interoperability IFD pointers. All field types of TIFF 6.0, -//! the TIFF 6.0 supplement (`IFD`) and BigTIFF (`LONG8`, `SLONG8`, `IFD8`) are decoded. -//! - [`parse_ifd_at`] parses a single IFD with an arbitrary offset base — the building block for -//! maker-note IFDs ([`makernote`]). -//! - [`image::ImageInfo`] describes the pixel layout of an IFD (strips or tiles, planar config, -//! compression, predictor) and enumerates its [`image::Chunk`]s. -//! - [`writer::TiffWriter`] writes IFD trees (with strips/tiles, `SubIFDs` and pointer IFDs) in -//! either byte order, classic or BigTIFF. -//! -//! The reader never panics on malformed input: every offset is bounds-checked, IFD loops are -//! detected, nesting depth / IFD count are limited, at most 65,536 directory entry slots are read -//! across the main chain and child IFDs, and decoded value bytes are capped relative to the input -//! size (so overlapping tables cannot multiply entry-vector allocations without bound). -//! -//! Sources: TIFF 6.0 specification (Adobe, 1992), TIFF Technical Note / supplements, the BigTIFF -//! design notes (AWare Systems), Adobe DNG specification 1.7 (tag numbers), CIPA DC-008 (Exif 2.32). -#![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -pub mod image; -pub mod makernote; -mod reader; -pub mod tags; -pub mod writer; - -pub use reader::{DirectoryEntries, EntrySpan, ParseOptions, decode as decode_value, directory_entries, entry_span, parse_ifd_at}; -pub use writer::{IfdBuilder, ImageData, TiffWriter}; - -use serde::{Deserialize, Serialize}; - -/// Errors from TIFF parsing / writing. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -pub enum TiffError { - #[error("not a TIFF stream (bad header)")] - NotTiff, - #[error("data truncated at offset {0}")] - Truncated(u64), - #[error("invalid TIFF structure: {0}")] - Invalid(String), - #[error("resource limit exceeded: {0}")] - Limit(&'static str), - #[error("missing required tag {0}")] - MissingTag(u16), -} - -pub type Result = std::result::Result; - -/// Byte order of a TIFF stream. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] -pub enum ByteOrder { - /// `II` — Intel, little-endian. - #[default] - Little, - /// `MM` — Motorola, big-endian. - Big, -} - -impl ByteOrder { - #[inline] - pub fn u16(self, b: [u8; 2]) -> u16 { - match self { - ByteOrder::Little => u16::from_le_bytes(b), - ByteOrder::Big => u16::from_be_bytes(b), - } - } - #[inline] - pub fn u32(self, b: [u8; 4]) -> u32 { - match self { - ByteOrder::Little => u32::from_le_bytes(b), - ByteOrder::Big => u32::from_be_bytes(b), - } - } - #[inline] - pub fn u64(self, b: [u8; 8]) -> u64 { - match self { - ByteOrder::Little => u64::from_le_bytes(b), - ByteOrder::Big => u64::from_be_bytes(b), - } - } - /// Read a `u16` at `off`, or `None` if out of bounds. - #[inline] - pub fn read_u16(self, data: &[u8], off: usize) -> Option { - data.get(off..off.checked_add(2)?).map(|s| self.u16([s[0], s[1]])) - } - #[inline] - pub fn read_u32(self, data: &[u8], off: usize) -> Option { - data.get(off..off.checked_add(4)?).map(|s| self.u32([s[0], s[1], s[2], s[3]])) - } - #[inline] - pub fn read_u64(self, data: &[u8], off: usize) -> Option { - data.get(off..off.checked_add(8)?).map(|s| self.u64([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) - } - pub fn put_u16(self, out: &mut Vec, v: u16) { - out.extend_from_slice(&match self { - ByteOrder::Little => v.to_le_bytes(), - ByteOrder::Big => v.to_be_bytes(), - }); - } - pub fn put_u32(self, out: &mut Vec, v: u32) { - out.extend_from_slice(&match self { - ByteOrder::Little => v.to_le_bytes(), - ByteOrder::Big => v.to_be_bytes(), - }); - } - pub fn put_u64(self, out: &mut Vec, v: u64) { - out.extend_from_slice(&match self { - ByteOrder::Little => v.to_le_bytes(), - ByteOrder::Big => v.to_be_bytes(), - }); - } -} - -/// TIFF field types (TIFF 6.0 §2 + supplements + BigTIFF). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[repr(u16)] -pub enum FieldType { - Byte = 1, - Ascii = 2, - Short = 3, - Long = 4, - Rational = 5, - SByte = 6, - Undefined = 7, - SShort = 8, - SLong = 9, - SRational = 10, - Float = 11, - Double = 12, - Ifd = 13, - Long8 = 16, - SLong8 = 17, - Ifd8 = 18, -} - -impl FieldType { - pub fn from_u16(v: u16) -> Option { - use FieldType::*; - Some(match v { - 1 => Byte, - 2 => Ascii, - 3 => Short, - 4 => Long, - 5 => Rational, - 6 => SByte, - 7 => Undefined, - 8 => SShort, - 9 => SLong, - 10 => SRational, - 11 => Float, - 12 => Double, - 13 => Ifd, - 16 => Long8, - 17 => SLong8, - 18 => Ifd8, - _ => return None, - }) - } - /// Size in bytes of one value. - pub fn size(self) -> usize { - use FieldType::*; - match self { - Byte | Ascii | SByte | Undefined => 1, - Short | SShort => 2, - Long | SLong | Float | Ifd => 4, - Rational | SRational | Double | Long8 | SLong8 | Ifd8 => 8, - } - } -} - -/// A decoded field value. Arrays are stored in their native type. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub enum Value { - Byte(Vec), - /// ASCII text (bytes up to the first NUL, decoded lossily as UTF-8). - Ascii(String), - Short(Vec), - Long(Vec), - Rational(Vec<(u32, u32)>), - SByte(Vec), - Undefined(Vec), - SShort(Vec), - SLong(Vec), - SRational(Vec<(i32, i32)>), - Float(Vec), - Double(Vec), - Ifd(Vec), - Long8(Vec), - SLong8(Vec), - Ifd8(Vec), -} - -impl Value { - pub fn field_type(&self) -> FieldType { - match self { - Value::Byte(_) => FieldType::Byte, - Value::Ascii(_) => FieldType::Ascii, - Value::Short(_) => FieldType::Short, - Value::Long(_) => FieldType::Long, - Value::Rational(_) => FieldType::Rational, - Value::SByte(_) => FieldType::SByte, - Value::Undefined(_) => FieldType::Undefined, - Value::SShort(_) => FieldType::SShort, - Value::SLong(_) => FieldType::SLong, - Value::SRational(_) => FieldType::SRational, - Value::Float(_) => FieldType::Float, - Value::Double(_) => FieldType::Double, - Value::Ifd(_) => FieldType::Ifd, - Value::Long8(_) => FieldType::Long8, - Value::SLong8(_) => FieldType::SLong8, - Value::Ifd8(_) => FieldType::Ifd8, - } - } - - /// Number of values (for ASCII: bytes including the terminating NUL). - pub fn count(&self) -> usize { - match self { - Value::Byte(v) | Value::Undefined(v) => v.len(), - Value::Ascii(s) => s.len() + 1, - Value::Short(v) => v.len(), - Value::Long(v) | Value::Ifd(v) => v.len(), - Value::Rational(v) => v.len(), - Value::SByte(v) => v.len(), - Value::SShort(v) => v.len(), - Value::SLong(v) => v.len(), - Value::SRational(v) => v.len(), - Value::Float(v) => v.len(), - Value::Double(v) => v.len(), - Value::Long8(v) | Value::Ifd8(v) => v.len(), - Value::SLong8(v) => v.len(), - } - } - - /// Value `i` as `f64` (rationals divided; zero denominators give `None`). ASCII has no numbers. - pub fn get_f64(&self, i: usize) -> Option { - Some(match self { - Value::Byte(v) | Value::Undefined(v) => *v.get(i)? as f64, - Value::Ascii(_) => return None, - Value::Short(v) => *v.get(i)? as f64, - Value::Long(v) | Value::Ifd(v) => *v.get(i)? as f64, - Value::Rational(v) => { - let (n, d) = *v.get(i)?; - if d == 0 { - return None; - } - n as f64 / d as f64 - } - Value::SByte(v) => *v.get(i)? as f64, - Value::SShort(v) => *v.get(i)? as f64, - Value::SLong(v) => *v.get(i)? as f64, - Value::SRational(v) => { - let (n, d) = *v.get(i)?; - if d == 0 { - return None; - } - n as f64 / d as f64 - } - Value::Float(v) => *v.get(i)? as f64, - Value::Double(v) => *v.get(i)?, - Value::Long8(v) | Value::Ifd8(v) => *v.get(i)? as f64, - Value::SLong8(v) => *v.get(i)? as f64, - }) - } - - /// Value `i` as an unsigned integer (integer types only; negative values give `None`). - pub fn get_u64(&self, i: usize) -> Option { - match self { - Value::Byte(v) | Value::Undefined(v) => v.get(i).map(|&x| x as u64), - Value::Short(v) => v.get(i).map(|&x| x as u64), - Value::Long(v) | Value::Ifd(v) => v.get(i).map(|&x| x as u64), - Value::Long8(v) | Value::Ifd8(v) => v.get(i).copied(), - Value::SByte(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()), - Value::SShort(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()), - Value::SLong(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()), - Value::SLong8(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()), - _ => None, - } - } - - /// Value `i` as a signed integer (integer types only). - pub fn get_i64(&self, i: usize) -> Option { - match self { - Value::SByte(v) => v.get(i).map(|&x| x as i64), - Value::SShort(v) => v.get(i).map(|&x| x as i64), - Value::SLong(v) => v.get(i).map(|&x| x as i64), - Value::SLong8(v) => v.get(i).copied(), - _ => self.get_u64(i).and_then(|x| i64::try_from(x).ok()), - } - } - - /// All values as `f64` (missing/invalid entries skipped for rationals with zero denominators → 0). - pub fn to_f64_vec(&self) -> Vec { - (0..self.len_values()).map(|i| self.get_f64(i).unwrap_or(0.0)).collect() - } - - /// All values as `u64` (integer types only; otherwise empty). - pub fn to_u64_vec(&self) -> Vec { - (0..self.len_values()).map_while(|i| self.get_u64(i)).collect() - } - - fn len_values(&self) -> usize { - match self { - Value::Ascii(_) => 0, - _ => self.count(), - } - } - - /// Text for ASCII values (trimmed of trailing NULs / spaces); `Byte`/`Undefined` are decoded as UTF-8 (lossy) - /// up to the first NUL, which covers XMP packets and UCS-less Exif strings. - pub fn as_str(&self) -> Option { - match self { - Value::Ascii(s) => Some(s.trim_end_matches([' ', '\0']).to_string()), - Value::Byte(b) | Value::Undefined(b) => { - let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); - Some(String::from_utf8_lossy(&b[..end]).trim_end().to_string()) - } - _ => None, - } - } - - /// Raw bytes for `Byte` / `Undefined` / `SByte` / `Ascii`. - pub fn as_bytes(&self) -> Option<&[u8]> { - match self { - Value::Byte(b) | Value::Undefined(b) => Some(b), - Value::Ascii(s) => Some(s.as_bytes()), - _ => None, - } - } -} - -/// One IFD entry. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Entry { - pub tag: u16, - pub value: Value, - /// Absolute position in the parsed buffer of the value bytes (inline or out-of-line). - pub offset: u64, -} - -impl Entry { - pub fn field_type(&self) -> FieldType { - self.value.field_type() - } - pub fn count(&self) -> usize { - self.value.count() - } -} - -/// An Image File Directory with its child IFDs already resolved. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Ifd { - /// Absolute offset of the IFD in the buffer. - pub offset: u64, - /// Entries sorted by tag (duplicate tags: the first occurrence wins). - pub entries: Vec, - /// IFDs referenced by `SubIFDs` (330). - pub sub_ifds: Vec, - /// Exif private IFD (34665). - pub exif: Option>, - /// GPS IFD (34853). - pub gps: Option>, - /// Interoperability IFD (40965). - pub interop: Option>, -} - -impl Ifd { - pub fn get(&self, tag: u16) -> Option<&Entry> { - self.entries.binary_search_by_key(&tag, |e| e.tag).ok().map(|i| &self.entries[i]) - } - pub fn contains(&self, tag: u16) -> bool { - self.get(tag).is_some() - } - pub fn value(&self, tag: u16) -> Option<&Value> { - self.get(tag).map(|e| &e.value) - } - /// First value as `u32` (integer types, saturating from wider types). - pub fn u32(&self, tag: u16) -> Option { - self.value(tag)?.get_u64(0).map(|v| v.min(u32::MAX as u64) as u32) - } - pub fn u64(&self, tag: u16) -> Option { - self.value(tag)?.get_u64(0) - } - pub fn u16(&self, tag: u16) -> Option { - self.value(tag)?.get_u64(0).map(|v| v.min(u16::MAX as u64) as u16) - } - pub fn i64(&self, tag: u16) -> Option { - self.value(tag)?.get_i64(0) - } - pub fn f64(&self, tag: u16) -> Option { - self.value(tag)?.get_f64(0) - } - pub fn f64s(&self, tag: u16) -> Option> { - self.value(tag).map(|v| v.to_f64_vec()) - } - pub fn u64s(&self, tag: u16) -> Option> { - self.value(tag).map(|v| v.to_u64_vec()) - } - /// Text value (ASCII, or UTF-8 bytes). - pub fn string(&self, tag: u16) -> Option { - self.value(tag)?.as_str().filter(|s| !s.is_empty()) - } - pub fn bytes(&self, tag: u16) -> Option<&[u8]> { - self.value(tag)?.as_bytes() - } - - /// This IFD and all descendants (sub-IFDs, Exif, GPS, Interop), depth-first, pre-order. - pub fn walk(&self) -> Vec<&Ifd> { - let mut out = vec![self]; - for s in &self.sub_ifds { - out.extend(s.walk()); - } - for c in [&self.exif, &self.gps, &self.interop].into_iter().flatten() { - out.extend(c.walk()); - } - out - } - - /// Image layout of this IFD, if it describes an image. - pub fn image(&self) -> Result { - image::ImageInfo::from_ifd(self) - } -} - -/// A parsed TIFF stream (IFD chain with resolved children). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Tiff { - pub order: ByteOrder, - pub bigtiff: bool, - /// The main IFD chain (IFD0, IFD1, …). - pub ifds: Vec, -} - -impl Tiff { - /// Parse a TIFF stream (the header must be at offset 0 of `data`). - pub fn parse(data: &[u8]) -> Result { - reader::parse(data, &ParseOptions::default()) - } - pub fn parse_with(data: &[u8], opts: &ParseOptions) -> Result { - reader::parse(data, opts) - } - /// Header check only: returns the byte order and BigTIFF flag. - pub fn sniff(data: &[u8]) -> Option<(ByteOrder, bool)> { - reader::header(data).ok().map(|(o, b, _)| (o, b)) - } - /// Every IFD (main chain and all children), depth-first. - pub fn all_ifds(&self) -> Vec<&Ifd> { - self.ifds.iter().flat_map(|i| i.walk()).collect() - } - /// The Exif IFD attached to IFD0 (or any IFD). - pub fn exif(&self) -> Option<&Ifd> { - self.all_ifds().into_iter().find_map(|i| i.exif.as_deref()) - } - pub fn gps(&self) -> Option<&Ifd> { - self.all_ifds().into_iter().find_map(|i| i.gps.as_deref()) - } - /// First entry for `tag` in IFD0, then the Exif IFD, then any IFD. - pub fn find(&self, tag: u16) -> Option<&Entry> { - if let Some(e) = self.ifds.first().and_then(|i| i.get(tag)) { - return Some(e); - } - if let Some(e) = self.exif().and_then(|i| i.get(tag)) { - return Some(e); - } - self.all_ifds().into_iter().find_map(|i| i.get(tag)) - } -} diff --git a/crates/tiff/src/makernote.rs b/crates/tiff/src/makernote.rs deleted file mode 100644 index 288b366f64..0000000000 --- a/crates/tiff/src/makernote.rs +++ /dev/null @@ -1,235 +0,0 @@ -//! Maker-note IFD helpers. -//! -//! Most vendors store their maker note (Exif tag 37500) as a TIFF IFD, but each uses its own header, -//! byte order and *offset base* (what stored value offsets are relative to). The header layouts here -//! follow the public descriptions in the ExifTool tag documentation (`MakerNotes` table) and the -//! vendors' own published notes; no third-party code was consulted. - -use crate::{ByteOrder, Ifd, ParseOptions, parse_ifd_at}; -use serde::{Deserialize, Serialize}; - -/// Maker-note dialects we know how to locate. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum MakerNoteKind { - /// Plain IFD at the start of the note, offsets relative to the enclosing TIFF header (Canon, many others). - Plain, - /// `Nikon\0` + version + embedded TIFF header at +10; offsets relative to that header. - NikonV3, - /// `Nikon\0\x01\0`: IFD at +8, offsets relative to the enclosing TIFF header. - NikonV1, - /// `SONY DSC `/`SONY CAM `/`SONY MOBILE` etc.: 12-byte header, offsets relative to the TIFF header. - Sony, - /// `FUJIFILM` + LE u32 IFD offset; little-endian, offsets relative to the note start. - Fujifilm, - /// `OLYMPUS\0` + byte order + version: IFD at +12, offsets relative to the note start. - OlympusNew, - /// `OLYMP\0` / `EPSON\0` etc.: IFD at +8, offsets relative to the TIFF header. - OlympusOld, - /// `Panasonic\0\0\0`: IFD at +12, offsets relative to the TIFF header. - Panasonic, - /// `AOC\0` + byte order: IFD at +6, offsets relative to the TIFF header. - PentaxAoc, - /// `PENTAX \0` + byte order: IFD at +10, offsets relative to the note start. - Pentax, -} - -/// A parsed maker-note IFD. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct MakerNote { - pub kind: MakerNoteKind, - pub order: ByteOrder, - /// Absolute offset that stored value offsets are relative to. - pub base: u64, - pub ifd: Ifd, -} - -/// Locate and parse the maker note stored at absolute `offset` (length `len`) inside `data`, the buffer whose -/// start is the enclosing TIFF header. `order` is the enclosing stream's byte order. `make` (the Exif Make) is -/// used only as a hint for header-less notes. Returns `None` for unknown or unparsable notes. -pub fn parse_makernote(data: &[u8], offset: u64, len: u64, order: ByteOrder, make: &str) -> Option { - let start = usize::try_from(offset).ok()?; - let end = start.checked_add(usize::try_from(len).ok()?)?.min(data.len()); - let note = data.get(start..end)?; - let order_at = |i: usize| match note.get(i..i + 2) { - Some(b"II") => Some(ByteOrder::Little), - Some(b"MM") => Some(ByteOrder::Big), - _ => None, - }; - // A fixed value budget: a maker note is at most tens of kilobytes of values in any honest file, and - // computing the budget from the buffer's length multiplies the file length (a hostile entry in a - // sparse header-read buffer, where the buffer holds the file's logical size but only a few - // kilobytes are loaded, would decode allocations no actual data backs). - let opts = ParseOptions { max_ifds: 64, max_depth: 3, value_budget: Some(1 << 20), ..Default::default() }; - let try_parse = |kind: MakerNoteKind, ifd_at: u64, base: u64, ord: ByteOrder| -> Option { - let (ifd, _) = parse_ifd_at(data, ifd_at, ord, base, false, &opts).ok()?; - (!ifd.entries.is_empty()).then_some(MakerNote { kind, order: ord, base, ifd }) - }; - if note.starts_with(b"Nikon\0") { - if note.get(6) == Some(&1) { - return try_parse(MakerNoteKind::NikonV1, offset + 8, 0, order); - } - let ord = order_at(10)?; - let ifd_rel = ord.read_u32(note, 14)? as u64; - let base = offset + 10; - return try_parse(MakerNoteKind::NikonV3, base + ifd_rel, base, ord); - } - if note.starts_with(b"FUJIFILM") || note.starts_with(b"GENERALE") { - let rel = ByteOrder::Little.read_u32(note, 8)? as u64; - return try_parse(MakerNoteKind::Fujifilm, offset + rel, offset, ByteOrder::Little); - } - if note.starts_with(b"OLYMPUS\0") || note.starts_with(b"OM SYSTEM\0") { - let (ord_at, ifd_at) = if note.starts_with(b"OM SYSTEM\0") { (12, 16) } else { (8, 12) }; - let ord = order_at(ord_at).unwrap_or(order); - return try_parse(MakerNoteKind::OlympusNew, offset + ifd_at, offset, ord); - } - for p in [b"OLYMP\0", b"EPSON\0", b"MINOL\0", b"CAMER\0", b"SANYO\0"] { - if note.starts_with(p) { - return try_parse(MakerNoteKind::OlympusOld, offset + 8, 0, order); - } - } - if note.starts_with(b"Panasonic\0") { - return try_parse(MakerNoteKind::Panasonic, offset + 12, 0, order); - } - if note.starts_with(b"AOC\0") { - let ord = order_at(4).unwrap_or(order); - return try_parse(MakerNoteKind::PentaxAoc, offset + 6, 0, ord); - } - if note.starts_with(b"PENTAX \0") { - let ord = order_at(8).unwrap_or(order); - return try_parse(MakerNoteKind::Pentax, offset + 10, offset, ord); - } - if (note.starts_with(b"SONY") || note.starts_with(b"VHAB \0")) - && let Some(m) = try_parse(MakerNoteKind::Sony, offset + 12, 0, order) - { - return Some(m); - } - let _ = make; - try_parse(MakerNoteKind::Plain, offset, 0, order) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{IfdBuilder, TiffWriter, Value, tags}; - - /// Build a TIFF whose Exif IFD carries `note` as the maker note, return (bytes, note offset, len). - fn with_note(order: ByteOrder, note: Vec) -> (Vec, u64, u64) { - let mut exif = IfdBuilder::new(); - exif.set(tags::MAKER_NOTE, Value::Undefined(note)); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(tags::MAKE, Value::Ascii("Test".into())); - ifd0.set_child(tags::EXIF_IFD, exif); - let bytes = TiffWriter { order, bigtiff: false }.write(&[ifd0]).unwrap(); - let t = crate::Tiff::parse(&bytes).unwrap(); - let e = t.exif().unwrap().get(tags::MAKER_NOTE).unwrap(); - let (off, len) = (e.offset, e.count() as u64); - (bytes, off, len) - } - - /// An IFD with one SHORT entry (tag 1, value 7) and one out-of-line LONG[2] entry at `rel` (relative to base). - fn tiny_ifd(order: ByteOrder, rel_values: u32) -> Vec { - let mut v = Vec::new(); - order.put_u16(&mut v, 2); - order.put_u16(&mut v, 1); - order.put_u16(&mut v, 3); - order.put_u32(&mut v, 1); - order.put_u16(&mut v, 7); - order.put_u16(&mut v, 0); - order.put_u16(&mut v, 2); - order.put_u16(&mut v, 4); - order.put_u32(&mut v, 2); - order.put_u32(&mut v, rel_values); - order.put_u32(&mut v, 0); - v - } - - #[test] - fn nikon_v3_uses_embedded_header_base() { - for order in [ByteOrder::Little, ByteOrder::Big] { - let mut note = b"Nikon\0\x02\x10\0\0".to_vec(); - let hdr_at = note.len(); - note.extend_from_slice(if order == ByteOrder::Little { b"II" } else { b"MM" }); - order.put_u16(&mut note, 42); - order.put_u32(&mut note, 8); - // IFD at +8 (relative to embedded header), values after IFD: 8 + 2 + 24 + 4 = 38 - note.extend(tiny_ifd(order, 38)); - order.put_u32(&mut note, 111); - order.put_u32(&mut note, 222); - let (bytes, off, len) = with_note(order, note); - let m = parse_makernote(&bytes, off, len, order, "NIKON CORPORATION").unwrap(); - assert_eq!(m.kind, MakerNoteKind::NikonV3); - assert_eq!(m.base, off + hdr_at as u64); - assert_eq!(m.ifd.u32(1), Some(7)); - assert_eq!(m.ifd.u64s(2).unwrap(), vec![111, 222]); - } - } - - #[test] - fn fujifilm_offsets_relative_to_note() { - let mut note = b"FUJIFILM".to_vec(); - ByteOrder::Little.put_u32(&mut note, 12); - // IFD at 12 (relative to note), values at 12 + 30 = 42 - note.extend(tiny_ifd(ByteOrder::Little, 42)); - ByteOrder::Little.put_u32(&mut note, 5); - ByteOrder::Little.put_u32(&mut note, 6); - // enclosing file is big-endian: Fuji notes are always little-endian - let (bytes, off, len) = with_note(ByteOrder::Big, note); - let m = parse_makernote(&bytes, off, len, ByteOrder::Big, "FUJIFILM").unwrap(); - assert_eq!(m.kind, MakerNoteKind::Fujifilm); - assert_eq!(m.order, ByteOrder::Little); - assert_eq!(m.ifd.u64s(2).unwrap(), vec![5, 6]); - } - - #[test] - fn plain_canon_style_note() { - // Plain IFD whose out-of-line offset is relative to the TIFF header: we need the absolute - // position, which we only know after writing. Write once to learn the offset, then patch. - let order = ByteOrder::Little; - let mut note = tiny_ifd(order, 0); - note.extend_from_slice(&[0; 8]); - let (mut bytes, off, len) = with_note(order, note); - let values_abs = off as u32 + 30; - bytes[off as usize + 22..off as usize + 26].copy_from_slice(&values_abs.to_le_bytes()); - bytes[off as usize + 30..off as usize + 34].copy_from_slice(&9u32.to_le_bytes()); - let m = parse_makernote(&bytes, off, len, order, "Canon").unwrap(); - assert_eq!(m.kind, MakerNoteKind::Plain); - assert_eq!(m.ifd.u64s(2).unwrap(), vec![9, 0]); - } - - /// A maker note's value budget is fixed, not computed from the length of the buffer it sits in: - /// an entry claiming more than the note budget (here 2 MB) is dropped, a fitting one is read. In a - /// sparse header read the buffer holds the file's logical size while only kilobytes were loaded, - /// so a length-scaled budget would let an unrelated entry decode megabytes of zeros (see the focus - /// reader, try_read_exif_with). - #[test] - fn a_note_entry_past_the_fixed_value_budget_is_dropped() { - let order = ByteOrder::Little; - let mut note = b"SONY DSC \0\0\0".to_vec(); - // the Sony IFD directly after the 12-byte header, one fitting BYTE entry and a decoy - // BYTE[2 MB] entry pointing into the file's own (zero-filled) body - order.put_u16(&mut note, 2); - order.put_u16(&mut note, 0x201b); - order.put_u16(&mut note, 1); - order.put_u32(&mut note, 1); - note.extend([3, 0, 0, 0]); - order.put_u16(&mut note, 0x9900); - order.put_u16(&mut note, 1); - order.put_u32(&mut note, 2 << 20); - order.put_u32(&mut note, 200); - order.put_u32(&mut note, 0); - let mut bytes = note.clone(); - bytes.resize(200 + (2 << 20), 0); // the decoy's value range is inside the real bytes - let m = parse_makernote(&bytes, 0, note.len() as u64, order, "SONY").unwrap(); - assert_eq!(m.kind, MakerNoteKind::Sony); - assert!(m.ifd.get(0x201b).is_some(), "the fitting entry is read"); - assert!(m.ifd.get(0x9900).is_none(), "the decoy is dropped by the value budget"); - } - - #[test] - fn garbage_note_is_none() { - let (bytes, off, len) = with_note(ByteOrder::Little, vec![0xff; 40]); - assert!(parse_makernote(&bytes, off, len, ByteOrder::Little, "X").is_none()); - assert!(parse_makernote(&bytes, 1 << 40, 10, ByteOrder::Little, "X").is_none()); - assert!(parse_makernote(&bytes, off, u64::MAX, ByteOrder::Little, "X").is_none()); - } -} diff --git a/crates/tiff/src/reader.rs b/crates/tiff/src/reader.rs deleted file mode 100644 index 70c66c5a74..0000000000 --- a/crates/tiff/src/reader.rs +++ /dev/null @@ -1,536 +0,0 @@ -//! Bounds-checked IFD parsing. - -use crate::{ByteOrder, Entry, FieldType, Ifd, Result, Tiff, TiffError, Value, tags}; -use std::collections::HashSet; - -/// Limits applied while parsing. The defaults are generous for real files and safe for hostile ones. -#[derive(Clone, Debug)] -pub struct ParseOptions { - /// Maximum number of IFDs visited in total (chain + children). - pub max_ifds: usize, - /// Maximum nesting depth of child IFDs. - pub max_depth: usize, - /// Maximum number of entries read from one IFD. - pub max_entries: usize, - /// Maximum total number of entries read across all IFDs (chain + children). - /// - /// Hostile files can reuse the same bytes for up to `max_ifds` tables of `max_entries` - /// entries each (overlapping IFD tables via SubIFD pointers shifted by one entry), which can - /// allocate millions of `Entry`s from a small input (~100 KB → ~400 MB). This hard cap bounds - /// that amplification regardless of entry size. 65 536 is generous for real files — a 50 MB - /// scanned TIFF with thousands of entries across chain + children stays well under it — yet - /// stops a small file from allocating hundreds of megabytes of `Entry`s. - pub max_entries_total: usize, - /// Maximum total bytes of decoded values; `None` = `8 × input length + 1 MiB`. - pub value_budget: Option, - /// Follow `SubIFDs` / Exif / GPS / Interop pointers. - pub follow_children: bool, - /// Accept the TIFF-like magic numbers used by some raw formats (ORF `IIRO`/`IIRS`, RW2 `IIU`). - pub accept_raw_magic: bool, -} - -impl Default for ParseOptions { - fn default() -> Self { - Self { - max_ifds: 1024, - max_depth: 10, - max_entries: 8192, - max_entries_total: 65536, - value_budget: None, - follow_children: true, - accept_raw_magic: true, - } - } -} - -impl ParseOptions { - /// The value budget for `data_len` bytes of input: [`Self::value_budget`], else `8 × data_len + 1 MiB`. - pub fn budget_for(&self, data_len: usize) -> u64 { - self.value_budget.unwrap_or((data_len as u64).saturating_mul(8).saturating_add(1 << 20)) - } -} - -/// Where a directory's entries are and how many of them the reader reads, as [`directory_entries`] found them. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct DirectoryEntries { - /// Position of the first entry. - table: usize, - /// Entries read: the declared count, cut to the entries the data holds and to the `max_entries` limit. - read: usize, - /// The declared entry count. - declared: u64, - /// Bytes per entry: 12, or 20 in BigTIFF. - entry_size: usize, -} - -impl DirectoryEntries { - /// Positions of the entries read, in directory order. Checked arithmetic: the iteration ends rather than - /// overflow, whatever the layout. - pub fn positions(&self) -> impl Iterator + use<> { - let (table, size) = (self.table, self.entry_size); - (0..self.read).map_while(move |i| i.checked_mul(size)?.checked_add(table)) - } - - /// The number of entries read. - pub fn read(&self) -> usize { - self.read - } - - /// The entry count the directory declares. - pub fn declared(&self) -> u64 { - self.declared - } -} - -/// The directory at `offset` as the reader walks it: its entry table and how many entries it reads. The same errors -/// as [`parse_ifd_at`] for a directory it can't read: past the data, empty, or without room for one entry. -pub fn directory_entries(data: &[u8], offset: u64, order: ByteOrder, bigtiff: bool, max_entries: usize) -> Result { - let pos = usize::try_from(offset).map_err(|_| TiffError::Truncated(offset))?; - let (n, head, entry_size) = if bigtiff { - (order.read_u64(data, pos).ok_or(TiffError::Truncated(offset))?, 8usize, 20usize) - } else { - (order.read_u16(data, pos).ok_or(TiffError::Truncated(offset))? as u64, 2, 12) - }; - let table = pos + head; - let fit = (data.len().saturating_sub(table) / entry_size) as u64; - let read = n.min(fit).min(max_entries as u64) as usize; - if n == 0 { - return Err(TiffError::Invalid(format!("empty IFD at {offset}"))); - } - if read == 0 { - return Err(TiffError::Truncated(offset)); - } - Ok(DirectoryEntries { table, read, declared: n, entry_size }) -} - -/// A directory entry the reader can read: its tag, type and count, and where its values are. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct EntrySpan { - pub tag: u16, - pub field_type: FieldType, - pub count: u64, - /// Position of the values in the data: the entry's own value field when they fit it, else `base` plus the offset - /// stored there. - pub start: u64, - /// `count × size` bytes. - pub len: u64, -} - -/// The entry at `pos`, when the reader reads it: a known field type, `count × size` without overflow, and values -/// inside `data`. Nothing is decoded; [`parse_ifd_at`] also drops an entry whose values exceed what is left of its -/// value budget ([`ParseOptions::budget_for`]), which this leaves to the caller. -pub fn entry_span(data: &[u8], pos: usize, order: ByteOrder, bigtiff: bool, base: u64) -> Option { - let tag = order.read_u16(data, pos)?; - let field_type = FieldType::from_u16(order.read_u16(data, pos.checked_add(2)?)?)?; - let (count, field, inline) = if bigtiff { - (order.read_u64(data, pos.checked_add(4)?)?, pos.checked_add(12)?, 8u64) - } else { - (order.read_u32(data, pos.checked_add(4)?)? as u64, pos.checked_add(8)?, 4) - }; - let len = count.checked_mul(field_type.size() as u64)?; - let start = if len <= inline { - field as u64 - } else { - let rel = if bigtiff { order.read_u64(data, field)? } else { order.read_u32(data, field)? as u64 }; - base.checked_add(rel)? - }; - let end = start.checked_add(len)?; - (end <= data.len() as u64).then_some(EntrySpan { tag, field_type, count, start, len }) -} - -/// Whether a directory declaring `declared` entries was read whole (`read` entries), so that its next-IFD pointer -/// follows them. The counts compare as 64-bit numbers: narrowing the declared count to `usize` instead would, on a -/// 32-bit target, let a BigTIFF declaring 4,294,967,297 entries but holding one pass for a whole directory. -fn reads_every_entry(declared: u64, read: usize) -> bool { - u64::try_from(read).is_ok_and(|read| read == declared) -} - -/// Parse the header: (byte order, bigtiff, first IFD offset). -pub(crate) fn header(data: &[u8]) -> Result<(ByteOrder, bool, u64)> { - header_with(data, true) -} - -fn header_with(data: &[u8], raw_magic: bool) -> Result<(ByteOrder, bool, u64)> { - let order = match data.get(0..2) { - Some(b"II") => ByteOrder::Little, - Some(b"MM") => ByteOrder::Big, - _ => return Err(TiffError::NotTiff), - }; - let magic = order.read_u16(data, 2).ok_or(TiffError::NotTiff)?; - match magic { - 42 => Ok((order, false, order.read_u32(data, 4).ok_or(TiffError::Truncated(4))? as u64)), - 43 => { - let bytesize = order.read_u16(data, 4).ok_or(TiffError::Truncated(4))?; - let zero = order.read_u16(data, 6).ok_or(TiffError::Truncated(6))?; - if bytesize != 8 || zero != 0 { - return Err(TiffError::NotTiff); - } - Ok((order, true, order.read_u64(data, 8).ok_or(TiffError::Truncated(8))?)) - } - 0x4f52 | 0x5352 | 0x0055 if raw_magic => Ok((order, false, order.read_u32(data, 4).ok_or(TiffError::Truncated(4))? as u64)), - _ => Err(TiffError::NotTiff), - } -} - -pub(crate) fn parse(data: &[u8], opts: &ParseOptions) -> Result { - let (order, big, first) = header_with(data, opts.accept_raw_magic)?; - let mut ctx = Ctx::new(data, order, big, opts); - let mut ifds = Vec::new(); - let mut off = first; - while off != 0 { - match ctx.ifd(off, 0, 0) { - Ok((ifd, next)) => { - ifds.push(ifd); - off = next; - } - Err(e) => { - if ifds.is_empty() { - return Err(e); - } - break; - } - } - } - if ifds.is_empty() { - return Err(TiffError::Invalid("no IFDs".into())); - } - Ok(Tiff { order, bigtiff: big, ifds }) -} - -/// Parse one IFD at absolute `offset` whose value offsets (and child IFD pointers) are relative to -/// `base` (absolute position = `base + stored offset`). Returns the IFD and the absolute offset of the -/// next IFD (0 when there is none). Used for maker notes, which often use their own offset base. -pub fn parse_ifd_at(data: &[u8], offset: u64, order: ByteOrder, base: u64, bigtiff: bool, opts: &ParseOptions) -> Result<(Ifd, u64)> { - let mut ctx = Ctx::new(data, order, bigtiff, opts); - ctx.ifd(offset, base, 0) -} - -struct Ctx<'a> { - data: &'a [u8], - order: ByteOrder, - big: bool, - opts: &'a ParseOptions, - visited: HashSet, - budget: u64, - entries_total: usize, -} - -impl<'a> Ctx<'a> { - fn new(data: &'a [u8], order: ByteOrder, big: bool, opts: &'a ParseOptions) -> Self { - let budget = opts.budget_for(data.len()); - Self { data, order, big, opts, visited: HashSet::new(), budget, entries_total: 0 } - } - - fn read_off(&self, pos: usize) -> Option { - if self.big { self.order.read_u64(self.data, pos) } else { self.order.read_u32(self.data, pos).map(|v| v as u64) } - } - - /// Returns (ifd, absolute next offset or 0). - fn ifd(&mut self, offset: u64, base: u64, depth: usize) -> Result<(Ifd, u64)> { - if depth > self.opts.max_depth { - return Err(TiffError::Limit("IFD nesting depth")); - } - if self.visited.len() >= self.opts.max_ifds { - return Err(TiffError::Limit("IFD count")); - } - if !self.visited.insert(offset) { - return Err(TiffError::Invalid(format!("IFD loop at {offset}"))); - } - let dir = directory_entries(self.data, offset, self.order, self.big, self.opts.max_entries)?; - // Bound total entries across the whole parse so overlapping IFD tables (SubIFD pointers - // shifted by one entry) cannot allocate millions of `Entry`s from a small input. - self.entries_total = self.entries_total.saturating_add(dir.read); - if self.entries_total > self.opts.max_entries_total { - return Err(TiffError::Limit("entry count")); - } - let mut entries = Vec::with_capacity(dir.read); - for p in dir.positions() { - if let Some(e) = self.entry(p, base) { - entries.push(e); - } - } - entries.sort_by_key(|e| e.tag); - entries.dedup_by_key(|e| e.tag); - // the next-IFD pointer follows the last entry, read only when every declared entry was (checked: a BigTIFF - // count can be anything up to u64::MAX) - let next = if reads_every_entry(dir.declared, dir.read) { - match dir.read.checked_mul(dir.entry_size).and_then(|n| n.checked_add(dir.table)).and_then(|p| self.read_off(p)) { - Some(0) | None => 0, - Some(v) => base.checked_add(v).unwrap_or(0), - } - } else { - 0 - }; - let mut ifd = Ifd { offset, entries, ..Default::default() }; - if self.opts.follow_children { - self.children(&mut ifd, base, depth); - } - Ok((ifd, next)) - } - - fn children(&mut self, ifd: &mut Ifd, base: u64, depth: usize) { - if let Some(v) = ifd.value(tags::SUB_IFDS) { - let offs = v.to_u64_vec(); - for o in offs { - if let Some(abs) = base.checked_add(o) - && let Ok((sub, _)) = self.ifd(abs, base, depth + 1) - { - ifd.sub_ifds.push(sub); - } - } - } - let child = |tag: u16, ctx: &mut Self| -> Option> { - let o = ifd.value(tag)?.get_u64(0)?; - let abs = base.checked_add(o)?; - ctx.ifd(abs, base, depth + 1).ok().map(|(i, _)| Box::new(i)) - }; - let exif = child(tags::EXIF_IFD, self); - let gps = child(tags::GPS_IFD, self); - let interop = child(tags::INTEROP_IFD, self); - ifd.exif = exif; - ifd.gps = gps; - ifd.interop = interop; - } - - fn entry(&mut self, p: usize, base: u64) -> Option { - let span = entry_span(self.data, p, self.order, self.big, base)?; - if span.len > self.budget { - return None; - } - self.budget -= span.len; - let bytes = self.data.get(usize::try_from(span.start).ok()?..usize::try_from(span.start + span.len).ok()?)?; - Some(Entry { tag: span.tag, value: decode(self.order, span.field_type, bytes), offset: span.start }) - } -} - -/// Decode `bytes` (exactly `count × size` long, or the first values of an entry) as values of type `typ`. -pub fn decode(o: ByteOrder, typ: FieldType, b: &[u8]) -> Value { - fn arr(c: &[u8]) -> [u8; N] { - let mut a = [0u8; N]; - a.copy_from_slice(c); - a - } - match typ { - FieldType::Byte => Value::Byte(b.to_vec()), - FieldType::Undefined => Value::Undefined(b.to_vec()), - FieldType::Ascii => { - let end = b.iter().position(|&c| c == 0).unwrap_or(b.len()); - Value::Ascii(String::from_utf8_lossy(&b[..end]).into_owned()) - } - FieldType::SByte => Value::SByte(b.iter().map(|&x| x as i8).collect()), - FieldType::Short => Value::Short(b.as_chunks::<2>().0.iter().map(|c| o.u16(arr(c))).collect()), - FieldType::SShort => Value::SShort(b.as_chunks::<2>().0.iter().map(|c| o.u16(arr(c)) as i16).collect()), - FieldType::Long => Value::Long(b.as_chunks::<4>().0.iter().map(|c| o.u32(arr(c))).collect()), - FieldType::Ifd => Value::Ifd(b.as_chunks::<4>().0.iter().map(|c| o.u32(arr(c))).collect()), - FieldType::SLong => Value::SLong(b.as_chunks::<4>().0.iter().map(|c| o.u32(arr(c)) as i32).collect()), - FieldType::Float => Value::Float(b.as_chunks::<4>().0.iter().map(|c| f32::from_bits(o.u32(arr(c)))).collect()), - FieldType::Rational => Value::Rational(b.as_chunks::<8>().0.iter().map(|c| (o.u32(arr(&c[..4])), o.u32(arr(&c[4..])))).collect()), - FieldType::SRational => { - Value::SRational(b.as_chunks::<8>().0.iter().map(|c| (o.u32(arr(&c[..4])) as i32, o.u32(arr(&c[4..])) as i32)).collect()) - } - FieldType::Double => Value::Double(b.as_chunks::<8>().0.iter().map(|c| f64::from_bits(o.u64(arr(c)))).collect()), - FieldType::Long8 => Value::Long8(b.as_chunks::<8>().0.iter().map(|c| o.u64(arr(c))).collect()), - FieldType::Ifd8 => Value::Ifd8(b.as_chunks::<8>().0.iter().map(|c| o.u64(arr(c))).collect()), - FieldType::SLong8 => Value::SLong8(b.as_chunks::<8>().0.iter().map(|c| o.u64(arr(c)) as i64).collect()), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Value; - use crate::tags as t; - use crate::writer::{IfdBuilder, TiffWriter}; - - /// A value budget the caller sets bounds what is decoded: an entry claiming more value bytes than - /// the budget allows is dropped, entries that fit are read (the sparse header-read path, where the - /// buffer holds the file's logical size but only a few kilobytes were ever loaded, sizes its - /// budget from what was fetched, not from whatever length the file claims). - #[test] - fn the_value_budget_drops_over_budget_entries_and_keeps_the_rest() { - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("Keep".into())); - ifd0.set(0x9000, Value::Byte(vec![0; 2 << 20])); - let file = TiffWriter { order: ByteOrder::Little, bigtiff: false }.write(&[ifd0]).unwrap(); - let opts = ParseOptions { value_budget: Some(1 << 20), ..Default::default() }; - let tiff = Tiff::parse_with(&file, &opts).unwrap(); - assert_eq!(tiff.ifds[0].string(t::MAKE), Some("Keep".to_string()), "a fitting entry is read"); - assert!(tiff.ifds[0].get(0x9000).is_none(), "the over-budget entry is dropped"); - } - - /// A BigTIFF whose first IFD, at 80, declares `declared` entries but holds one, followed by a next-IFD pointer - /// `next`; a valid one-entry IFD sits at 16. - fn bigtiff_chain(order: ByteOrder, declared: u64, next: u64) -> Vec { - let ifd = |d: &mut Vec, count: u64, tag: u16, next: u64| { - order.put_u64(d, count); - order.put_u16(d, tag); - order.put_u16(d, 3); - order.put_u64(d, 1); - order.put_u16(d, 8); - d.extend([0; 6]); - order.put_u64(d, next); - }; - let mut d = if order == ByteOrder::Little { b"II".to_vec() } else { b"MM".to_vec() }; - order.put_u16(&mut d, 43); - order.put_u16(&mut d, 8); - order.put_u16(&mut d, 0); - order.put_u64(&mut d, 80); - ifd(&mut d, 1, 0x0101, 0); - d.resize(80, 0); - ifd(&mut d, declared, 0x0100, next); - d - } - - #[test] - fn only_a_directory_read_whole_has_a_next_pointer() { - // the comparison itself, on every target: a declared count past u32::MAX never matches a small read count - for (declared, read, whole) in [ - (0, 0, true), - (1, 1, true), - (8192, 8192, true), - (8193, 8192, false), - (1, 0, false), - ((1 << 32) + 1, 1, false), - ((2 << 32) + 1, 1, false), - ((1 << 63) + 1, 1, false), - (u64::MAX, 1, false), - ] { - assert_eq!(reads_every_entry(declared, read), whole, "{declared} declared, {read} read"); - } - } - - #[test] - fn a_bigtiff_count_past_u32_max_never_follows_the_next_pointer() { - // the whole chain: on 32-bit targets (wasm32) the old cast truncated these counts to 1 and followed the pointer - for order in [ByteOrder::Little, ByteOrder::Big] { - for declared in [(1u64 << 32) + 1, (2u64 << 32) + 1, (1u64 << 63) + 1] { - let d = bigtiff_chain(order, declared, 16); - let tiff = Tiff::parse(&d).unwrap(); - assert_eq!(tiff.ifds.len(), 1, "{order:?} {declared}"); - assert_eq!(tiff.ifds[0].u64(0x0100), Some(8)); - assert_eq!(parse_ifd_at(&d, 80, order, 0, true, &ParseOptions::default()).unwrap().1, 0, "{order:?} {declared}"); - } - // control: the same file declaring its one entry follows the pointer to the IFD at 16 - let whole = Tiff::parse(&bigtiff_chain(order, 1, 16)).unwrap(); - assert_eq!(whole.ifds.len(), 2, "{order:?}"); - assert_eq!(whole.ifds[1].u64(0x0101), Some(8)); - } - } - - #[test] - fn directory_positions_never_overflow() { - // a hand-built layout the reader never produces: the iterator stops instead of overflowing - let hostile = DirectoryEntries { table: usize::MAX, read: 2, declared: 2, entry_size: 12 }; - assert_eq!(hostile.positions().collect::>(), vec![usize::MAX]); - assert_eq!(hostile.positions().nth(1), None); - let wide = DirectoryEntries { table: usize::MAX - 30, read: 4, declared: 4, entry_size: 12 }; - assert_eq!(wide.positions().collect::>(), vec![usize::MAX - 30, usize::MAX - 18, usize::MAX - 6]); - // a directory read from data lists its entries - let mut data = Vec::new(); - ByteOrder::Little.put_u16(&mut data, 2); - data.extend([0; 24]); - let dir = directory_entries(&data, 0, ByteOrder::Little, false, 8192).unwrap(); - assert_eq!(dir.positions().collect::>(), vec![2, 14]); - } - - #[test] - fn a_bigtiff_directory_declaring_u64_max_entries_parses_without_overflow() { - // 44 bytes: BigTIFF header (first IFD at 16), an entry count of u64::MAX, one 20-byte entry - let mut data = b"II\x2b\x00\x08\x00\x00\x00".to_vec(); - data.extend(16u64.to_le_bytes()); - data.extend(u64::MAX.to_le_bytes()); - data.extend(0x0100u16.to_le_bytes()); - data.extend(3u16.to_le_bytes()); - data.extend(1u64.to_le_bytes()); - data.extend([8, 0, 0, 0, 0, 0, 0, 0]); - assert_eq!(data.len(), 44); - let tiff = Tiff::parse(&data).unwrap(); - assert_eq!(tiff.ifds.len(), 1); - assert_eq!(tiff.ifds[0].u64(0x0100), Some(8)); - } - #[test] - fn overlapping_ifd_tables_hit_entry_cap_instead_of_amplifying() { - // classic TIFF; IFDs at 8, 20, 32, ... each declaring 8192 entries whose tables overlap - // (next table starts one entry after the previous table's start). Without the cap, a single - // `Tiff::parse` would run `Vec::with_capacity(8192)` per IFD inside one `Ctx`, amplifying a - // small file into millions of `Entry`s; the per-`Ctx` `max_entries_total` cap rejects the - // 9th IFD before any allocation. - let mut data = vec![0u8; 200_000]; - data[0..2].copy_from_slice(b"II"); - data[2..4].copy_from_slice(&42u16.to_le_bytes()); - data[4..8].copy_from_slice(&8u32.to_le_bytes()); // first IFD at 8 - - for k in 0..9u64 { - let ifd_off = (8 + 12 * k) as usize; - data[ifd_off..ifd_off + 2].copy_from_slice(&8192u16.to_le_bytes()); // count - let table = ifd_off + 2; - let ptr = table + 8192 * 12; // next-IFD pointer lives right after the entries - let next = if k + 1 < 9 { (8 + 12 * (k + 1)) as u32 } else { 0 }; - data[ptr..ptr + 4].copy_from_slice(&next.to_le_bytes()); - } - - let tiff = Tiff::parse(&data).unwrap(); - assert_eq!(tiff.ifds.len(), 8, "8 IFDs parsed, 9th rejected by max_entries_total before allocation"); - } - - #[test] - fn a_legitimate_multi_ifd_file_still_parses_under_the_entry_cap() { - // classic TIFF: IFD0 @8 (3 entries: value + Exif + GPS child pointers) -> IFD1 @58 chain, - // plus Exif child @60 and GPS child @90. Total entries = 6, far under max_entries_total. - let mut data = vec![0u8; 128]; - data[0..2].copy_from_slice(b"II"); - data[2..4].copy_from_slice(&42u16.to_le_bytes()); - data[4..8].copy_from_slice(&8u32.to_le_bytes()); // first IFD at 8 - - // IFD0 @8: count 3, table @10, next-IFD @46 -> IFD1 @58 - data[8..10].copy_from_slice(&3u16.to_le_bytes()); - // entry0 @10: tag 0x0100, SHORT, count 1, value 8 (inline @18..22) - data[10..12].copy_from_slice(&0x0100u16.to_le_bytes()); - data[12..14].copy_from_slice(&3u16.to_le_bytes()); - data[14..18].copy_from_slice(&1u32.to_le_bytes()); - data[18..22].copy_from_slice(&8u32.to_le_bytes()); - // entry1 @22: tag 0x8769 ExifIFD, LONG, count 1, value 60 (inline @30..34) - data[22..24].copy_from_slice(&0x8769u16.to_le_bytes()); - data[24..26].copy_from_slice(&4u16.to_le_bytes()); - data[26..30].copy_from_slice(&1u32.to_le_bytes()); - data[30..34].copy_from_slice(&60u32.to_le_bytes()); - // entry2 @34: tag 0x8825 GPSIFD, LONG, count 1, value 90 (inline @42..46) - data[34..36].copy_from_slice(&0x8825u16.to_le_bytes()); - data[36..38].copy_from_slice(&4u16.to_le_bytes()); - data[38..42].copy_from_slice(&1u32.to_le_bytes()); - data[42..46].copy_from_slice(&90u32.to_le_bytes()); - data[46..50].copy_from_slice(&58u32.to_le_bytes()); // next IFD - - // IFD1 @58: count 1, table @60, next 0 - data[58..60].copy_from_slice(&1u16.to_le_bytes()); - data[60..62].copy_from_slice(&0x0100u16.to_le_bytes()); - data[62..64].copy_from_slice(&3u16.to_le_bytes()); - data[64..68].copy_from_slice(&1u32.to_le_bytes()); - data[68..72].copy_from_slice(&8u32.to_le_bytes()); - data[72..76].copy_from_slice(&0u32.to_le_bytes()); - - // Exif child IFD @60: count 1, entry tag 0x9000 value 1, next 0 - data[60..62].copy_from_slice(&1u16.to_le_bytes()); - data[62..64].copy_from_slice(&0x9000u16.to_le_bytes()); - data[64..66].copy_from_slice(&3u16.to_le_bytes()); - data[66..70].copy_from_slice(&1u32.to_le_bytes()); - data[70..74].copy_from_slice(&1u32.to_le_bytes()); - data[74..78].copy_from_slice(&0u32.to_le_bytes()); - - // GPS child IFD @90: count 1, entry tag 0 value 1, next 0 - data[90..92].copy_from_slice(&1u16.to_le_bytes()); - data[92..94].copy_from_slice(&0u16.to_le_bytes()); - data[94..96].copy_from_slice(&3u16.to_le_bytes()); - data[96..100].copy_from_slice(&1u32.to_le_bytes()); - data[100..104].copy_from_slice(&1u32.to_le_bytes()); - data[104..108].copy_from_slice(&0u32.to_le_bytes()); - - let tiff = Tiff::parse(&data).unwrap(); - assert_eq!(tiff.ifds.len(), 2, "chain IFDs parse fully"); - assert_eq!(tiff.ifds[0].u64(0x0100), Some(8)); - let exif = tiff.ifds[0].exif.as_ref().expect("Exif child present"); - assert_eq!(exif.u64(0x9000), Some(1)); - let gps = tiff.ifds[0].gps.as_ref().expect("GPS child present"); - assert_eq!(gps.u64(0x0000), Some(1)); - } -} diff --git a/crates/tiff/src/tags.rs b/crates/tiff/src/tags.rs deleted file mode 100644 index 458aefe535..0000000000 --- a/crates/tiff/src/tags.rs +++ /dev/null @@ -1,226 +0,0 @@ -//! Tag numbers (TIFF 6.0, TIFF/EP, Exif 2.32, GPS, DNG 1.7). Public specification constants. - -// --- TIFF baseline / extensions -pub const NEW_SUBFILE_TYPE: u16 = 254; -pub const SUBFILE_TYPE: u16 = 255; -pub const IMAGE_WIDTH: u16 = 256; -pub const IMAGE_LENGTH: u16 = 257; -pub const BITS_PER_SAMPLE: u16 = 258; -pub const COMPRESSION: u16 = 259; -pub const PHOTOMETRIC: u16 = 262; -pub const FILL_ORDER: u16 = 266; -pub const DOCUMENT_NAME: u16 = 269; -pub const IMAGE_DESCRIPTION: u16 = 270; -pub const MAKE: u16 = 271; -pub const MODEL: u16 = 272; -pub const STRIP_OFFSETS: u16 = 273; -pub const ORIENTATION: u16 = 274; -pub const SAMPLES_PER_PIXEL: u16 = 277; -pub const ROWS_PER_STRIP: u16 = 278; -pub const STRIP_BYTE_COUNTS: u16 = 279; -pub const X_RESOLUTION: u16 = 282; -pub const Y_RESOLUTION: u16 = 283; -pub const PLANAR_CONFIGURATION: u16 = 284; -pub const RESOLUTION_UNIT: u16 = 296; -pub const SOFTWARE: u16 = 305; -pub const DATE_TIME: u16 = 306; -pub const ARTIST: u16 = 315; -pub const PREDICTOR: u16 = 317; -pub const TILE_WIDTH: u16 = 322; -pub const TILE_LENGTH: u16 = 323; -pub const TILE_OFFSETS: u16 = 324; -pub const TILE_BYTE_COUNTS: u16 = 325; -pub const SUB_IFDS: u16 = 330; -pub const EXTRA_SAMPLES: u16 = 338; -pub const SAMPLE_FORMAT: u16 = 339; -pub const JPEG_INTERCHANGE_FORMAT: u16 = 513; -pub const JPEG_INTERCHANGE_FORMAT_LENGTH: u16 = 514; -pub const YCBCR_SUBSAMPLING: u16 = 530; -pub const XMP: u16 = 700; -pub const RATING: u16 = 18246; -pub const RATING_PERCENT: u16 = 18249; -pub const CFA_REPEAT_PATTERN_DIM: u16 = 33421; -pub const CFA_PATTERN_EP: u16 = 33422; -pub const COPYRIGHT: u16 = 33432; -pub const EXPOSURE_TIME_EP: u16 = 33434; -pub const IPTC_NAA: u16 = 33723; -pub const EXIF_IFD: u16 = 34665; -pub const ICC_PROFILE: u16 = 34675; -pub const GPS_IFD: u16 = 34853; -pub const INTEROP_IFD: u16 = 40965; - -// --- Exif private IFD -pub const EXPOSURE_TIME: u16 = 33434; -pub const F_NUMBER: u16 = 33437; -pub const EXPOSURE_PROGRAM: u16 = 34850; -pub const ISO_SPEED: u16 = 34855; -pub const SENSITIVITY_TYPE: u16 = 34864; -pub const RECOMMENDED_EXPOSURE_INDEX: u16 = 34866; -pub const ISO_SPEED_RATINGS_EXT: u16 = 34867; -pub const EXIF_VERSION: u16 = 36864; -pub const DATE_TIME_ORIGINAL: u16 = 36867; -pub const DATE_TIME_DIGITIZED: u16 = 36868; -pub const OFFSET_TIME: u16 = 36880; -pub const OFFSET_TIME_ORIGINAL: u16 = 36881; -pub const OFFSET_TIME_DIGITIZED: u16 = 36882; -pub const SHUTTER_SPEED_VALUE: u16 = 37377; -pub const APERTURE_VALUE: u16 = 37378; -pub const EXPOSURE_BIAS: u16 = 37380; -pub const MAX_APERTURE: u16 = 37381; -pub const METERING_MODE: u16 = 37383; -pub const LIGHT_SOURCE: u16 = 37384; -pub const FLASH: u16 = 37385; -pub const FOCAL_LENGTH: u16 = 37386; -pub const MAKER_NOTE: u16 = 37500; -pub const USER_COMMENT: u16 = 37510; -pub const SUBSEC_TIME: u16 = 37520; -pub const SUBSEC_TIME_ORIGINAL: u16 = 37521; -pub const SUBSEC_TIME_DIGITIZED: u16 = 37522; -pub const PIXEL_X_DIMENSION: u16 = 40962; -pub const PIXEL_Y_DIMENSION: u16 = 40963; -pub const FOCAL_PLANE_X_RESOLUTION: u16 = 41486; -pub const EXPOSURE_MODE: u16 = 41986; -pub const WHITE_BALANCE: u16 = 41987; -pub const FOCAL_LENGTH_35MM: u16 = 41989; -pub const SCENE_CAPTURE_TYPE: u16 = 41990; -pub const BODY_SERIAL_NUMBER: u16 = 42033; -pub const LENS_SPECIFICATION: u16 = 42034; -pub const LENS_MAKE: u16 = 42035; -pub const LENS_MODEL: u16 = 42036; -pub const LENS_SERIAL_NUMBER: u16 = 42037; - -// --- GPS IFD -pub const GPS_VERSION_ID: u16 = 0; -pub const GPS_LATITUDE_REF: u16 = 1; -pub const GPS_LATITUDE: u16 = 2; -pub const GPS_LONGITUDE_REF: u16 = 3; -pub const GPS_LONGITUDE: u16 = 4; -pub const GPS_ALTITUDE_REF: u16 = 5; -pub const GPS_ALTITUDE: u16 = 6; -pub const GPS_TIME_STAMP: u16 = 7; -pub const GPS_IMG_DIRECTION_REF: u16 = 16; -pub const GPS_IMG_DIRECTION: u16 = 17; -pub const GPS_DATE_STAMP: u16 = 29; - -// --- DNG -pub const DNG_VERSION: u16 = 50706; -pub const DNG_BACKWARD_VERSION: u16 = 50707; -pub const UNIQUE_CAMERA_MODEL: u16 = 50708; -pub const LOCALIZED_CAMERA_MODEL: u16 = 50709; -pub const CFA_PLANE_COLOR: u16 = 50710; -pub const CFA_LAYOUT: u16 = 50711; -pub const LINEARIZATION_TABLE: u16 = 50712; -pub const BLACK_LEVEL_REPEAT_DIM: u16 = 50713; -pub const BLACK_LEVEL: u16 = 50714; -pub const BLACK_LEVEL_DELTA_H: u16 = 50715; -pub const BLACK_LEVEL_DELTA_V: u16 = 50716; -pub const WHITE_LEVEL: u16 = 50717; -pub const DEFAULT_SCALE: u16 = 50718; -pub const DEFAULT_CROP_ORIGIN: u16 = 50719; -pub const DEFAULT_CROP_SIZE: u16 = 50720; -pub const COLOR_MATRIX_1: u16 = 50721; -pub const COLOR_MATRIX_2: u16 = 50722; -pub const CAMERA_CALIBRATION_1: u16 = 50723; -pub const CAMERA_CALIBRATION_2: u16 = 50724; -pub const REDUCTION_MATRIX_1: u16 = 50725; -pub const REDUCTION_MATRIX_2: u16 = 50726; -pub const ANALOG_BALANCE: u16 = 50727; -pub const AS_SHOT_NEUTRAL: u16 = 50728; -pub const AS_SHOT_WHITE_XY: u16 = 50729; -pub const BASELINE_EXPOSURE: u16 = 50730; -pub const BASELINE_NOISE: u16 = 50731; -pub const BASELINE_SHARPNESS: u16 = 50732; -pub const BAYER_GREEN_SPLIT: u16 = 50733; -pub const LINEAR_RESPONSE_LIMIT: u16 = 50734; -pub const CAMERA_SERIAL_NUMBER: u16 = 50735; -pub const LENS_INFO: u16 = 50736; -pub const CHROMA_BLUR_RADIUS: u16 = 50737; -pub const ANTI_ALIAS_STRENGTH: u16 = 50738; -pub const SHADOW_SCALE: u16 = 50739; -pub const DNG_PRIVATE_DATA: u16 = 50740; -pub const MAKER_NOTE_SAFETY: u16 = 50741; -pub const CALIBRATION_ILLUMINANT_1: u16 = 50778; -pub const CALIBRATION_ILLUMINANT_2: u16 = 50779; -pub const BEST_QUALITY_SCALE: u16 = 50780; -pub const RAW_DATA_UNIQUE_ID: u16 = 50781; -pub const ORIGINAL_RAW_FILE_NAME: u16 = 50827; -pub const ACTIVE_AREA: u16 = 50829; -pub const MASKED_AREAS: u16 = 50830; -pub const AS_SHOT_ICC_PROFILE: u16 = 50831; -pub const COLORIMETRIC_REFERENCE: u16 = 50879; -pub const CAMERA_CALIBRATION_SIGNATURE: u16 = 50931; -pub const PROFILE_CALIBRATION_SIGNATURE: u16 = 50932; -pub const AS_SHOT_PROFILE_NAME: u16 = 50934; -pub const PROFILE_NAME: u16 = 50936; -pub const PROFILE_HUE_SAT_MAP_DIMS: u16 = 50937; -pub const PROFILE_HUE_SAT_MAP_DATA_1: u16 = 50938; -pub const PROFILE_HUE_SAT_MAP_DATA_2: u16 = 50939; -pub const PROFILE_TONE_CURVE: u16 = 50940; -pub const PROFILE_EMBED_POLICY: u16 = 50941; -pub const PROFILE_LOOK_TABLE_DIMS: u16 = 50981; -pub const PROFILE_LOOK_TABLE_DATA: u16 = 50982; -pub const PROFILE_HUE_SAT_MAP_ENCODING: u16 = 51107; -pub const PROFILE_LOOK_TABLE_ENCODING: u16 = 51108; -pub const BASELINE_EXPOSURE_OFFSET: u16 = 51109; -pub const DEFAULT_BLACK_RENDER: u16 = 51110; -pub const FORWARD_MATRIX_1: u16 = 50964; -pub const FORWARD_MATRIX_2: u16 = 50965; -pub const PREVIEW_COLOR_SPACE: u16 = 50970; -pub const CURRENT_PREVIEW_DATE_TIME: u16 = 50971; -pub const OPCODE_LIST_1: u16 = 51008; -pub const OPCODE_LIST_2: u16 = 51009; -pub const OPCODE_LIST_3: u16 = 51022; -pub const NOISE_PROFILE: u16 = 51041; -pub const DEFAULT_USER_CROP: u16 = 51125; -pub const PROFILE_GAIN_TABLE_MAP: u16 = 52525; -/// DNG 1.7 row interleave: the stored raster holds this many interleaved row groups (each group is -/// every `n`-th row of the image), so it must be un-interleaved before the data is a mosaic. -pub const ROW_INTERLEAVE_FACTOR: u16 = 50975; -/// DNG 1.7 column interleave, the column-wise counterpart of [`ROW_INTERLEAVE_FACTOR`]. -pub const COLUMN_INTERLEAVE_FACTOR: u16 = 52547; -pub const CALIBRATION_ILLUMINANT_3: u16 = 52529; -pub const CAMERA_CALIBRATION_3: u16 = 52530; -pub const COLOR_MATRIX_3: u16 = 52531; -pub const FORWARD_MATRIX_3: u16 = 52532; -pub const ILLUMINANT_DATA_1: u16 = 52533; -pub const ILLUMINANT_DATA_2: u16 = 52534; -pub const ILLUMINANT_DATA_3: u16 = 52535; -// DNG 1.6 semantic masks (spec chapter 4, "Semantic Masks") -pub const SEMANTIC_NAME: u16 = 52526; -pub const SEMANTIC_INSTANCE_ID: u16 = 52528; -pub const MASK_SUB_AREA: u16 = 52536; -/// NewSubFileType of a semantic mask IFD. -pub const SUBFILE_SEMANTIC_MASK: u32 = 0x10004; -pub const PROFILE_GAIN_TABLE_MAP_2: u16 = 52544; - -// --- Compression codes (TIFF 6.0, DNG, and widely used registrations) -pub mod compression { - pub const NONE: u16 = 1; - pub const LZW: u16 = 5; - pub const OLD_JPEG: u16 = 6; - pub const JPEG: u16 = 7; - pub const ADOBE_DEFLATE: u16 = 8; - pub const DEFLATE: u16 = 32946; - pub const PACKBITS: u16 = 32773; - /// DNG lossy JPEG (baseline DCT, 8-bit). - pub const LOSSY_JPEG: u16 = 34892; - pub const JPEG_XL: u16 = 52546; - /// SMPTE ST 2073 (VC-5) as written by GoPro's GPR files (the value measured in them). - pub const VC5: u16 = 9; - /// Nikon NEF Huffman compression. - pub const NIKON: u16 = 34713; - /// Sony ARW compressed (the value used by ARW files). - pub const SONY_ARW: u16 = 32767; -} - -// --- PhotometricInterpretation -pub mod photometric { - pub const WHITE_IS_ZERO: u16 = 0; - pub const BLACK_IS_ZERO: u16 = 1; - pub const RGB: u16 = 2; - pub const YCBCR: u16 = 6; - pub const CFA: u16 = 32803; - pub const LINEAR_RAW: u16 = 34892; - /// DNG 1.6 semantic mask. - pub const MASK: u16 = 52527; -} diff --git a/crates/tiff/src/writer.rs b/crates/tiff/src/writer.rs deleted file mode 100644 index 5732e7d060..0000000000 --- a/crates/tiff/src/writer.rs +++ /dev/null @@ -1,293 +0,0 @@ -//! TIFF writer: IFD trees with strips / tiles, `SubIFDs` and pointer IFDs (Exif, GPS, Interop, …). -//! -//! Layout: header, then for each IFD of the main chain its image chunks, child IFDs, out-of-line values -//! and finally the IFD itself (all word-aligned). Children are written before their parent so every -//! pointer is known when the parent's entries are emitted; only the chain's next-IFD pointers are patched. - -use crate::{ByteOrder, Result, TiffError, Value, tags}; -use std::collections::BTreeMap; - -/// Pixel data attached to an IFD. The writer fills in the offset / byte-count tags. -#[derive(Clone, Debug, PartialEq)] -pub enum ImageData { - /// Strips (each already compressed as the IFD's `Compression` says). Sets `RowsPerStrip`. - Strips { rows_per_strip: u32, strips: Vec> }, - /// Tiles in row-major tile order. Sets `TileWidth` / `TileLength`. - Tiles { tile_width: u32, tile_height: u32, tiles: Vec> }, -} - -/// An IFD to be written. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct IfdBuilder { - pub entries: BTreeMap, - /// Written and referenced through the `SubIFDs` (330) tag. - pub sub_ifds: Vec, - /// Pointer IFDs keyed by the pointer tag (e.g. [`tags::EXIF_IFD`], [`tags::GPS_IFD`], [`tags::INTEROP_IFD`]). - pub children: BTreeMap, - pub image: Option, -} - -impl IfdBuilder { - pub fn new() -> Self { - Self::default() - } - pub fn set(&mut self, tag: u16, value: Value) -> &mut Self { - self.entries.insert(tag, value); - self - } - /// Builder-style [`IfdBuilder::set`]. - pub fn with(mut self, tag: u16, value: Value) -> Self { - self.entries.insert(tag, value); - self - } - pub fn set_child(&mut self, tag: u16, child: IfdBuilder) -> &mut Self { - self.children.insert(tag, child); - self - } - pub fn add_sub_ifd(&mut self, sub: IfdBuilder) -> &mut Self { - self.sub_ifds.push(sub); - self - } - pub fn set_image(&mut self, image: ImageData) -> &mut Self { - self.image = Some(image); - self - } -} - -/// Serialises IFD chains. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct TiffWriter { - pub order: ByteOrder, - pub bigtiff: bool, -} - -impl TiffWriter { - pub fn new(order: ByteOrder, bigtiff: bool) -> Self { - Self { order, bigtiff } - } - - /// Write `chain` (IFD0, IFD1, …) as a complete TIFF stream. - pub fn write(&self, chain: &[IfdBuilder]) -> Result> { - if chain.is_empty() { - return Err(TiffError::Invalid("no IFDs to write".into())); - } - let o = self.order; - let mut buf = Vec::new(); - buf.extend_from_slice(match o { - ByteOrder::Little => b"II", - ByteOrder::Big => b"MM", - }); - let mut patch = if self.bigtiff { - o.put_u16(&mut buf, 43); - o.put_u16(&mut buf, 8); - o.put_u16(&mut buf, 0); - let p = buf.len(); - o.put_u64(&mut buf, 0); - p - } else { - o.put_u16(&mut buf, 42); - let p = buf.len(); - o.put_u32(&mut buf, 0); - p - }; - for ifd in chain { - let (off, next_pos) = self.write_ifd(&mut buf, ifd, 0)?; - self.patch_offset(&mut buf, patch, off)?; - patch = next_pos; - } - Ok(buf) - } - - fn patch_offset(&self, buf: &mut [u8], pos: usize, v: u64) -> Result<()> { - let mut tmp = Vec::with_capacity(8); - if self.bigtiff { - self.order.put_u64(&mut tmp, v); - } else { - self.order.put_u32(&mut tmp, u32::try_from(v).map_err(|_| TiffError::Limit("classic TIFF larger than 4 GiB"))?); - } - buf[pos..pos + tmp.len()].copy_from_slice(&tmp); - Ok(()) - } - - fn offset_value(&self, v: Vec) -> Result { - if self.bigtiff { - Ok(Value::Long8(v)) - } else { - Ok(Value::Long( - v.into_iter().map(|x| u32::try_from(x).map_err(|_| TiffError::Limit("classic TIFF larger than 4 GiB"))).collect::>()?, - )) - } - } - - /// Writes the IFD (and everything it references); returns (IFD offset, position of its next-IFD pointer). - fn write_ifd(&self, buf: &mut Vec, ifd: &IfdBuilder, depth: usize) -> Result<(u64, usize)> { - if depth > 16 { - return Err(TiffError::Limit("IFD nesting depth")); - } - let o = self.order; - let mut entries = ifd.entries.clone(); - if let Some(img) = &ifd.image { - let chunks = match img { - ImageData::Strips { rows_per_strip, strips } => { - entries.insert(tags::ROWS_PER_STRIP, Value::Long(vec![*rows_per_strip])); - strips - } - ImageData::Tiles { tile_width, tile_height, tiles } => { - entries.insert(tags::TILE_WIDTH, Value::Long(vec![*tile_width])); - entries.insert(tags::TILE_LENGTH, Value::Long(vec![*tile_height])); - tiles - } - }; - let mut offs = Vec::with_capacity(chunks.len()); - let mut counts = Vec::with_capacity(chunks.len()); - for c in chunks { - align(buf); - offs.push(buf.len() as u64); - counts.push(c.len() as u64); - buf.extend_from_slice(c); - } - let (ot, ct) = match img { - ImageData::Strips { .. } => (tags::STRIP_OFFSETS, tags::STRIP_BYTE_COUNTS), - ImageData::Tiles { .. } => (tags::TILE_OFFSETS, tags::TILE_BYTE_COUNTS), - }; - entries.insert(ot, self.offset_value(offs)?); - entries.insert(ct, self.offset_value(counts)?); - } - if !ifd.sub_ifds.is_empty() { - let mut offs = Vec::new(); - for s in &ifd.sub_ifds { - offs.push(self.write_ifd(buf, s, depth + 1)?.0); - } - entries.insert(tags::SUB_IFDS, self.offset_value(offs)?); - } - for (&tag, child) in &ifd.children { - let off = self.write_ifd(buf, child, depth + 1)?.0; - entries.insert(tag, self.offset_value(vec![off])?); - } - let inline = if self.bigtiff { 8 } else { 4 }; - // out-of-line values - let mut encoded: Vec<(u16, &Value, Vec, Option)> = Vec::with_capacity(entries.len()); - for (&tag, v) in &entries { - let bytes = encode(o, v); - let pos = if bytes.len() > inline { - align(buf); - let p = buf.len() as u64; - buf.extend_from_slice(&bytes); - Some(p) - } else { - None - }; - encoded.push((tag, v, bytes, pos)); - } - align(buf); - let ifd_off = buf.len() as u64; - if !self.bigtiff && ifd_off > u32::MAX as u64 { - return Err(TiffError::Limit("classic TIFF larger than 4 GiB")); - } - if self.bigtiff { - o.put_u64(buf, encoded.len() as u64); - } else { - o.put_u16(buf, u16::try_from(encoded.len()).map_err(|_| TiffError::Limit("more than 65535 entries"))?); - } - for (tag, v, bytes, pos) in &encoded { - o.put_u16(buf, *tag); - o.put_u16(buf, v.field_type() as u16); - if self.bigtiff { - o.put_u64(buf, v.count() as u64); - } else { - o.put_u32(buf, u32::try_from(v.count()).map_err(|_| TiffError::Limit("value count"))?); - } - match pos { - Some(p) => { - if self.bigtiff { - o.put_u64(buf, *p); - } else { - o.put_u32(buf, u32::try_from(*p).map_err(|_| TiffError::Limit("classic TIFF larger than 4 GiB"))?); - } - } - None => { - buf.extend_from_slice(bytes); - buf.extend(std::iter::repeat_n(0u8, inline - bytes.len())); - } - } - } - let next_pos = buf.len(); - if self.bigtiff { - o.put_u64(buf, 0); - } else { - o.put_u32(buf, 0); - } - Ok((ifd_off, next_pos)) - } -} - -fn align(buf: &mut Vec) { - if buf.len() % 2 == 1 { - buf.push(0); - } -} - -/// Serialise a value's bytes in `o` order. -pub fn encode(o: ByteOrder, v: &Value) -> Vec { - let mut b = Vec::new(); - match v { - Value::Byte(x) | Value::Undefined(x) => b.extend_from_slice(x), - Value::Ascii(s) => { - b.extend_from_slice(s.as_bytes()); - b.push(0); - } - Value::SByte(x) => b.extend(x.iter().map(|&c| c as u8)), - Value::Short(x) => x.iter().for_each(|&c| o.put_u16(&mut b, c)), - Value::SShort(x) => x.iter().for_each(|&c| o.put_u16(&mut b, c as u16)), - Value::Long(x) | Value::Ifd(x) => x.iter().for_each(|&c| o.put_u32(&mut b, c)), - Value::SLong(x) => x.iter().for_each(|&c| o.put_u32(&mut b, c as u32)), - Value::Float(x) => x.iter().for_each(|&c| o.put_u32(&mut b, c.to_bits())), - Value::Rational(x) => x.iter().for_each(|&(n, d)| { - o.put_u32(&mut b, n); - o.put_u32(&mut b, d); - }), - Value::SRational(x) => x.iter().for_each(|&(n, d)| { - o.put_u32(&mut b, n as u32); - o.put_u32(&mut b, d as u32); - }), - Value::Double(x) => x.iter().for_each(|&c| o.put_u64(&mut b, c.to_bits())), - Value::Long8(x) | Value::Ifd8(x) => x.iter().for_each(|&c| o.put_u64(&mut b, c)), - Value::SLong8(x) => x.iter().for_each(|&c| o.put_u64(&mut b, c as u64)), - } - b -} - -/// Convenience: approximate `v` by an unsigned rational with denominator up to 1e6 (for writing Exif rationals). -pub fn rational(v: f64) -> (u32, u32) { - if !v.is_finite() || v <= 0.0 { - return (0, 1); - } - for d in [1u32, 10, 100, 1000, 10_000, 100_000, 1_000_000] { - let n = v * d as f64; - if n > u32::MAX as f64 { - return ((v * (d / 10).max(1) as f64).round().min(u32::MAX as f64) as u32, (d / 10).max(1)); - } - if (n - n.round()).abs() < 1e-9 * d as f64 || d == 1_000_000 { - return (n.round() as u32, d); - } - } - (0, 1) -} - -/// Signed variant of [`rational`]. -pub fn srational(v: f64) -> (i32, i32) { - if !v.is_finite() { - return (0, 1); - } - for d in [1i32, 10, 100, 1000, 10_000, 100_000, 1_000_000] { - let n = v * d as f64; - if n.abs() > i32::MAX as f64 { - let d = (d / 10).max(1); - return ((v * d as f64).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32, d); - } - if (n - n.round()).abs() < 1e-9 * d as f64 || d == 1_000_000 { - return (n.round() as i32, d); - } - } - (0, 1) -} diff --git a/crates/tiff/tests/it/main.rs b/crates/tiff/tests/it/main.rs deleted file mode 100644 index e415ed5377..0000000000 --- a/crates/tiff/tests/it/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! The integration tests, one module per file, linked into one test binary. - -mod roundtrip; diff --git a/crates/tiff/tests/it/roundtrip.rs b/crates/tiff/tests/it/roundtrip.rs deleted file mode 100644 index 3b9a1bd1cf..0000000000 --- a/crates/tiff/tests/it/roundtrip.rs +++ /dev/null @@ -1,429 +0,0 @@ -use lightcraft_tiff::image::{Layout, chunk_bytes}; -use lightcraft_tiff::writer::{rational, srational}; -use lightcraft_tiff::{ByteOrder, FieldType, IfdBuilder, ImageData, ParseOptions, Tiff, TiffError, TiffWriter, Value, parse_ifd_at, tags}; -use proptest::prelude::*; - -const ORDERS: [ByteOrder; 2] = [ByteOrder::Little, ByteOrder::Big]; - -fn all_values() -> Vec<(u16, Value)> { - vec![ - (1000, Value::Byte(vec![1, 2, 3, 255])), - (1001, Value::Ascii("hello tiff".into())), - (1002, Value::Short(vec![1, 65535, 3])), - (1003, Value::Long(vec![7])), - (1004, Value::Rational(vec![(1, 3), (22, 7)])), - (1005, Value::SByte(vec![-1, 0, 127, -128])), - (1006, Value::Undefined(vec![9; 17])), - (1007, Value::SShort(vec![-32768, 32767])), - (1008, Value::SLong(vec![-5, i32::MAX])), - (1009, Value::SRational(vec![(-1, 3), (5, -2)])), - (1010, Value::Float(vec![1.5, -0.25, f32::MAX])), - (1011, Value::Double(vec![std::f64::consts::PI])), - (1012, Value::Ifd(vec![0])), - (1013, Value::Short(vec![42])), - (1014, Value::Ascii(String::new())), - ] -} - -fn big_values() -> Vec<(u16, Value)> { - vec![(1020, Value::Long8(vec![1 << 40, 3])), (1021, Value::SLong8(vec![-(1 << 50)])), (1022, Value::Ifd8(vec![0]))] -} - -#[test] -fn all_field_types_roundtrip_every_variant() { - for order in ORDERS { - for big in [false, true] { - let mut ifd = IfdBuilder::new(); - for (t, v) in all_values() { - ifd.set(t, v); - } - if big { - for (t, v) in big_values() { - ifd.set(t, v); - } - } - let bytes = TiffWriter::new(order, big).write(&[ifd]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - assert_eq!(t.order, order); - assert_eq!(t.bigtiff, big); - assert_eq!(Tiff::sniff(&bytes), Some((order, big))); - let ifd0 = &t.ifds[0]; - for (tag, v) in all_values().into_iter().chain(if big { big_values() } else { vec![] }) { - assert_eq!(ifd0.value(tag), Some(&v), "tag {tag} order {order:?} big {big}"); - } - } - } -} - -#[test] -fn accessors() { - let mut ifd = IfdBuilder::new(); - ifd.set(1, Value::Rational(vec![(28, 10), (0, 0)])); - ifd.set(2, Value::Short(vec![5, 6])); - ifd.set(3, Value::SLong(vec![-3])); - ifd.set(4, Value::Ascii("Canon ".into())); - ifd.set(5, Value::Byte(b"\0junk".to_vec())); - let bytes = TiffWriter::default().write(&[ifd]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - let i = &t.ifds[0]; - assert_eq!(i.f64(1), Some(2.8)); - assert_eq!(i.f64s(1).unwrap(), vec![2.8, 0.0]); - assert_eq!(i.u32(2), Some(5)); - assert_eq!(i.u64s(2).unwrap(), vec![5, 6]); - assert_eq!(i.u32(3), None); - assert_eq!(i.i64(3), Some(-3)); - assert_eq!(i.string(4).as_deref(), Some("Canon")); - assert_eq!(i.string(5).as_deref(), Some("")); - assert_eq!(i.get(4).unwrap().field_type(), FieldType::Ascii); - assert!(i.u32(999).is_none()); - assert_eq!(t.find(2).map(|e| e.tag), Some(2)); -} - -#[test] -fn chain_subifds_and_pointer_ifds() { - for order in ORDERS { - for big in [false, true] { - let mut interop = IfdBuilder::new(); - interop.set(1, Value::Ascii("R98".into())); - let mut exif = IfdBuilder::new(); - exif.set(tags::F_NUMBER, Value::Rational(vec![(56, 10)])); - exif.set_child(tags::INTEROP_IFD, interop); - let mut gps = IfdBuilder::new(); - gps.set(tags::GPS_LATITUDE_REF, Value::Ascii("N".into())); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(tags::MAKE, Value::Ascii("Maker".into())); - ifd0.set_child(tags::EXIF_IFD, exif); - ifd0.set_child(tags::GPS_IFD, gps); - let mut raw = IfdBuilder::new(); - raw.set(tags::IMAGE_WIDTH, Value::Long(vec![4])); - let mut nested = IfdBuilder::new(); - nested.set(tags::IMAGE_WIDTH, Value::Long(vec![2])); - raw.add_sub_ifd(nested); - ifd0.add_sub_ifd(raw); - ifd0.add_sub_ifd(IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Short(vec![3]))); - let ifd1 = IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Short(vec![160])); - let ifd2 = IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Short(vec![80])); - let bytes = TiffWriter::new(order, big).write(&[ifd0, ifd1, ifd2]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - assert_eq!(t.ifds.len(), 3); - assert_eq!(t.ifds[1].u32(tags::IMAGE_WIDTH), Some(160)); - assert_eq!(t.ifds[2].u32(tags::IMAGE_WIDTH), Some(80)); - let i0 = &t.ifds[0]; - assert_eq!(i0.sub_ifds.len(), 2); - assert_eq!(i0.sub_ifds[0].u32(tags::IMAGE_WIDTH), Some(4)); - assert_eq!(i0.sub_ifds[0].sub_ifds[0].u32(tags::IMAGE_WIDTH), Some(2)); - assert_eq!(i0.sub_ifds[1].u32(tags::IMAGE_WIDTH), Some(3)); - let exif = t.exif().unwrap(); - assert_eq!(exif.f64(tags::F_NUMBER), Some(5.6)); - assert_eq!(exif.interop.as_ref().unwrap().string(1).as_deref(), Some("R98")); - assert_eq!(t.gps().unwrap().string(tags::GPS_LATITUDE_REF).as_deref(), Some("N")); - // IFD0, sub0, sub0.sub, sub1, exif, interop, gps, ifd1, ifd2 - assert_eq!(t.all_ifds().len(), 9); - } - } -} - -fn gradient(w: usize, h: usize) -> Vec { - (0..w * h).map(|i| (i * 7 % 251) as u8).collect() -} - -#[test] -fn strips_layout_and_bytes() { - let (w, h) = (10usize, 7usize); - let px = gradient(w, h); - let rps = 3; - let strips: Vec> = px.chunks(w * rps).map(|c| c.to_vec()).collect(); - let mut ifd = IfdBuilder::new(); - ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![w as u32])); - ifd.set(tags::IMAGE_LENGTH, Value::Long(vec![h as u32])); - ifd.set(tags::BITS_PER_SAMPLE, Value::Short(vec![8])); - ifd.set(tags::COMPRESSION, Value::Short(vec![1])); - ifd.set_image(ImageData::Strips { rows_per_strip: rps as u32, strips }); - for order in ORDERS { - for big in [false, true] { - let bytes = TiffWriter::new(order, big).write(std::slice::from_ref(&ifd)).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - let info = t.ifds[0].image().unwrap(); - assert_eq!(info.layout, Layout::Strips { rows_per_strip: 3 }); - assert_eq!(info.grid(), (1, 3)); - let chunks = info.chunks(bytes.len() as u64); - assert_eq!(chunks.len(), 3); - assert_eq!(chunks[2].height, 1); - let mut out = Vec::new(); - for c in &chunks { - out.extend_from_slice(chunk_bytes(&bytes, c).unwrap()); - } - assert_eq!(out, px); - } - } -} - -#[test] -fn tiles_layout_and_bytes() { - let (w, h, tw, th) = (20usize, 13usize, 16usize, 8usize); - let px = gradient(w, h); - let (ta, td) = (w.div_ceil(tw), h.div_ceil(th)); - let mut tiles = Vec::new(); - for ty in 0..td { - for tx in 0..ta { - let mut t = vec![0u8; tw * th]; - for y in 0..th { - for x in 0..tw { - let (sx, sy) = (tx * tw + x, ty * th + y); - if sx < w && sy < h { - t[y * tw + x] = px[sy * w + sx]; - } - } - } - tiles.push(t); - } - } - let mut ifd = IfdBuilder::new(); - ifd.set(tags::IMAGE_WIDTH, Value::Short(vec![w as u16])); - ifd.set(tags::IMAGE_LENGTH, Value::Short(vec![h as u16])); - ifd.set_image(ImageData::Tiles { tile_width: tw as u32, tile_height: th as u32, tiles }); - let bytes = TiffWriter::new(ByteOrder::Big, false).write(&[ifd]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - let info = t.ifds[0].image().unwrap(); - assert_eq!(info.grid(), (2, 2)); - let chunks = info.chunks(bytes.len() as u64); - assert_eq!(chunks.len(), 4); - let mut out = vec![0u8; w * h]; - for c in &chunks { - let b = chunk_bytes(&bytes, c).unwrap(); - for y in 0..c.height as usize { - for x in 0..c.width as usize { - let (sx, sy) = (c.x as usize + x, c.y as usize + y); - if sx < w && sy < h { - out[sy * w + sx] = b[y * tw + x]; - } - } - } - } - assert_eq!(out, px); -} - -#[test] -fn missing_byte_counts_are_inferred() { - let mut ifd = IfdBuilder::new(); - ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![4])); - ifd.set(tags::IMAGE_LENGTH, Value::Long(vec![2])); - ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![vec![1; 4], vec![2; 4]] }); - let bytes = TiffWriter::default().write(&[ifd]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - let mut info = t.ifds[0].image().unwrap(); - info.byte_counts.clear(); - let c = info.chunks(bytes.len() as u64); - assert_eq!(c[0].len, 4); - assert_eq!(&chunk_bytes(&bytes, &c[0]).unwrap()[..4], &[1; 4]); - assert!(c[1].len >= 4); -} - -#[test] -fn bad_headers() { - assert_eq!(Tiff::parse(b""), Err(TiffError::NotTiff)); - assert_eq!(Tiff::parse(b"XX*\0\0\0\0\0"), Err(TiffError::NotTiff)); - assert_eq!(Tiff::parse(b"II\x2b\0\x04\0\0\0"), Err(TiffError::NotTiff)); - assert!(Tiff::parse(b"II*\0").is_err()); - assert!(Tiff::parse(b"II*\0\x08\0\0\0").is_err()); - assert!(Tiff::parse(b"II*\0\x08\0\0\0\0\0").is_err()); - assert!(Tiff::sniff(b"MM\0*\0\0\0\x08").is_some()); -} - -#[test] -fn ifd_loops_are_detected() { - // IFD0 at 8 whose next pointer points back to itself, and whose SubIFDs point to itself too. - let mut b = b"II*\0\x08\0\0\0".to_vec(); - b.extend_from_slice(&1u16.to_le_bytes()); - b.extend_from_slice(&330u16.to_le_bytes()); - b.extend_from_slice(&4u16.to_le_bytes()); - b.extend_from_slice(&1u32.to_le_bytes()); - b.extend_from_slice(&8u32.to_le_bytes()); - b.extend_from_slice(&8u32.to_le_bytes()); - let t = Tiff::parse(&b).unwrap(); - assert_eq!(t.ifds.len(), 1); - assert!(t.ifds[0].sub_ifds.is_empty()); -} - -#[test] -fn out_of_range_entries_are_skipped() { - let mut ifd = IfdBuilder::new(); - ifd.set(1, Value::Long(vec![1, 2, 3])); - ifd.set(2, Value::Short(vec![5])); - let mut bytes = TiffWriter::default().write(&[ifd]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - let e = t.ifds[0].get(1).unwrap().clone(); - // point tag 1's value offset past EOF - let ifd_off = t.ifds[0].offset as usize; - let field = ifd_off + 2 + 8; - assert_eq!(u32::from_le_bytes(bytes[field..field + 4].try_into().unwrap()) as u64, e.offset); - bytes[field..field + 4].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); - let t = Tiff::parse(&bytes).unwrap(); - assert!(t.ifds[0].get(1).is_none()); - assert_eq!(t.ifds[0].u32(2), Some(5)); -} - -#[test] -fn value_budget_limits_allocation() { - // 50 entries all pointing at the same 1000-byte blob. - let mut ifd = IfdBuilder::new(); - ifd.set(1, Value::Undefined(vec![7; 1000])); - let bytes = TiffWriter::default().write(&[ifd]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - let blob = t.ifds[0].get(1).unwrap().offset as u32; - let mut b = b"II*\0".to_vec(); - b.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); - let mut file = bytes.clone(); - file[..8].copy_from_slice(&b); - file.extend_from_slice(&50u16.to_le_bytes()); - for i in 0..50u16 { - file.extend_from_slice(&i.to_le_bytes()); - file.extend_from_slice(&7u16.to_le_bytes()); - file.extend_from_slice(&1000u32.to_le_bytes()); - file.extend_from_slice(&blob.to_le_bytes()); - } - file.extend_from_slice(&0u32.to_le_bytes()); - let opts = ParseOptions { value_budget: Some(10_000), ..Default::default() }; - let t = Tiff::parse_with(&file, &opts).unwrap(); - assert_eq!(t.ifds[0].entries.len(), 10); - let t = Tiff::parse(&file).unwrap(); - assert_eq!(t.ifds[0].entries.len(), 50); -} - -#[test] -fn parse_ifd_with_base() { - // an IFD blob embedded at 100 whose offsets are relative to 100 - let mut blob = Vec::new(); - let o = ByteOrder::Big; - o.put_u16(&mut blob, 1); - o.put_u16(&mut blob, 5); - o.put_u16(&mut blob, 4); - o.put_u32(&mut blob, 3); - o.put_u32(&mut blob, 18); - o.put_u32(&mut blob, 0); - for v in [10u32, 20, 30] { - o.put_u32(&mut blob, v); - } - let mut data = vec![0u8; 100]; - data.extend(blob); - let (ifd, next) = parse_ifd_at(&data, 100, o, 100, false, &ParseOptions::default()).unwrap(); - assert_eq!(next, 0); - assert_eq!(ifd.u64s(5).unwrap(), vec![10, 20, 30]); - assert_eq!(ifd.get(5).unwrap().offset, 118); -} - -#[test] -fn rationals() { - assert_eq!(rational(2.8), (28, 10)); - assert_eq!(rational(0.004), (4, 1000)); - assert_eq!(rational(-1.0), (0, 1)); - assert_eq!(srational(-0.333), (-333, 1000)); - assert_eq!(srational(7.0), (7, 1)); - let (n, d) = rational(1.0 / 3.0); - assert!((n as f64 / d as f64 - 1.0 / 3.0).abs() < 1e-6); -} - -fn sample_file() -> Vec { - let mut exif = IfdBuilder::new(); - exif.set(tags::F_NUMBER, Value::Rational(vec![(4, 1)])); - exif.set(tags::MAKER_NOTE, Value::Undefined(b"Nikon\0\x02\x10\0\0II*\0\x08\0\0\0\x01\0\x01\0\x03\0\x01\0\0\0\x05\0\0\0\0\0\0\0".to_vec())); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(tags::IMAGE_WIDTH, Value::Long(vec![8])); - ifd0.set(tags::IMAGE_LENGTH, Value::Long(vec![4])); - ifd0.set(tags::MAKE, Value::Ascii("NIKON".into())); - ifd0.set_child(tags::EXIF_IFD, exif); - ifd0.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![vec![1; 16], vec![2; 16]] }); - ifd0.add_sub_ifd(IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Long(vec![2]))); - TiffWriter::default().write(&[ifd0, IfdBuilder::new().with(1, Value::Short(vec![1]))]).unwrap() -} - -fn exercise(t: &Tiff, data: &[u8]) { - for ifd in t.all_ifds() { - if let Ok(info) = ifd.image() { - for c in info.chunks(data.len() as u64).iter().take(64) { - let _ = chunk_bytes(data, c); - } - } - for e in &ifd.entries { - let _ = e.value.to_f64_vec(); - let _ = e.value.as_str(); - } - } - if let Some(e) = t.exif().and_then(|x| x.get(tags::MAKER_NOTE)) { - let _ = lightcraft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, t.order, "NIKON"); - } -} - -proptest! { - #![proptest_config(ProptestConfig { cases: 2000, .. ProptestConfig::default() })] - - #[test] - fn random_bytes_never_panic(mut data in proptest::collection::vec(any::(), 0..512), hdr in 0usize..4) { - let heads: [&[u8]; 4] = [b"II*\0", b"MM\0*", b"II+\0\x08\0\0\0", b"MM\0+\0\x08\0\0"]; - let h = heads[hdr]; - if data.len() >= h.len() { - data[..h.len()].copy_from_slice(h); - } - if let Ok(t) = Tiff::parse(&data) { - exercise(&t, &data); - } - } - - #[test] - fn mutated_files_never_panic(flips in proptest::collection::vec((any::(), any::()), 1..16), cut in any::()) { - let mut data = sample_file(); - for (i, v) in flips { - let n = data.len(); - data[i % n] = v; - } - let keep = if cut % 4 == 0 { cut % data.len() } else { data.len() }; - let data = &data[..keep]; - if let Ok(t) = Tiff::parse(data) { - exercise(&t, data); - } - } - - #[test] - fn random_short_arrays_roundtrip(v in proptest::collection::vec(any::(), 1..300), big in any::(), le in any::()) { - let order = if le { ByteOrder::Little } else { ByteOrder::Big }; - let ifd = IfdBuilder::new().with(500, Value::Short(v.clone())).with(501, Value::Double(v.iter().map(|&x| x as f64 / 3.0).collect())); - let bytes = TiffWriter::new(order, big).write(&[ifd]).unwrap(); - let t = Tiff::parse(&bytes).unwrap(); - prop_assert_eq!(t.ifds[0].value(500), Some(&Value::Short(v.clone()))); - prop_assert_eq!(t.ifds[0].f64s(501).unwrap().len(), v.len()); - } -} - -/// A BigTIFF whose IFD says it has an enormous number of entries, with one readable, computed where the next-IFD -/// offset would be from the advertised count: an add overflow, a panic in builds with overflow checks (issue -/// #1516). The readable entry is kept and there is no next IFD; complete chains still link. -#[test] -fn bigtiff_with_an_enormous_entry_count_does_not_panic() { - for order in ORDERS { - for count in [u64::MAX, 1 << 62, 2] { - // little-endian bytes, reversed for big-endian files - let e = |le: &[u8]| -> Vec { if order == ByteOrder::Little { le.to_vec() } else { le.iter().rev().copied().collect() } }; - let mut f = if order == ByteOrder::Little { b"II".to_vec() } else { b"MM".to_vec() }; - for part in [e(&43u16.to_le_bytes()), e(&8u16.to_le_bytes()), e(&0u16.to_le_bytes()), e(&16u64.to_le_bytes()), e(&count.to_le_bytes())] { - f.extend(part); - } - // one entry: ImageWidth, LONG, 1 value (inline in the 8-byte field) - for part in [e(&tags::IMAGE_WIDTH.to_le_bytes()), e(&4u16.to_le_bytes()), e(&1u64.to_le_bytes()), e(&640u32.to_le_bytes())] { - f.extend(part); - } - f.extend([0; 4]); - let (ifd, next) = parse_ifd_at(&f, 16, order, 0, true, &ParseOptions::default()).unwrap(); - assert_eq!(ifd.value(tags::IMAGE_WIDTH), Some(&Value::Long(vec![640])), "{order:?} {count}"); - assert_eq!(next, 0, "{order:?} {count}"); - let t = Tiff::parse(&f).unwrap(); - assert_eq!(t.ifds.len(), 1); - } - // a complete chain of two IFDs still links - let mut a = IfdBuilder::new(); - a.set(1000, Value::Short(vec![1])); - let mut b = IfdBuilder::new(); - b.set(1000, Value::Short(vec![2])); - let t = Tiff::parse(&TiffWriter::new(order, true).write(&[a, b]).unwrap()).unwrap(); - assert_eq!(t.ifds.len(), 2, "{order:?}"); - } -} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 70597bffbd..db515980bc 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -37,7 +37,6 @@ pub const TABLE: &[(&str, Class)] = &[ ("geom", Class::Layer(0)), ("color", Class::Layer(0)), ("raster", Class::Layer(0)), - ("tiff", Class::Layer(0)), ("sysmem", Class::Layer(0)), ("wincolor", Class::Layer(0)), ("fetch", Class::Layer(0)), @@ -78,7 +77,6 @@ pub const TABLE: &[(&str, Class)] = &[ /// L1: `raw` and `codecs` read metadata through `meta`; `develop` uses `meta` for XMP. pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["geom", "color", "raster"], - &["tiff", "raster"], &["denoise-core", "denoise"], &["meta", "raw"], &["meta", "codecs"], From ebfd2d063b62b39a7ab149c81e98768f0d07f241 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 23:34:40 +0000 Subject: [PATCH 04/23] Use craft-heif from craft-libs; remove crates/heif lightcraft-heif moved to craft-libs unchanged as craft-heif (storytold/craft-libs#784), so PhotoCraft can share it. The layer table, the heif CI step and the change triggers drop the local crate; a workspace file change (which a craft-heif rev bump is) still runs the heif step. --- Cargo.lock | 23 +- Cargo.toml | 3 +- apps/lightcraft-cli/Cargo.toml | 2 +- apps/lightcraft-web/Cargo.toml | 2 +- apps/lightcraft/Cargo.toml | 2 +- crates/codecs/Cargo.toml | 8 +- crates/codecs/README.md | 2 +- crates/codecs/src/heif.rs | 18 +- crates/codecs/tests/it/heif.rs | 4 +- crates/engine/Cargo.toml | 2 +- crates/engine/src/tests/import.rs | 4 +- crates/heif/Cargo.toml | 26 -- crates/heif/README.md | 47 --- crates/heif/src/census.rs | 122 ------- crates/heif/src/lib.rs | 528 ---------------------------- crates/heif/src/orient.rs | 178 ---------- crates/heif/src/testdata.rs | 542 ----------------------------- crates/heif/src/tests_synthetic.rs | 200 ----------- crates/heif/src/vui.rs | 459 ------------------------ crates/heif/src/ycc.rs | 352 ------------------- crates/meta/Cargo.toml | 2 +- crates/meta/src/heif.rs | 8 +- xtask/src/ci.rs | 5 +- xtask/src/ci_quick.rs | 4 +- xtask/src/layers.rs | 1 - 25 files changed, 44 insertions(+), 2500 deletions(-) delete mode 100644 crates/heif/Cargo.toml delete mode 100644 crates/heif/README.md delete mode 100644 crates/heif/src/census.rs delete mode 100644 crates/heif/src/lib.rs delete mode 100644 crates/heif/src/orient.rs delete mode 100644 crates/heif/src/testdata.rs delete mode 100644 crates/heif/src/tests_synthetic.rs delete mode 100644 crates/heif/src/vui.rs delete mode 100644 crates/heif/src/ycc.rs diff --git a/Cargo.lock b/Cargo.lock index 1d824dde9d..7c4b6ad874 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1199,6 +1199,15 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +[[package]] +name = "craft-heif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7e66c62b7a87db26993795a9da7ab35d098805b2#7e66c62b7a87db26993795a9da7ab35d098805b2" +dependencies = [ + "heic-rs", + "rayon", +] + [[package]] name = "craft-i18n" version = "0.1.0" @@ -3658,6 +3667,7 @@ version = "0.18.0" dependencies = [ "avif-serialize", "bytemuck", + "craft-heif", "dhat", "image", "image-webp", @@ -3667,7 +3677,6 @@ dependencies = [ "jxl-oxide", "lightcraft-color", "lightcraft-geom", - "lightcraft-heif", "lightcraft-raster", "lightcraft-testkit", "moxcms 0.9.1", @@ -3744,6 +3753,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "craft-heif", "crc32fast", "fs4", "harfrust 0.13.3", @@ -3760,7 +3770,6 @@ dependencies = [ "lightcraft-geocode", "lightcraft-geom", "lightcraft-gpu", - "lightcraft-heif", "lightcraft-lensdb", "lightcraft-merge", "lightcraft-meta", @@ -3853,14 +3862,6 @@ dependencies = [ "wgpu", ] -[[package]] -name = "lightcraft-heif" -version = "0.18.0" -dependencies = [ - "heic-rs", - "rayon", -] - [[package]] name = "lightcraft-inpaint" version = "0.18.0" @@ -3909,8 +3910,8 @@ name = "lightcraft-meta" version = "0.18.0" dependencies = [ "chrono", + "craft-heif", "lightcraft-geom", - "lightcraft-heif", "lightcraft-tiff", "proptest", "quick-xml 0.41.0", diff --git a/Cargo.toml b/Cargo.toml index 2215751be9..d3f9bcdcb2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,8 @@ lightcraft-engine = { path = "crates/engine" } lightcraft-ui-egui = { path = "crates/ui-egui" } lightcraft-mcp = { path = "crates/mcp" } lightcraft-fetch = { path = "crates/fetch" } -lightcraft-heif = { path = "crates/heif" } +# HEIC/HEIF: the shared decoder (moved from crates/heif; craft-libs#784). +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "7e66c62b7a87db26993795a9da7ab35d098805b2" } lightcraft-segment = { path = "crates/segment" } lightcraft-geocode = { path = "crates/geocode" } lightcraft-slideshow = { path = "crates/slideshow" } diff --git a/apps/lightcraft-cli/Cargo.toml b/apps/lightcraft-cli/Cargo.toml index e55d458b32..380bace5f2 100644 --- a/apps/lightcraft-cli/Cargo.toml +++ b/apps/lightcraft-cli/Cargo.toml @@ -37,6 +37,6 @@ rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"] # (open it in DHAT's viewer: allocation sites by bytes at the peak). Slows allocation-heavy work. dhat-heap = ["dep:dhat"] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. heif = ["lightcraft-codecs/heif"] diff --git a/apps/lightcraft-web/Cargo.toml b/apps/lightcraft-web/Cargo.toml index 62fb546991..8946efb048 100644 --- a/apps/lightcraft-web/Cargo.toml +++ b/apps/lightcraft-web/Cargo.toml @@ -77,7 +77,7 @@ web-sys = { workspace = true, features = [ ] } [features] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. On wasm32 panics abort, so # heic-rs's `catch_unwind` guard does not apply there. heif = ["lightcraft-codecs/heif"] diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index cf8aaf2e06..18024a32f6 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -13,7 +13,7 @@ workspace = true default = ["denoise"] denoise = ["lightcraft-engine/denoise"] rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"] -# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose +# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose # it (HEVC patents); build with `--features heif` to include it. heif = ["lightcraft-codecs/heif"] diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 589d285fae..2a766aeee7 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -12,7 +12,7 @@ workspace = true lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } -lightcraft-heif = { workspace = true, optional = true } +craft-heif = { workspace = true, optional = true } serde = { workspace = true } bytemuck = { workspace = true } thiserror = { workspace = true } @@ -40,10 +40,10 @@ default = ["parallel", "jxl", "avif"] parallel = ["dep:rayon", "lightcraft-raster/parallel", "jpeg-decoder/rayon"] ## JPEG XL decode (jxl-oxide) and, on native targets, encode (jixel); both pure Rust. jxl = ["dep:jxl-oxide", "dep:jixel"] -# HEIC/HEIF decode via the optional lightcraft-heif crate (heic-rs, pure Rust). Off by default so +# HEIC/HEIF decode via the optional craft-heif crate (heic-rs, pure Rust). Off by default so # distributors choose it at build time (HEVC patents are a distributor's call, same policy as # PhotoCraft); `cargo xtask ci` clippies and tests it (`--features heif`), releases don't ship it yet. -heif = ["dep:lightcraft-heif"] +heif = ["dep:craft-heif"] ## AVIF encoding via ravif/rav1e (pure Rust, BSD). Native targets only; a no-op on wasm32. avif = ["dep:ravif", "dep:rav1e", "dep:avif-serialize"] @@ -54,7 +54,7 @@ lightcraft-testkit = { workspace = true } jxl-oxide = { workspace = true } proptest = { workspace = true } # Lossless synthetic HEIC files for the `heif` feature's tests. -lightcraft-heif = { workspace = true, features = ["testdata"] } +craft-heif = { workspace = true, features = ["testdata"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] dhat = { workspace = true } diff --git a/crates/codecs/README.md b/crates/codecs/README.md index b993c52efe..39815b4add 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -54,7 +54,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d | PSD / PSB | merged composite: 8/16/32-bit gray, RGB, CMYK, indexed, duotone (as gray); raw/RLE | — | ICC (1039), EXIF (1058), XMP (1060); ZIP-compressed composite, Lab and 1-bit unsupported | | JPEG XL | yes (jxl-oxide, feature `jxl`, default on) | yes (jixel, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes | | AVIF | **no** | yes (ravif/rav1e, native only, feature `avif`) | 8/10-bit sRGB, EXIF; no ICC in the muxer. HDR: `encode_avif_hdr` writes 10-bit BT.2020 PQ (SDR white at 203 cd/m², CICP `nclx` + `clli`) or HLG (`hlg_signal`, SDR white at 0.75) | -| HEIC/HEIF | yes with feature `heif` (lightcraft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported | +| HEIC/HEIF | yes with feature `heif` (craft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported | | Gain map JPEG (HDR) | gain map found and decoded (`gainmap::read_jpeg`): ISO 21496-1 metadata, else Adobe `hdrgm` XMP | yes (`gainmap::encode_jpeg`) | CIPA DC-007 MPF index (gain map typed `0x050000`), ISO 21496-1 APP2 on both images, `hdrgm` + Container XMP for Android/Chrome, Apple `HDRGainMap`/`HDRToneMap` XMP; gain maps are never used as thumbnails | ## Colour diff --git a/crates/codecs/src/heif.rs b/crates/codecs/src/heif.rs index 702a0d27d2..3e899bcdd7 100644 --- a/crates/codecs/src/heif.rs +++ b/crates/codecs/src/heif.rs @@ -1,6 +1,6 @@ //! HEIF / HEIC (the iPhone and Mac photo format), read-only. //! -//! Decoding lives in the optional `lightcraft-heif` crate (heic-rs, a pure-Rust HEVC +//! Decoding lives in the optional `craft-heif` crate (heic-rs, a pure-Rust HEVC //! still-picture decoder, plus a libheif-matching colour conversion), enabled by this crate's //! `heif` feature — off by default because HEVC is patent-encumbered and whether a build carries //! an HEVC decoder is the distributor's call (the same policy as the sibling PhotoCraft). Without @@ -35,10 +35,10 @@ pub(crate) fn header(_bytes: &[u8]) -> Result<(u32, u32, u16)> { } #[cfg(feature = "heif")] -fn err(e: lightcraft_heif::Error) -> Error { +fn err(e: craft_heif::Error) -> Error { match e { - lightcraft_heif::Error::Unsupported(why) => Error::Unsupported(F, why), - lightcraft_heif::Error::Limit(m) | lightcraft_heif::Error::Malformed(m) => Error::Malformed(F, m), + craft_heif::Error::Unsupported(why) => Error::Unsupported(F, why), + craft_heif::Error::Limit(m) | craft_heif::Error::Malformed(m) => Error::Malformed(F, m), } } @@ -46,24 +46,24 @@ fn err(e: lightcraft_heif::Error) -> Error { /// alone: no picture is decoded. #[cfg(feature = "heif")] pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { - let info = lightcraft_heif::probe(bytes).map_err(err)?; + let info = craft_heif::probe(bytes).map_err(err)?; Ok((info.width, info.height, 1)) } #[cfg(feature = "heif")] pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { // The container alone: the declared size is checked before any pixel is decoded. - let info = lightcraft_heif::probe(bytes).map_err(err)?; + let info = craft_heif::probe(bytes).map_err(err)?; if (info.width as u64).saturating_mul(info.height as u64) > opts.max_pixels { return Err(Error::TooLarge(info.width as u64, info.height as u64)); } - let options = lightcraft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true }; + let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true }; // A small decode (a thumbnail or a cataloguing probe) uses the file's own thumbnail image when // it is at least as large as asked: iPhones store one of 320 × 240, and decoding it is a // hundredth of the work of the 12 MP photo. let thumb = match opts.max_size { Some((mw, mh)) if mw > 0 && mh > 0 && mw.max(mh) < info.width.max(info.height) => { - lightcraft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| { + craft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| { // Only a thumbnail of the same picture: same orientation and aspect within 1 %. let aspect = |w: u32, h: u32| w as f64 / h.max(1) as f64; (aspect(t.width, t.height) / aspect(info.width, info.height) - 1.0).abs() < 0.01 @@ -73,7 +73,7 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { }; let mut decoded = match thumb { Some(t) => t, - None => lightcraft_heif::decode(bytes, &options).map_err(err)?, + None => craft_heif::decode(bytes, &options).map_err(err)?, }; let raw = Raw { width: decoded.width as usize, diff --git a/crates/codecs/tests/it/heif.rs b/crates/codecs/tests/it/heif.rs index 3364aec4d3..5cd2e63d0b 100644 --- a/crates/codecs/tests/it/heif.rs +++ b/crates/codecs/tests/it/heif.rs @@ -1,9 +1,9 @@ //! HEIC/HEIF through the codec API (feature `heif`), on lossless synthetic files from -//! `lightcraft_heif::testdata`: an iPhone-like grid with a Display P3 profile, rotation, EXIF, a +//! `craft_heif::testdata`: an iPhone-like grid with a Display P3 profile, rotation, EXIF, a //! thumbnail and an HDR gain map; `nclx`-only colour; 10-bit; and hostile input. +use craft_heif::testdata::{Prop, Spec, build}; use lightcraft_codecs::*; -use lightcraft_heif::testdata::{Prop, Spec, build}; fn grey(x: u32, y: u32) -> [u16; 3] { [((x * 7 + y * 13) % 220 + 20) as u16, 128, 128] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 895ef52126..86f44895f5 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -66,6 +66,6 @@ lightcraft-testkit = { workspace = true } # HDR JPEG XL tests read the file's colour encoding jxl-oxide = { workspace = true } # Lossless synthetic HEIC files (the import test; decoded when the codecs' `heif` feature is on). -lightcraft-heif = { workspace = true, features = ["testdata"] } +craft-heif = { workspace = true, features = ["testdata"] } libc = { workspace = true } lightcraft-tiff = { workspace = true } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 4885b5d30b..3c387ce42c 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -2820,7 +2820,7 @@ fn a_file_gone_since_the_import_review_is_not_imported() { /// a JPEG. In a build without the codecs' `heif` feature it is reported as failed, saying why. #[test] fn heic_imports_as_a_normal_photo_or_says_why_not() { - use lightcraft_heif::testdata::{Prop, Spec, build}; + use craft_heif::testdata::{Prop, Spec, build}; let src = temp_dir("heic"); let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150]; let p3 = lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::DisplayP3); @@ -2857,7 +2857,7 @@ fn heic_imports_as_a_normal_photo_or_says_why_not() { /// writes as UTC: an iPhone photo landed five hours late and after 19:00 on the wrong day. #[test] fn a_heic_is_dated_by_its_exif_and_not_by_the_file() { - use lightcraft_heif::testdata::{Spec, build}; + use craft_heif::testdata::{Spec, build}; use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t}; let src = temp_dir("heic-capture-time"); let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150]; diff --git a/crates/heif/Cargo.toml b/crates/heif/Cargo.toml deleted file mode 100644 index 95641fb2fd..0000000000 --- a/crates/heif/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "lightcraft-heif" -description = "Optional HEIF/HEIC still-image decoder for LightCraft (heic-rs for the container and HEVC, libheif-matching colour conversion, panic-guarded)" -version.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -# Pure Rust, no unsafe. Pinned exactly: a young, single-owner crate that parses untrusted files; -# moving the pin is a reviewed change (re-run the heif tests and the codecs corpus tests). -# Mirrors PhotoCraft's photocraft-heif (same team, same decision): heic-rs was chosen over the -# other permissive candidates (heif-oxide's HEVC decoder, rust_h265, follows FFmpeg's (LGPL) -# code structure; gamut-heic has no HEVC decoder of its own). -heic-rs = { version = "=0.1.4", default-features = false, features = ["std"] } - -# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded. -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"] } -rayon = { workspace = true } - -[features] -# `lightcraft_heif::testdata`: lossless synthetic HEIF files, for the tests of the crates above. -testdata = [] - -[lints] -workspace = true diff --git a/crates/heif/README.md b/crates/heif/README.md deleted file mode 100644 index 75db814b0d..0000000000 --- a/crates/heif/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# lightcraft-heif - -The optional HEIF / HEIC decoder of LightCraft: iPhone and Mac photos. [`heic-rs`](https://github.com/tbraun96/heic-rs) -(pure Rust, no `unsafe`, MIT OR Apache-2.0, written from the H.265 / HEIF specifications) reads the -container and reconstructs the HEVC pictures; this crate turns them into 16-bit RGB itself so the -result matches libheif to within one code value: - -- the colour description is the item's `colr nclx` (or its first tile's), else the HEVC VUI - (iPhones: full range), else the H.265 defaults; an unspecified matrix is BT.601. heic-rs alone - assumes BT.709 limited range, about 8 code values off on every iPhone photo; -- chroma is upsampled by nearest neighbour, or centred bilinear when a `clap` starts on an odd - pixel, as libheif does; -- `imir` axis 0 flips top and bottom, as libheif writes and reads it (heic-rs names it the other way); -- a grid's ICC profile may sit on its tiles. - -Single pictures and grid-tiled photos, 4:2:0 and monochrome, 8- to 10-bit, alpha auxiliary images -(other auxiliary images — HDR gain maps, depth — are ignored), the container's rotation/mirror/crop, -ICC, EXIF and XMP, and the file's thumbnail item. 4:2:2 and 4:4:4 (Canon/Sony "HIF") are refused -with `Error::Unsupported`: heic-rs 0.1.1 loses sync on them. Read-only. - -```rust -let info = lightcraft_heif::probe(&bytes)?; // size, depth, alpha: check limits first -let img = lightcraft_heif::decode(&bytes, &lightcraft_heif::Options::default())?; -// img.width, img.height, img.has_alpha, img.bit_depth, img.data (RGB/RGBA u16), img.colour, img.icc, img.exif, img.xmp -let thumb = lightcraft_heif::decode_thumbnail(&bytes, 256, &Default::default())?; // Option -``` - -Errors are `Error::Unsupported` (image sequences, overlays, 4:2:2/4:4:4, …), `Error::Limit` or -`Error::Malformed`. It never panics: every call into heic-rs runs under `catch_unwind`, and a panic -inside it (PhotoCraft's fuzzing found two in 0.1.1) becomes `Error::Malformed`. - -Feature `testdata` exposes `lightcraft_heif::testdata`: lossless synthetic HEIF files (PCM-coded -32 × 32 HEVC pictures, grids, every property above) for the tests of the crates above. - -## Why it is a separate, optional crate - -- **A young decoder.** heic-rs is new and has a single maintainer. It is pinned exactly - (`=0.1.1`); moving the pin is a reviewed change (re-run the crate tests and - `cargo test -p lightcraft-codecs --features heif`). The other permissive candidates were - rejected: heif-oxide's HEVC decoder (rust_h265) follows FFmpeg's (LGPL) code structure, and - gamut-heic has no HEVC decoder of its own. -- **HEVC patents are a distributor's call.** `lightcraft-codecs` uses this crate only behind its - non-default `heif` feature; the apps forward it and the release packages enable it. Without it, - HEIC files are still recognised and opening one is a clear "HEIC/HEIF support isn't included in - this build" error — the same policy as PhotoCraft. - -The crate depends on no other LightCraft crate; `codecs` → `heif` is the only edge between them. diff --git a/crates/heif/src/census.rs b/crates/heif/src/census.rs deleted file mode 100644 index 6dbe035fca..0000000000 --- a/crates/heif/src/census.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Caps on the container's metadata boxes, counted before heic-rs touches the file. -//! -//! heic-rs 0.1.4 (pinned `=0.1.4`) has no aggregate work budget inside its container parsing: -//! every `ipma` association entry rescans the vector of already-seen item ids (quadratic in -//! the number of entries), and an `iloc` extent using construction method 2 reconstructs its -//! source item afresh for every extent that references it, with no shared cache. Legitimate -//! phone-photo metadata never comes near these caps — real corpora keep both well under a few -//! kilobytes — so anything above them is hostile or corrupt and is refused before the -//! countable CPU work happens. -//! -//! [`depth_boxes`] stops silently at structural blips: heic-rs's own parser reports those -//! better than this walk could, and an `ipma` box past the cap is caught wherever it parses. - -use heic_rs::boxes::BoxIter; - -use crate::Error; - -/// The largest `ipma` box (item ↔ property associations) payload accepted, 64 KiB. An entry -/// costs at least 3 bytes, so this bounds heic-rs's per-entry rescan of earlier item ids to -/// ~21 000 entries ≈ 220 million comparisons: long enough to be annoying, never minutes. -const MAX_IPMA_BYTES: usize = 64 << 10; - -/// The largest `iloc` box (item locations) payload accepted, 64 KiB. An extent costs at least -/// 12 bytes, so this bounds both the parse itself and how many extents a -/// construction-method-2 reconstruction chain can visit. -const MAX_ILOC_BYTES: usize = 64 << 10; - -/// Falls through unless the container declares more `ipma` or `iloc` payload than a -/// legitimate phone photo ever does. -pub fn cap(bytes: &[u8]) -> Result<(), Error> { - let mut c = Census::default(); - depth_boxes(&mut c, BoxIter::new(bytes), 0); - if c.ipma > MAX_IPMA_BYTES { - return Err(Error::Limit(format!("the image carries {} bytes of property associations, over the {MAX_IPMA_BYTES}-byte cap", c.ipma))); - } - if c.iloc > MAX_ILOC_BYTES { - return Err(Error::Limit(format!("the image carries {} bytes of item locations, over the {MAX_ILOC_BYTES}-byte cap", c.iloc))); - } - Ok(()) -} - -/// The metadata-box payload sizes seen so far. -#[derive(Default)] -struct Census { - ipma: usize, - iloc: usize, -} - -/// Walks boxes, adding the payload sizes of those named in [`Census`]. -/// -/// Only `meta` and `iprp` (the two nesting boxes the metadata is built from) are descended -/// into, no deeper than that depth, so a nested-box trick can't hide a box from the count. -fn depth_boxes(c: &mut Census, boxes: BoxIter<'_>, depth: u32) { - if depth > 3 { - return; - } - for b in boxes { - // A structural error stops the walk; `heic_rs::probe` reports it properly afterwards. - let Ok(b) = b else { return }; - if b.is(b"ipma") { - c.ipma = c.ipma.saturating_add(b.payload.len()); - } else if b.is(b"iloc") { - c.iloc = c.iloc.saturating_add(b.payload.len()); - } else if b.is(b"meta") { - // `meta` is a FullBox: version and flags sit between its header and its children. - if b.payload.len() >= 4 { - depth_boxes(c, BoxIter::new(&b.payload[4..]), depth + 1); - } - } else if b.is(b"iprp") { - depth_boxes(c, b.children(), depth + 1); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Assembles ftyp + meta(version/flags + iprp(ipco, ipma)) by hand; only the structure - /// the census walks matters, no item is ever defined. - fn file_with(ipma_payload: &[u8]) -> Vec { - let mut out = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic".to_vec(); - let mut iprp = Vec::new(); - iprp.extend(box_of(b"ipco", b"")); - iprp.extend(box_of(b"ipma", ipma_payload)); - let mut meta = vec![0u8, 0, 0, 0]; // version 0, flags 0 - meta.extend(box_of(b"iprp", &iprp)); - out.extend(box_of(b"meta", &meta)); - out - } - - fn box_of(kind: &[u8; 4], body: &[u8]) -> Vec { - let mut out = Vec::with_capacity(8 + body.len()); - let size = u32::try_from(8 + body.len()).expect("test box fits in u32"); - out.extend_from_slice(&size.to_be_bytes()); - out.extend_from_slice(kind); - out.extend_from_slice(body); - out - } - - #[test] - fn an_oversized_ipma_is_refused() { - // 40 000 entries of 6 bytes: 240 KiB of ipma, far over the cap, and quadratic if - // parsed (each entry rescans the earlier item ids in heic-rs 0.1.4). - let mut ipma = Vec::new(); - for _ in 0..40_000u32 { - ipma.extend_from_slice(&[0u8, 0, 0, 0, 0, 0]); - } - let bytes = file_with(&ipma); - let r = crate::probe(&bytes).map(|_| ()); - assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("associations")), "{r:?}"); - } - - #[test] - fn a_undersized_ipma_is_untouched_by_the_caps() { - // The same shape with a normal ipma (two entries): the caps pass, and whatever error - // follows must not come from them. - let bytes = file_with(&[0, 0, 4, 1, 1, 2, 0, 0]); - let r = crate::probe(&bytes); - assert!(!matches!(r, Err(Error::Limit(ref m)) if m.contains("cap")), "{r:?}"); - } -} diff --git a/crates/heif/src/lib.rs b/crates/heif/src/lib.rs deleted file mode 100644 index 5b20e31d75..0000000000 --- a/crates/heif/src/lib.rs +++ /dev/null @@ -1,528 +0,0 @@ -//! `lightcraft-heif`: the optional HEIF / HEIC (iPhone and Mac photo) decoder. -//! -//! `heic-rs`, a pure-Rust HEIF container and HEVC still-picture decoder, reads the container and -//! reconstructs the coded pictures (bit-exact against libde265 on iPhone photos); this crate turns -//! them into RGB itself ([`ycc`]) so the colours match libheif: it honours the HEVC VUI's range -//! and matrix ([`vui`]) where heic-rs assumes BT.709 limited range, and upsamples chroma like -//! libheif. Single pictures and grid-tiled photos, 8- to 16-bit, monochrome, alpha auxiliary -//! images, ICC, EXIF and XMP. The API is plain data ([`Info`], [`Decoded`], [`Error`]) so the -//! crate knows nothing about the rest of LightCraft; `lightcraft-codecs` adapts it behind its -//! `heif` feature. Shares heic-rs and its regression fixtures with PhotoCraft's `photocraft-heif`. -//! -//! HEIF records orientation in the container (`irot`/`imir`, plus a `clap` crop), not in EXIF. -//! [`Options::apply_transforms`] applies them; with it off, the pixels come back as coded. -//! Auxiliary images other than alpha (HDR gain maps, depth maps) are ignored. -//! -//! Never panics: heic-rs is young, so every call into it runs under `catch_unwind` and a panic -//! inside it becomes [`Error::Malformed`]. - -#![forbid(unsafe_code)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -mod census; -mod orient; -/// Lossless synthetic HEIF files for tests, here and in the crates above (feature `testdata`). -#[cfg(any(test, feature = "testdata"))] -#[doc(hidden)] -pub mod testdata; -mod vui; -mod ycc; - -use std::borrow::Cow; - -use heic_rs::context::Context; -use heic_rs::hevc::Frame; -use heic_rs::props::ItemProps; -use heic_rs::props::colr::Range; - -/// What a HEIF file declares, read from the container alone (no pixel is decoded). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Info { - /// Size after the container transforms (rotation, mirror, crop): what a viewer shows. - pub width: u32, - pub height: u32, - /// Size as coded, before the transforms. - pub coded_width: u32, - pub coded_height: u32, - /// The primary image has an alpha auxiliary image. - pub has_alpha: bool, - /// Bits per sample as coded (8 for most photos, 10 for HDR-capable ones). - pub bit_depth: u8, -} - -/// Decode settings. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Options { - /// Refuse images with more pixels than this (checked before decoding). - pub max_pixels: u64, - /// Apply the container's rotation, mirror and crop (`irot`/`imir`/`clap`). - pub apply_transforms: bool, -} - -impl Default for Options { - fn default() -> Self { - Options { max_pixels: 1 << 28, apply_transforms: true } - } -} - -/// How the file describes its colour: the code points of ITU-T H.273, from the `colr` `nclx` -/// box, else the HEVC VUI, else the standard defaults (2 = unspecified, limited range). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Colour { - pub primaries: u16, - pub transfer: u16, - pub matrix: u16, - pub full_range: bool, -} - -/// A decoded image: interleaved RGB or RGBA, 16 bits per sample whatever the coded depth, -/// row-major, no padding. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Decoded { - pub width: u32, - pub height: u32, - /// Four channels (RGBA) instead of three (RGB). - pub has_alpha: bool, - /// Bits per sample as coded. - pub bit_depth: u8, - pub data: Vec, - pub colour: Colour, - /// The primary image's ICC profile. - pub icc: Option>, - /// EXIF as a TIFF structure (without HEIF's offset header). Its Orientation tag only mirrors - /// what the container says; it is returned verbatim. - pub exif: Option>, - /// The XMP packet. - pub xmp: Option, -} - -/// Why a file could not be decoded. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Error { - /// A valid file using something this decoder does not handle (image sequences, overlays…). - Unsupported(&'static str), - /// The image is larger than [`Options::max_pixels`] or holds an oversized box. - Limit(String), - /// Broken or truncated data (or a decoder bug, reported the same way). - Malformed(String), -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Unsupported(m) => write!(f, "unsupported HEIF: {m}"), - Error::Limit(m) => write!(f, "limit exceeded: {m}"), - Error::Malformed(m) => write!(f, "malformed HEIF: {m}"), - } - } -} - -impl std::error::Error for Error {} - -const SEQUENCE: &str = "this file holds an image sequence; only HEIF still images can be opened"; - -/// heic-rs 0.1.1 reconstructs 4:2:0 and monochrome pictures exactly but fails on the 4:2:2 and -/// 4:4:4 ones some cameras write (Canon and Sony "HIF"); those failures are reported as this. -const CHROMA_422_444: &str = "4:2:2 and 4:4:4 HEIF images (as some Canon and Sony cameras write) can't be decoded yet"; - -pub(crate) fn err(e: heic_rs::Error) -> Error { - match e { - heic_rs::Error::Unsupported(what) => Error::Unsupported(what), - // The primary item is neither an HEVC picture nor a grid of them. - heic_rs::Error::MissingBox("hvcC") => Error::Unsupported("the image is an overlay, an identity derivation or not HEVC-coded"), - heic_rs::Error::PixelLimit { .. } | heic_rs::Error::BoxTooLarge { .. } => Error::Limit(e.to_string()), - e => Error::Malformed(e.to_string()), - } -} - -/// Runs `f`, turning a heic-rs panic into an error. Fuzzing in the sibling app found two -/// out-of-range slices in heic-rs 0.1.1 on malformed files: in its box parser (`boxes.rs:130`) -/// and during reconstruction (`hevc/decode/recon.rs:70`). -fn guarded(f: impl FnOnce() -> Result) -> Result { - std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(Error::Malformed("the HEIF decoder failed on this file".into()))) -} - -/// Reads the container's declared size, depth and alpha without decoding pixels, so callers can -/// check their limits first. Also refuses a file cut short: every coded picture of the primary -/// image must lie within `bytes`. -pub fn probe(bytes: &[u8]) -> Result { - guarded(|| probe_unguarded(bytes)) -} - -fn probe_unguarded(bytes: &[u8]) -> Result { - census::cap(bytes)?; - // No `meta` box: no still image, only a `moov` image sequence (a video track). - let open_error = |e| match e { - heic_rs::Error::MissingBox("meta") => Error::Unsupported(SEQUENCE), - e => err(e), - }; - let ctx = Context::open(bytes).map_err(open_error)?; - let id = ctx.meta.primary; - // heic-rs 0.1.4 caps the size of what it assembles, not the work: an item built from other - // items (`iloc` construction method 2) is rebuilt once per extent, so a chain of such items - // multiplies at every level while each result stays small. Count those visits from the - // `iloc` table before reconstructing anything: the primary item first (`heic_rs::probe` and - // `Context::grid` both rebuild its descriptor), then its alpha plane, then every tile - // reference, repeats included. - let mut visits = 0_usize; - item_visits(&ctx, id, 0, &mut visits)?; - let info = heic_rs::probe(bytes).map_err(open_error)?; - if let Some(alpha) = ctx.alpha_item(id).map_err(err)? { - item_visits(&ctx, alpha, 0, &mut visits)?; - } - let mut coded = match ctx.grid(id).map_err(err)? { - Some((_, tiles)) => tiles, - None => vec![id], - }; - for &item in coded.iter().filter(|&&item| item != id) { - item_visits(&ctx, item, 0, &mut visits)?; - } - // A `dimg` listing may name the same tile more than once, and reconstructable items are - // moreover rebuilt for every extent that references them in heic-rs 0.1.4. For the size - // check each unique item counts once: the total reconstruction (all of it assembled from - // `bytes` by heic-rs) is held below one copy of the file, above which a repeat or chain - // wants more bytes than exist. Order doesn't matter here: this only checks that every - // tile's bytes lie in the file. - coded.sort_unstable(); - coded.dedup(); - let mut reconstructed = 0_usize; - for item in coded { - reconstructed = reconstructed.saturating_add(ctx.item_data(item).map_err(err)?.len()); - if reconstructed > bytes.len() { - return Err(Error::Limit(format!( - "the container holds {reconstructed} bytes of item data, over the {} bytes of the file itself", - bytes.len() - ))); - } - } - Ok(Info { - width: info.width, - height: info.height, - coded_width: info.coded_width, - coded_height: info.coded_height, - has_alpha: info.has_alpha, - bit_depth: info.bit_depth, - }) -} - -/// Most extent visits heic-rs may spend reconstructing the primary image's coded items; real -/// files need one per tile (plus a few for the rare derived item). -const MAX_ITEM_VISITS: usize = 4096; -/// Deepest chain of items built from items we follow (heic-rs refuses beyond eight itself). -const MAX_ITEM_CHAIN: u32 = 8; - -/// Adds to `visits` the extents heic-rs would read to reconstruct `id`, following items built -/// from other items, and fails once that passes [`MAX_ITEM_VISITS`] or the chain is too deep. -fn item_visits(ctx: &Context<'_>, id: u32, depth: u32, visits: &mut usize) -> Result<(), Error> { - use heic_rs::meta::iloc::Construction; - if depth > MAX_ITEM_CHAIN { - return Err(Error::Limit(format!("items built from items nest deeper than {MAX_ITEM_CHAIN} levels"))); - } - let Some(loc) = ctx.meta.location(id) else { return Ok(()) }; - *visits = visits.saturating_add(loc.extents.len().max(1)); - if *visits > MAX_ITEM_VISITS { - return Err(Error::Limit(format!("reconstructing the image takes over {MAX_ITEM_VISITS} item extent reads"))); - } - if loc.construction == Construction::Item { - for e in &loc.extents { - if let Ok(source) = u32::try_from(e.index) - && source != id - { - item_visits(ctx, source, depth + 1, visits)?; - } - } - } - Ok(()) -} - -/// Decodes the primary image, with its metadata. -pub fn decode(bytes: &[u8], options: &Options) -> Result { - guarded(|| decode_unguarded(bytes, options)) -} - -/// Decodes the smallest thumbnail image the file carries whose long edge is at least -/// `min_edge`, if any (iPhones store one of about 320 × 240). Transforms are applied as for the -/// primary image; the metadata (and, when the thumbnail has no profile of its own, the ICC -/// profile) are the primary image's. -pub fn decode_thumbnail(bytes: &[u8], min_edge: u32, options: &Options) -> Result, Error> { - guarded(|| { - let ctx = Context::open(bytes).map_err(err)?; - let primary = ctx.meta.primary; - let mut best: Option<(u32, u32)> = None; - // A thumbnail whose own reconstruction would cost too much is not a candidate; the visits - // of all the candidates share one budget. - let mut candidate_visits = 0_usize; - for r in ctx.meta.refs.iter().filter(|r| r.kind == heic_rs::meta::iref::RefKind::Thmb && r.to.contains(&primary)) { - if item_visits(&ctx, r.from, 0, &mut candidate_visits).is_err() { - continue; - } - let Ok(p) = ctx.props(r.from) else { continue }; - let Ok((w, h)) = ctx.coded_size(r.from, &p) else { continue }; - let edge = w.max(h); - if edge >= min_edge && best.is_none_or(|(_, e)| edge < e) { - best = Some((r.from, edge)); - } - } - let Some((id, _)) = best else { return Ok(None) }; - // The same pre-scan as `probe`: the thumbnail's own descriptor and every tile reference - // are counted before heic-rs rebuilds any of them. - let mut visits = 0_usize; - item_visits(&ctx, id, 0, &mut visits)?; - if let Some((_, tiles)) = ctx.grid(id).map_err(err)? { - for &tile in &tiles { - item_visits(&ctx, tile, 0, &mut visits)?; - } - } - let mut decoded = decode_item(&ctx, id, options, false)?; - if decoded.icc.is_none() { - decoded.icc = item_icc(&ctx, primary); - } - (decoded.exif, decoded.xmp) = metadata(&ctx); - Ok(Some(decoded)) - }) -} - -/// An item's ICC profile; a grid whose own properties carry none takes its first tile's (as on -/// some iPhones). -fn item_icc(ctx: &Context<'_>, id: u32) -> Option> { - let p = ctx.props(id).ok()?; - let icc = p.icc.or_else(|| { - let (_, tiles) = ctx.grid(id).ok()??; - ctx.props(*tiles.first()?).ok()?.icc - }); - icc.map(<[u8]>::to_vec) -} - -fn decode_unguarded(bytes: &[u8], options: &Options) -> Result { - // Refuses sequences with a clear message before anything else is read. - probe_unguarded(bytes)?; - let ctx = Context::open(bytes).map_err(err)?; - let mut decoded = decode_item(&ctx, ctx.meta.primary, options, true)?; - let (exif, xmp) = metadata(&ctx); - decoded.exif = exif; - decoded.xmp = xmp; - Ok(decoded) -} - -/// Decodes one image item (a coded picture or a grid of them) to RGB(A), alpha included when -/// `with_alpha` and the item has an alpha auxiliary image. -fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool) -> Result { - let p = ctx.props(id).map_err(err)?; - // heic-rs 0.1.4 keeps every associated transform and its [`orient::apply`] allocates the - // full picture again for each: a file could chain the repetition and multiply decode CPU - // without changing any checked size. Real files carry at most one `clap`, `irot` and - // `imir`, so refuse anything approaching [`MAX_TRANSFORMS`] (CodeRabbit #44). - if p.transforms.len() > MAX_TRANSFORMS { - return Err(Error::Limit(format!("the image carries {} transform properties, over the {MAX_TRANSFORMS}-property cap", p.transforms.len()))); - } - let limit = options.max_pixels; - // The declared sizes are refused before anything is decoded or allocated. - let (cw, ch) = ctx.coded_size(id, &p).map_err(err)?; - heic_rs::image::check_pixels(cw, ch, limit).map_err(err)?; - let (tw, th) = heic_rs::transform::transformed_size(cw, ch, &p.transforms).map_err(err)?; - heic_rs::image::check_pixels(tw, th, limit).map_err(err)?; - - let coded = Coded::decode(ctx, id, &p, limit)?; - let planes = coded.planes()?; - let colour = colour(&p, &coded.first_props); - let signal = ycc::Signal { matrix: colour.matrix, full_range: colour.full_range }; - let alpha_id = if with_alpha { ctx.alpha_item(id).map_err(err)? } else { None }; - let (w, h) = planes.size(); - // A grid's canvas dimensions come from its payload, not the checked `ispe` (CodeRabbit - // #48): check the real one, before [`ycc::to_rgb16`] allocates for it. - match (u32::try_from(w), u32::try_from(h)) { - (Ok(wu), Ok(hu)) => { - heic_rs::image::check_pixels(wu, hu, limit).map_err(err)?; - } - _ => return Err(Error::Limit(format!("the image canvas is {w}x{h}, beyond the {limit}-pixel limit"))), - } - let mode = if options.apply_transforms && orient::odd_crop(w, h, &p.transforms)? { ycc::Upsampling::Bilinear } else { ycc::Upsampling::Nearest }; - let mut data = ycc::to_rgb16(&planes, signal, alpha_id.is_some(), mode) - .ok_or_else(|| Error::Malformed("the decoded pictures don't cover the image".into()))?; - if let Some(aux) = alpha_id { - let ap = ctx.props(aux).map_err(err)?; - let alpha = Coded::decode(ctx, aux, &ap, limit)?; - let alpha_planes = alpha.planes()?; - if alpha_planes.size() != (w, h) { - return Err(Error::Unsupported("an alpha image of a different size than the picture")); - } - ycc::put_alpha(&alpha_planes, &mut data).ok_or_else(|| Error::Malformed("the alpha image is incomplete".into()))?; - } - let bit_depth = planes.bit_depth(); - let has_alpha = alpha_id.is_some(); - let mut img = orient::Pixels { width: w, height: h, ch: if has_alpha { 4 } else { 3 }, data }; - if options.apply_transforms { - img = orient::apply(img, &p.transforms)?; - } - Ok(Decoded { - width: u32::try_from(img.width).map_err(|_| Error::Limit("image too wide".into()))?, - height: u32::try_from(img.height).map_err(|_| Error::Limit("image too tall".into()))?, - has_alpha, - bit_depth, - data: img.data, - colour, - // A grid whose own properties carry no profile takes its tiles' (as on some iPhones). - icc: p.icc.or(coded.first_props.icc).map(<[u8]>::to_vec), - exif: None, - xmp: None, - }) -} - -/// How many times `max_pixels` the coded pictures of one item may hold together: a grid's tiles -/// cover its canvas rounded up to whole tiles, so legitimate grids sit near 1. -const GRID_BUDGET: u64 = 2; - -/// The most transform properties (`clap`/`irot`/`imir`) one item may carry. Real files have at -/// most one of each, so anything approaching this is a reordered or hostile association list. -const MAX_TRANSFORMS: usize = 12; - -/// The decoded pictures of an item: one, or a grid's tiles in `dimg` order. -struct Coded<'a> { - frames: Vec, - grid: Option, - /// The properties of the first coded picture (the item itself, or the first tile): where the - /// HEVC configuration and its VUI live. - first_props: ItemProps<'a>, - /// A failed 4:2:2 / 4:4:4 picture, for the error message. - chroma_format: u8, -} - -impl<'a> Coded<'a> { - fn decode(ctx: &Context<'a>, id: u32, p: &ItemProps<'a>, limit: u64) -> Result, Error> { - let (grid, ids) = match ctx.grid(id).map_err(err)? { - Some((g, tiles)) => (Some(g), tiles), - None => (None, vec![id]), - }; - let first = *ids.first().ok_or_else(|| Error::Malformed("grid lists no tiles".into()))?; - let first_props = if first == id { p.clone() } else { ctx.props(first).map_err(err)? }; - let chroma_format = first_props.hvcc.as_ref().map_or(1, |c| c.chroma_format); - // #1518: the decoder allocates each picture at its SPS's uncropped size, which a - // conformance window (or a slice picking another SPS) can make far larger than the - // declared one, and a grid holds all its tiles at once. Both are refused before decoding. - let mut total = 0u64; - for t in &ids { - let tp = ctx.props(*t).map_err(err)?; - let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?; - let sizes = vui::coded_sizes(&hvcc.parameter_sets()).ok_or_else(|| Error::Malformed("unreadable sequence parameter set".into()))?; - let mut largest = 0u64; - for (w, h) in sizes { - heic_rs::image::check_pixels(w, h, limit).map_err(err)?; - largest = largest.max(u64::from(w) * u64::from(h)); - } - total = total.saturating_add(largest); - } - if total > limit.saturating_mul(GRID_BUDGET) { - return Err(Error::Limit(format!("the coded pictures hold {total} pixels, over the {limit}-pixel limit"))); - } - let decode_one = |t: &u32| -> Result { - let tp = ctx.props(*t).map_err(err)?; - let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?; - let data = ctx.item_data(*t).map_err(err)?; - let nals = hvcc.split_nals(&data).map_err(err)?; - let params = hvcc.parameter_sets(); - if params.is_empty() { - return Err(Error::Malformed("hvcC carries no parameter sets".into())); - } - let frame = heic_rs::hevc::decode_still(¶ms, &nals).map_err(err)?; - frame.validate().map_err(err)?; - heic_rs::image::check_pixels(frame.width, frame.height, limit).map_err(err)?; - Ok(frame) - }; - #[cfg(not(target_arch = "wasm32"))] - let frames: Result, Error> = { - use rayon::prelude::*; - ids.par_iter().map(decode_one).collect() - }; - #[cfg(target_arch = "wasm32")] - let frames: Result, Error> = ids.iter().map(decode_one).collect(); - let frames = frames.map_err(|e| match e { - Error::Malformed(_) if chroma_format >= 2 => Error::Unsupported(CHROMA_422_444), - e => e, - })?; - Ok(Coded { frames, grid, first_props, chroma_format }) - } - - fn planes(&self) -> Result, Error> { - match (&self.grid, self.frames.as_slice()) { - (Some(g), tiles) => heic_rs::grid::Mosaic::new(g, tiles).map(ycc::Planes::Grid).map_err(err), - (None, [frame]) => Ok(ycc::Planes::Picture(frame)), - (None, _) => Err(Error::Malformed(format!("expected one coded picture (chroma format {})", self.chroma_format))), - } - } -} - -/// The colour description in force: `nclx` on the item (or, for a grid without one, on its -/// first tile), else the VUI of its (first) coded picture, else the H.265 defaults. -fn colour(p: &ItemProps<'_>, coded: &ItemProps<'_>) -> Colour { - if let Some(n) = p.nclx.or(coded.nclx) { - return Colour { primaries: n.primaries, transfer: n.transfer, matrix: n.matrix_code, full_range: n.range == Range::Full }; - } - let s = coded.hvcc.as_ref().and_then(|c| vui::signal(&c.parameter_sets())).unwrap_or_default(); - Colour { primaries: s.primaries.into(), transfer: s.transfer.into(), matrix: s.matrix.into(), full_range: s.full_range } -} - -/// The primary image's EXIF (TIFF structure) and XMP packet. Metadata is a courtesy: a broken -/// metadata item never fails a decode whose pixels came out fine. -fn metadata(ctx: &Context<'_>) -> (Option>, Option) { - let id = ctx.meta.primary; - // Metadata is best effort, so an item that would cost too much to rebuild is skipped, not an error. - let mut visits = 0_usize; - let cheap = |item: Option, visits: &mut usize| item.is_none_or(|item| item_visits(ctx, item, 0, visits).is_ok()); - let exif = if cheap(ctx.exif_item(id), &mut visits) { ctx.exif(id).ok().flatten().map(<[u8]>::to_vec) } else { None }; - let xmp_item = ctx.xmp_item(id).filter(|&x| cheap(Some(x), &mut visits)); - let xmp = xmp_item.and_then(|x| ctx.item_data(x).ok()).and_then(|d| match d { - Cow::Borrowed(b) => String::from_utf8(b.to_vec()).ok(), - Cow::Owned(b) => String::from_utf8(b).ok(), - }); - (exif, xmp.map(|x| x.trim_end_matches('\0').to_string())) -} - -#[cfg(test)] -mod tests_synthetic; - -#[cfg(test)] -mod tests { - use super::*; - - /// Found by PhotoCraft's `decode_heif` fuzz target: a malformed box makes heic-rs 0.1.1 slice - /// out of range (`boxes.rs:130`). It must be an error, not a crash. - const HEIC_RS_BOX_PANIC: [u8; 72] = [ - 0x00, 0x00, 0x00, 0x24, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x69, 0x66, 0x31, 0x4d, 0x69, 0x50, - 0x72, 0x6d, 0x69, 0x61, 0x66, 0x4d, 0x69, 0x48, 0x42, 0x72, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x65, 0x74, 0x61, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x75, 0x75, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x03, 0x08, 0x08, 0x08, 0x00, 0x03, 0x01, 0x03, 0x70, - 0x00, 0xa8, 0x00, - ]; - - #[test] - fn a_heic_rs_panic_is_a_malformed_error() { - for apply_transforms in [true, false] { - let r = decode(&HEIC_RS_BOX_PANIC, &Options { apply_transforms, ..Default::default() }); - assert!(matches!(r, Err(Error::Malformed(_))), "{r:?}"); - } - } - - #[test] - fn image_sequence_is_unsupported_with_a_clear_message() { - // An ftyp and nothing else: a HEIF image sequence would have a moov here instead of a meta. - let bytes = b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc"; - for r in [probe(bytes).map(|_| ()), decode(bytes, &Options::default()).map(|_| ())] { - assert!(matches!(&r, Err(Error::Unsupported(m)) if m.contains("sequence")), "{r:?}"); - } - } - - #[test] - fn garbage_is_an_error() { - for bytes in [&b""[..], b"\0\0\0\x18ftypheic\0\0\0\0mif1heic", &[0xFF; 64]] { - assert!(probe(bytes).is_err()); - assert!(decode(bytes, &Options::default()).is_err()); - assert!(decode_thumbnail(bytes, 1, &Options::default()).is_err()); - } - } - - #[test] - fn errors_display_their_kind() { - assert!(Error::Unsupported("x").to_string().contains("unsupported")); - assert!(Error::Limit("x".into()).to_string().contains("limit")); - assert!(Error::Malformed("x".into()).to_string().contains("malformed")); - } -} diff --git a/crates/heif/src/orient.rs b/crates/heif/src/orient.rs deleted file mode 100644 index 487eb7e220..0000000000 --- a/crates/heif/src/orient.rs +++ /dev/null @@ -1,178 +0,0 @@ -//! The container's transformative properties (`clap` crop, `irot` rotation, `imir` mirror), -//! applied to interleaved 16-bit pixels in the order the file associates them. -//! -//! `imir` follows libheif, which writes and reads `axis = 0` as a flip about the horizontal axis -//! (top and bottom exchanged) and `axis = 1` as a left-right flip. heic-rs 0.1.1 names the coded -//! values the other way round (`Mirror::LeftRight` is `axis = 0`), so they are swapped here. - -use heic_rs::props::Transform; -use heic_rs::props::simple::{Clap, Mirror, Rotation}; - -use crate::Error; - -/// Interleaved samples, `ch` per pixel, row-major. -pub struct Pixels { - pub width: usize, - pub height: usize, - pub ch: usize, - pub data: Vec, -} - -impl Pixels { - fn remap(&self, width: usize, height: usize, src: impl Fn(usize, usize) -> (usize, usize)) -> Pixels { - let ch = self.ch; - let mut data = vec![0u16; width * height * ch]; - for (y, row) in data.chunks_exact_mut(width * ch).enumerate() { - for (x, px) in row.chunks_exact_mut(ch).enumerate() { - let (sx, sy) = src(x, y); - let i = (sy * self.width + sx) * ch; - if let Some(s) = self.data.get(i..i + ch) { - px.copy_from_slice(s); - } - } - } - Pixels { width, height, ch, data } - } -} - -/// The rectangle `(left, top, width, height)` a `clap` selects from a `w` × `h` image. Its centre -/// is `((w - 1) / 2 + horizOff, (h - 1) / 2 + vertOff)`; a corner that falls between two pixels -/// is rounded as libheif does: left down, top up. -pub fn crop_rect(w: usize, h: usize, c: Clap) -> Result<(usize, usize, usize, usize), Error> { - let bad = || Error::Malformed("clap selects an impossible rectangle".into()); - let size = |(n, d): (u32, u32)| (d != 0).then(|| n / d).ok_or_else(bad); - let (cw, ch) = (size(c.width)? as usize, size(c.height)? as usize); - if cw == 0 || ch == 0 || cw > w || ch > h { - return Err(bad()); - } - // Twice the corner, so the half pixels of odd sizes stay exact. - let twice = |full: usize, cropped: usize, (n, d): (i32, u32)| -> Result { - if d == 0 { - return Err(bad()); - } - Ok((full - cropped) as i64 + (2 * i64::from(n)).div_euclid(i64::from(d))) - }; - let left = twice(w, cw, c.horiz_off)?.div_euclid(2); - let top = (twice(h, ch, c.vert_off)? + 1).div_euclid(2); - let left = usize::try_from(left).map_err(|_| bad())?; - let top = usize::try_from(top).map_err(|_| bad())?; - if left + cw > w || top + ch > h { - return Err(bad()); - } - Ok((left, top, cw, ch)) -} - -/// Whether a `clap` among `transforms` (applied to a `w` × `h` image) starts at an odd column -/// or row. libheif crops such images after upsampling their chroma bilinearly instead of with -/// its default nearest neighbour; [`crate::ycc`] follows it so the pixels match. -pub fn odd_crop(mut w: usize, mut h: usize, transforms: &[Transform]) -> Result { - for t in transforms { - match *t { - Transform::Crop(c) => { - let (left, top, cw, ch) = crop_rect(w, h, c)?; - if left % 2 == 1 || top % 2 == 1 { - return Ok(true); - } - (w, h) = (cw, ch); - } - Transform::Rotate(Rotation::Ccw90 | Rotation::Ccw270) => (w, h) = (h, w), - _ => {} - } - } - Ok(false) -} - -pub fn apply(mut img: Pixels, transforms: &[Transform]) -> Result { - for t in transforms { - let (w, h) = (img.width, img.height); - img = match *t { - Transform::Crop(c) => { - let (left, top, cw, ch) = crop_rect(w, h, c)?; - img.remap(cw, ch, |x, y| (x + left, y + top)) - } - // Counter-clockwise: the right column becomes the top row. - Transform::Rotate(Rotation::Ccw90) => img.remap(h, w, |x, y| (w - 1 - y, x)), - Transform::Rotate(Rotation::Ccw180) => img.remap(w, h, |x, y| (w - 1 - x, h - 1 - y)), - Transform::Rotate(Rotation::Ccw270) => img.remap(h, w, |x, y| (y, h - 1 - x)), - Transform::Rotate(Rotation::None) => img, - // `axis = 0` (heic-rs's `LeftRight`): top and bottom exchanged, as libheif reads it. - Transform::Mirror(Mirror::LeftRight) => img.remap(w, h, |x, y| (x, h - 1 - y)), - // `axis = 1`: left and right exchanged. - Transform::Mirror(Mirror::TopBottom) => img.remap(w, h, |x, y| (w - 1 - x, y)), - }; - } - Ok(img) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// 3×2, one channel: 1 2 3 / 4 5 6. - fn img() -> Pixels { - Pixels { width: 3, height: 2, ch: 1, data: vec![1, 2, 3, 4, 5, 6] } - } - - fn run(t: Transform) -> (usize, usize, Vec) { - let p = apply(img(), &[t]).unwrap(); - (p.width, p.height, p.data) - } - - #[test] - fn rotations_are_counter_clockwise() { - assert_eq!(run(Transform::Rotate(Rotation::Ccw90)), (2, 3, vec![3, 6, 2, 5, 1, 4])); - assert_eq!(run(Transform::Rotate(Rotation::Ccw180)), (3, 2, vec![6, 5, 4, 3, 2, 1])); - assert_eq!(run(Transform::Rotate(Rotation::Ccw270)), (2, 3, vec![4, 1, 5, 2, 6, 3])); - assert_eq!(run(Transform::Rotate(Rotation::None)), (3, 2, vec![1, 2, 3, 4, 5, 6])); - } - - #[test] - fn mirrors_follow_libheif() { - // axis 0 (heic-rs `LeftRight`) exchanges top and bottom; axis 1 left and right. - assert_eq!(run(Transform::Mirror(Mirror::LeftRight)), (3, 2, vec![4, 5, 6, 1, 2, 3])); - assert_eq!(run(Transform::Mirror(Mirror::TopBottom)), (3, 2, vec![3, 2, 1, 6, 5, 4])); - } - - fn clap(w: u32, h: u32, ho: i32, vo: i32) -> Clap { - Clap { width: (w, 1), height: (h, 1), horiz_off: (ho, 1), vert_off: (vo, 1) } - } - - #[test] - fn clap_corners_round_like_libheif() { - // Measured against libheif 1.23 on a 512 × 512 picture. - assert_eq!(crop_rect(512, 512, clap(301, 201, 0, 0)).unwrap(), (105, 156, 301, 201)); - assert_eq!(crop_rect(512, 512, clap(300, 200, 0, 0)).unwrap(), (106, 156, 300, 200)); - assert_eq!(crop_rect(512, 512, clap(301, 201, 37, -21)).unwrap(), (142, 135, 301, 201)); - assert_eq!(crop_rect(512, 512, clap(301, 201, -3, 5)).unwrap(), (102, 161, 301, 201)); - assert_eq!(crop_rect(512, 512, clap(300, 201, 0, 0)).unwrap(), (106, 156, 300, 201)); - assert_eq!(crop_rect(1500, 1000, clap(1001, 701, 37, -21)).unwrap(), (286, 129, 1001, 701)); - let p = apply(img(), &[Transform::Crop(clap(2, 1, 1, 0))]).unwrap(); - // The half-pixel top rounds down a row. - assert_eq!((p.width, p.height, p.data), (2, 1, vec![5, 6])); - } - - #[test] - fn impossible_claps_are_errors() { - for c in [ - clap(0, 1, 0, 0), - clap(4, 1, 0, 0), - clap(3, 2, 1, 0), - clap(3, 2, 0, -1), - Clap { width: (1, 0), ..clap(1, 1, 0, 0) }, - Clap { horiz_off: (0, 0), ..clap(1, 1, 0, 0) }, - ] { - assert!(crop_rect(3, 2, c).is_err(), "{c:?}"); - } - assert!(apply(img(), &[Transform::Crop(clap(9, 9, 0, 0))]).is_err()); - } - - #[test] - fn odd_crops_are_detected_through_rotations() { - assert!(!odd_crop(512, 512, &[Transform::Crop(clap(300, 200, 0, 0))]).unwrap()); - assert!(odd_crop(512, 512, &[Transform::Crop(clap(301, 200, 0, 0))]).unwrap()); - // After a quarter turn the crop applies to a 200 × 300 image. - let t = [Transform::Crop(clap(300, 200, 0, 0)), Transform::Rotate(Rotation::Ccw90), Transform::Crop(clap(197, 300, 0, 0))]; - assert!(odd_crop(512, 512, &t).unwrap()); - assert!(!odd_crop(512, 512, &[Transform::Rotate(Rotation::Ccw90)]).unwrap()); - } -} diff --git a/crates/heif/src/testdata.rs b/crates/heif/src/testdata.rs deleted file mode 100644 index 595cfa33c5..0000000000 --- a/crates/heif/src/testdata.rs +++ /dev/null @@ -1,542 +0,0 @@ -//! Synthetic HEIF files for tests (feature `testdata`): lossless, so every decoded sample is known. -//! -//! Each coded picture is one 32 × 32 coding tree unit stored as PCM samples (H.265 7.3.8.7): -//! the bitstream carries the YCbCr values verbatim, so the decoder's HEVC stage reproduces them -//! exactly and a test checks everything after it (grid composition, colour, transforms, -//! metadata) against values it chose. The few CABAC bins around the PCM data are written with a -//! minimal arithmetic encoder (9.3.4.4). Larger images are grids of such pictures, which is how -//! iPhones store photos too (with 512 × 512 tiles). -//! -//! Not a general HEIF or HEVC writer: 4:2:0 or monochrome, 8 or 10 bits, a CTU per picture. - -/// Side of every coded picture. -pub const TILE: u32 = 32; - -/// YCbCr samples at a luma position (chroma is taken at even positions, 4:2:0). -pub type Sampler<'a> = &'a dyn Fn(u32, u32) -> [u16; 3]; - -/// A property of the primary image. -#[derive(Debug, Clone, PartialEq)] -pub enum Prop { - /// `colr` of type `prof`. - Icc(Vec), - /// `colr` of type `nclx`: primaries, transfer, matrix, full range. - Nclx(u16, u16, u16, bool), - /// `irot`: quarter turns counter-clockwise. - Irot(u8), - /// `imir` with this axis. - Imir(u8), - /// `clap`: width, height, horizontal and vertical offset (whole pixels). - Clap(u32, u32, i32, i32), -} - -/// What [`build`] writes. -pub struct Spec<'a> { - /// Displayed (grid output) size, before transforms. - pub width: u32, - pub height: u32, - pub bit_depth: u8, - pub sample: Sampler<'a>, - /// Properties of the primary image, in association order. - pub props: Vec, - /// EXIF as a TIFF structure (written with HEIF's 4-byte offset header). - pub exif: Option>, - /// An alpha auxiliary image (monochrome, full range). - pub alpha: Option<&'a dyn Fn(u32, u32) -> u16>, - /// A thumbnail item of half the size with these samples (in its own coordinates). - pub thumbnail: Option>, - /// Auxiliary images of these types the decoder must ignore (HDR gain map, depth…). - pub ignored_aux: Vec<&'static str>, -} - -impl<'a> Spec<'a> { - pub fn new(width: u32, height: u32, sample: Sampler<'a>) -> Spec<'a> { - Spec { width, height, bit_depth: 8, sample, props: Vec::new(), exif: None, alpha: None, thumbnail: None, ignored_aux: Vec::new() } - } -} - -#[derive(Default)] -struct Bits { - bytes: Vec, - n: usize, -} - -impl Bits { - fn put(&mut self, v: u32, len: u32) { - for i in (0..len).rev() { - if self.n.is_multiple_of(8) { - self.bytes.push(0); - } - if (v >> i) & 1 == 1 - && let Some(b) = self.bytes.last_mut() - { - *b |= 0x80 >> (self.n % 8); - } - self.n += 1; - } - } - - fn ue(&mut self, v: u32) { - let x = u64::from(v) + 1; - let len = 64 - x.leading_zeros(); - self.put(0, len - 1); - self.put((x & 0xffff_ffff) as u32, len); - } - - fn align_zero(&mut self) { - while !self.n.is_multiple_of(8) { - self.put(0, 1); - } - } - - fn trailing(&mut self) { - self.put(1, 1); - self.align_zero(); - } -} - -/// The CABAC arithmetic encoder of H.265 9.3.4.4, for the bins these pictures need. -struct Cabac { - low: u32, - range: u32, - first: bool, - outstanding: u32, -} - -impl Cabac { - fn new() -> Cabac { - Cabac { low: 0, range: 510, first: true, outstanding: 0 } - } - - fn put_bit(&mut self, out: &mut Bits, b: u32) { - if self.first { - self.first = false; - } else { - out.put(b, 1); - } - while self.outstanding > 0 { - out.put(1 - b, 1); - self.outstanding -= 1; - } - } - - fn renorm(&mut self, out: &mut Bits) { - while self.range < 256 { - if self.low < 256 { - self.put_bit(out, 0); - } else if self.low >= 512 { - self.low -= 512; - self.put_bit(out, 1); - } else { - self.low -= 256; - self.outstanding += 1; - } - self.range <<= 1; - self.low <<= 1; - } - } - - /// `part_mode` = PART_2Nx2N: the most probable symbol of a fresh context (initValue 184 at - /// QP 26 gives pStateIdx 0, valMps 1), so the LPS range is `rangeTabLps[0][3]` = 240. - fn part_mode_2nx2n(&mut self, out: &mut Bits) { - let lps = [128, 176, 208, 240][((self.range >> 6) & 3) as usize]; - self.range -= lps; - self.renorm(out); - } - - /// A terminating bin equal to 1 (`pcm_flag`, `end_of_slice_segment_flag`), with the flush. - fn terminate_one(&mut self, out: &mut Bits) { - self.range -= 2; - self.low += self.range; - self.range = 2; - self.renorm(out); - self.put_bit(out, (self.low >> 9) & 1); - out.put(((self.low >> 7) & 3) | 1, 2); - } -} - -fn nal(kind: u8, rbsp: &[u8]) -> Vec { - let mut out = vec![kind << 1, 1]; - let mut zeros = 0; - for &b in rbsp { - if zeros >= 2 && b <= 3 { - out.push(3); - zeros = 0; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - out.push(b); - } - out -} - -fn profile_idc(bit_depth: u8, mono: bool) -> u32 { - match (bit_depth, mono) { - (_, true) => 4, // range extensions - (8, false) => 1, - _ => 2, - } -} - -fn ptl(w: &mut Bits, idc: u32) { - w.put(0, 2); - w.put(0, 1); - w.put(idc, 5); - w.put(1 << (31 - idc), 32); // compatible with itself - w.put(0b1001, 4); // progressive, frame only - w.put(0, 22); - w.put(0, 21); - w.put(0, 1); - w.put(93, 8); // level 3.1 -} - -fn parameter_sets(bit_depth: u8, mono: bool) -> [Vec; 3] { - let idc = profile_idc(bit_depth, mono); - let bd = u32::from(bit_depth); - let mut v = Bits::default(); - v.put(0, 4); - v.put(3, 2); - v.put(0, 6); - v.put(0, 3); - v.put(1, 1); - v.put(0xffff, 16); - ptl(&mut v, idc); - v.put(0, 1); // vps_sub_layer_ordering_info_present_flag - v.ue(0); - v.ue(0); - v.ue(0); - v.put(0, 6); // vps_max_layer_id - v.ue(0); // vps_num_layer_sets_minus1 - v.put(0, 1); // vps_timing_info_present_flag - v.put(0, 1); // vps_extension_flag - v.trailing(); - - let mut s = Bits::default(); - s.put(0, 4); - s.put(0, 3); - s.put(1, 1); - ptl(&mut s, idc); - s.ue(0); - s.ue(if mono { 0 } else { 1 }); - s.ue(TILE); - s.ue(TILE); - s.put(0, 1); // conformance_window_flag - s.ue(bd - 8); - s.ue(bd - 8); - s.ue(4); - s.put(1, 1); - s.ue(0); - s.ue(0); - s.ue(0); - s.ue(2); // log2_min_luma_coding_block_size_minus3: 32 - s.ue(0); // log2_diff_max_min_luma_coding_block_size: CTB 32 - s.ue(0); // log2_min_luma_transform_block_size_minus2: 4 - s.ue(3); // log2_diff_max_min_luma_transform_block_size: 32 - s.ue(0); - s.ue(0); - s.put(0, 1); // scaling_list_enabled_flag - s.put(0, 1); // amp_enabled_flag - s.put(0, 1); // sample_adaptive_offset_enabled_flag - s.put(1, 1); // pcm_enabled_flag - s.put(bd - 1, 4); // pcm_sample_bit_depth_luma_minus1 - s.put(bd - 1, 4); // pcm_sample_bit_depth_chroma_minus1 - s.ue(2); // log2_min_pcm_luma_coding_block_size_minus3: 32 - s.ue(0); // log2_diff_max_min_pcm_luma_coding_block_size - s.put(1, 1); // pcm_loop_filter_disabled_flag - s.ue(0); // num_short_term_ref_pic_sets - s.put(0, 1); // long_term_ref_pics_present_flag - s.put(0, 1); // sps_temporal_mvp_enabled_flag - s.put(0, 1); // strong_intra_smoothing_enabled_flag - s.put(0, 1); // vui_parameters_present_flag - s.put(0, 1); // sps_extension_present_flag - s.trailing(); - - let mut p = Bits::default(); - p.ue(0); - p.ue(0); - p.put(0, 6); // dependent slices, output flag, 3 extra header bits, sign hiding - p.put(0, 1); // cabac_init_present_flag - p.ue(0); - p.ue(0); - p.ue(0); // init_qp_minus26 (se(0) is the same bits) - p.put(0, 3); // constrained intra, transform skip, cu_qp_delta - p.ue(0); - p.ue(0); - p.put(0, 1); - p.put(0, 2); - p.put(0, 1); // transquant_bypass_enabled_flag - p.put(0, 1); // tiles_enabled_flag - p.put(0, 1); // entropy_coding_sync_enabled_flag - p.put(0, 1); // pps_loop_filter_across_slices_enabled_flag - p.put(1, 1); // deblocking_filter_control_present_flag - p.put(0, 1); // deblocking_filter_override_enabled_flag - p.put(1, 1); // pps_deblocking_filter_disabled_flag - p.put(0, 1); - p.put(0, 1); - p.ue(0); - p.put(0, 1); - p.put(0, 1); - p.trailing(); - [nal(32, &v.bytes), nal(33, &s.bytes), nal(34, &p.bytes)] -} - -/// One coded 32 × 32 picture: the `hvcC` payload and the item data (length-prefixed NAL). -struct Coded { - hvcc: Vec, - data: Vec, -} - -fn picture(bit_depth: u8, mono: bool, sample: &dyn Fn(u32, u32) -> [u16; 3]) -> Coded { - let bd = u32::from(bit_depth); - let mut w = Bits::default(); - w.put(1, 1); // first_slice_segment_in_pic_flag - w.put(0, 1); // no_output_of_prior_pics_flag - w.ue(0); - w.ue(2); // I slice - w.ue(0); // slice_qp_delta, se(0) - w.trailing(); // byte_alignment() - let mut c = Cabac::new(); - c.part_mode_2nx2n(&mut w); - c.terminate_one(&mut w); // pcm_flag - w.align_zero(); // pcm_alignment_zero_bit - for y in 0..TILE { - for x in 0..TILE { - w.put(u32::from(sample(x, y)[0]), bd); - } - } - if !mono { - for k in 1..3 { - for y in 0..TILE / 2 { - for x in 0..TILE / 2 { - w.put(u32::from(sample(2 * x, 2 * y)[k]), bd); - } - } - } - } - let mut c = Cabac::new(); - c.terminate_one(&mut w); // end_of_slice_segment_flag (its flush ends in the stop bit) - w.align_zero(); - let slice = nal(19, &w.bytes); - - let sets = parameter_sets(bit_depth, mono); - let mut h = vec![1u8, profile_idc(bit_depth, mono) as u8]; - h.extend_from_slice(&(1u32 << (31 - profile_idc(bit_depth, mono))).to_be_bytes()); - h.extend_from_slice(&[ - 0x90, - 0, - 0, - 0, - 0, - 0, - 93, - 0xf0, - 0, - 0xfc, - 0xfc | u8::from(!mono), - 0xf8 | (bit_depth - 8), - 0xf8 | (bit_depth - 8), - 0, - 0, - 0x0f, - 3, - ]); - for (kind, set) in [32u8, 33, 34].into_iter().zip(&sets) { - h.push(0x80 | kind); - h.extend_from_slice(&1u16.to_be_bytes()); - h.extend_from_slice(&(set.len() as u16).to_be_bytes()); - h.extend_from_slice(set); - } - let mut data = (slice.len() as u32).to_be_bytes().to_vec(); - data.extend_from_slice(&slice); - Coded { hvcc: h, data } -} - -fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec { - let mut v = ((payload.len() + 8) as u32).to_be_bytes().to_vec(); - v.extend_from_slice(kind); - v.extend_from_slice(payload); - v -} - -fn full_box(kind: &[u8; 4], version: u8, payload: &[u8]) -> Vec { - let mut p = vec![version, 0, 0, 0]; - p.extend_from_slice(payload); - bx(kind, &p) -} - -struct Item { - id: u16, - kind: &'static [u8; 4], - data: Vec, - /// Indices (1-based) into the property list, with the essential flag. - props: Vec<(u8, bool)>, - /// Not an image of its own (a grid tile). - hidden: bool, -} - -#[derive(Default)] -struct File { - items: Vec, - props: Vec>, - refs: Vec<(&'static [u8; 4], u16, Vec)>, -} - -impl File { - fn prop(&mut self, b: Vec) -> u8 { - self.props.push(b); - self.props.len() as u8 - } - - fn add(&mut self, kind: &'static [u8; 4], data: Vec, props: Vec<(u8, bool)>) -> u16 { - let id = self.items.len() as u16 + 1; - self.items.push(Item { id, kind, data, props, hidden: false }); - id - } - - /// A coded image of `w` × `h` (a grid when larger than a tile); returns its item id. - fn image(&mut self, w: u32, h: u32, bit_depth: u8, mono: bool, sample: &dyn Fn(u32, u32) -> [u16; 3]) -> u16 { - let (cols, rows) = (w.div_ceil(TILE), h.div_ceil(TILE)); - let ispe = |w: u32, h: u32| { - let mut p = w.to_be_bytes().to_vec(); - p.extend_from_slice(&h.to_be_bytes()); - full_box(b"ispe", 0, &p) - }; - let mut hvcc_prop = None; - let tile_ispe = self.prop(ispe(TILE, TILE)); - let mut tiles = Vec::new(); - for r in 0..rows { - for c in 0..cols { - let coded = picture(bit_depth, mono, &|x, y| sample((c * TILE + x).min(w - 1), (r * TILE + y).min(h - 1))); - let hv = *hvcc_prop.get_or_insert_with(|| self.prop(bx(b"hvcC", &coded.hvcc))); - tiles.push(self.add(b"hvc1", coded.data, vec![(hv, true), (tile_ispe, false)])); - } - } - if let ([only], true) = (tiles.as_slice(), w == TILE && h == TILE) { - return *only; - } - for it in self.items.iter_mut().filter(|i| tiles.contains(&i.id)) { - it.hidden = true; - } - let mut g = vec![0u8, 0, (rows - 1) as u8, (cols - 1) as u8]; - g.extend_from_slice(&(w as u16).to_be_bytes()); - g.extend_from_slice(&(h as u16).to_be_bytes()); - let grid_ispe = self.prop(ispe(w, h)); - let id = self.add(b"grid", g, vec![(grid_ispe, false)]); - self.refs.push((b"dimg", id, tiles)); - id - } - - fn write(self, primary: u16) -> Vec { - let ftyp = bx(b"ftyp", b"heic\0\0\0\0mif1heic"); - let mut hdlr = vec![0u8; 4]; - hdlr.extend_from_slice(b"pict"); - hdlr.extend_from_slice(&[0; 13]); - let hdlr = full_box(b"hdlr", 0, &hdlr); - let pitm = full_box(b"pitm", 0, &primary.to_be_bytes()); - let mut iinf = (self.items.len() as u16).to_be_bytes().to_vec(); - for it in &self.items { - let mut e = vec![2, 0, 0, u8::from(it.hidden)]; // version 2, flags - e.extend_from_slice(&it.id.to_be_bytes()); - e.extend_from_slice(&[0, 0]); - e.extend_from_slice(it.kind); - e.push(0); - iinf.extend_from_slice(&bx(b"infe", &e)); - } - let iinf = full_box(b"iinf", 0, &iinf); - let mut iref = Vec::new(); - for (kind, from, to) in &self.refs { - let mut r = from.to_be_bytes().to_vec(); - r.extend_from_slice(&(to.len() as u16).to_be_bytes()); - for t in to { - r.extend_from_slice(&t.to_be_bytes()); - } - iref.extend_from_slice(&bx(kind, &r)); - } - let iref = full_box(b"iref", 0, &iref); - let ipco = bx(b"ipco", &self.props.concat()); - let mut ipma = (self.items.iter().filter(|i| !i.props.is_empty()).count() as u32).to_be_bytes().to_vec(); - for it in self.items.iter().filter(|i| !i.props.is_empty()) { - ipma.extend_from_slice(&it.id.to_be_bytes()); - ipma.push(it.props.len() as u8); - ipma.extend(it.props.iter().map(|&(i, essential)| i | if essential { 0x80 } else { 0 })); - } - let iprp = bx(b"iprp", &[ipco, full_box(b"ipma", 0, &ipma)].concat()); - let iloc = |base: u32| { - let mut l = vec![0x44, 0x00]; - l.extend_from_slice(&(self.items.len() as u16).to_be_bytes()); - let mut offset = base; - for it in &self.items { - l.extend_from_slice(&it.id.to_be_bytes()); - l.extend_from_slice(&[0, 0, 0, 0, 0, 1]); // construction method 0, data ref 0, one extent - l.extend_from_slice(&offset.to_be_bytes()); - l.extend_from_slice(&(it.data.len() as u32).to_be_bytes()); - offset += it.data.len() as u32; - } - full_box(b"iloc", 1, &l) - }; - let meta = |base| full_box(b"meta", 0, &[hdlr.clone(), pitm.clone(), iloc(base), iinf.clone(), iref.clone(), iprp.clone()].concat()); - let start = (ftyp.len() + meta(0).len() + 8) as u32; - let mdat = bx(b"mdat", &self.items.iter().flat_map(|i| i.data.iter().copied()).collect::>()); - [ftyp, meta(start), mdat].concat() - } -} - -/// Writes the HEIF file `spec` describes. -pub fn build(spec: &Spec<'_>) -> Vec { - let mut f = File::default(); - let primary = f.image(spec.width, spec.height, spec.bit_depth, false, spec.sample); - let mut assoc = Vec::new(); - for p in &spec.props { - let b = match p { - Prop::Icc(icc) => bx(b"colr", &[b"prof".as_slice(), icc].concat()), - Prop::Nclx(pr, tc, mc, full) => { - let mut c = b"nclx".to_vec(); - for v in [pr, tc, mc] { - c.extend_from_slice(&v.to_be_bytes()); - } - c.push(if *full { 0x80 } else { 0 }); - bx(b"colr", &c) - } - Prop::Irot(a) => bx(b"irot", &[a & 3]), - Prop::Imir(a) => bx(b"imir", &[a & 1]), - Prop::Clap(w, h, ho, vo) => { - let mut c = Vec::new(); - for v in [*w as i32, 1, *h as i32, 1, *ho, 1, *vo, 1] { - c.extend_from_slice(&v.to_be_bytes()); - } - bx(b"clap", &c) - } - }; - assoc.push((f.prop(b), true, matches!(p, Prop::Clap(..)))); - } - if let Some(it) = f.items.iter_mut().find(|i| i.id == primary) { - it.props.extend(assoc.iter().map(|&(i, e, _)| (i, e))); - } - if let Some(exif) = &spec.exif { - let id = f.add(b"Exif", [&[0u8, 0, 0, 0][..], exif].concat(), Vec::new()); - f.refs.push((b"cdsc", id, vec![primary])); - } - let bd = spec.bit_depth; - let aux = |f: &mut File, urn: &str, sample: &dyn Fn(u32, u32) -> [u16; 3]| { - let id = f.image(spec.width, spec.height, bd, true, sample); - let auxc = f.prop(full_box(b"auxC", 0, &[urn.as_bytes(), &[0]].concat())); - if let Some(it) = f.items.iter_mut().find(|i| i.id == id) { - it.props.push((auxc, true)); - } - f.refs.push((b"auxl", id, vec![primary])); - }; - if let Some(alpha) = spec.alpha { - aux(&mut f, "urn:mpeg:hevc:2015:auxid:1", &|x, y| [alpha(x, y), 0, 0]); - } - for urn in &spec.ignored_aux { - aux(&mut f, urn, &|x, y| [((x + y) % 256) as u16, 0, 0]); - } - if let Some(sample) = spec.thumbnail { - // Half the size, with the primary image's colour and orientation (not its crop). - let id = f.image(spec.width / 2, spec.height / 2, spec.bit_depth, false, sample); - if let Some(it) = f.items.iter_mut().find(|i| i.id == id) { - it.props.extend(assoc.iter().filter(|a| !a.2).map(|&(i, e, _)| (i, e))); - } - f.refs.push((b"thmb", id, vec![primary])); - } - f.write(primary) -} diff --git a/crates/heif/src/tests_synthetic.rs b/crates/heif/src/tests_synthetic.rs deleted file mode 100644 index 1286ff82a9..0000000000 --- a/crates/heif/src/tests_synthetic.rs +++ /dev/null @@ -1,200 +0,0 @@ -//! Decoding lossless synthetic HEIF files ([`crate::testdata`]): every expected sample is known. - -use crate::testdata::{Prop, Spec, build}; -use crate::{Error, Options, decode, decode_thumbnail, probe}; - -/// A luma value unique enough to identify its position; chroma neutral. -fn luma(x: u32, y: u32) -> u16 { - ((x * 7 + y * 13) % 220 + 20) as u16 -} - -fn grey(x: u32, y: u32) -> [u16; 3] { - [luma(x, y), 128, 128] -} - -const FULL_601: Prop = Prop::Nclx(1, 13, 6, true); - -/// Decoded red channel at `(x, y)`, back in 8-bit code values. -fn at(d: &crate::Decoded, x: u32, y: u32) -> u16 { - let ch = if d.has_alpha { 4 } else { 3 }; - d.data[((y * d.width + x) as usize) * ch] / 257 -} - -fn decoded(spec: &Spec) -> crate::Decoded { - decode(&build(spec), &Options::default()).unwrap() -} - -#[test] -fn a_grid_reassembles_exactly() { - // 4 × 3 tiles of 32, cropped by the grid to 100 × 70. - let d = decoded(&Spec { props: vec![FULL_601], ..Spec::new(100, 70, &grey) }); - assert_eq!((d.width, d.height, d.bit_depth, d.has_alpha), (100, 70, 8, false)); - for y in 0..70 { - for x in 0..100 { - let px = &d.data[((y * 100 + x) * 3) as usize..][..3]; - assert_eq!(px, [luma(x, y) * 257; 3], "({x}, {y})"); - } - } - let info = probe(&build(&Spec::new(100, 70, &grey))).unwrap(); - assert_eq!((info.width, info.height, info.coded_width, info.coded_height, info.bit_depth), (100, 70, 100, 70, 8)); -} - -#[test] -fn colour_follows_the_matrix_and_range() { - // BT.601 full range, a saturated orange: within one code value of the exact conversion. - let (y, cb, cr) = (150.0f32, 80.0, 190.0); - let s = |_: u32, _: u32| [y as u16, cb as u16, cr as u16]; - let d = decoded(&Spec { props: vec![FULL_601], ..Spec::new(32, 32, &s) }); - let (u, v) = (cb - 128.0, cr - 128.0); - let expected = [y + 1.402 * v, y - 0.344_136 * u - 0.714_136 * v, y + 1.772 * u].map(|c| c.clamp(0.0, 255.0)); - for (got, want) in d.data[..3].iter().zip(expected) { - assert!((f32::from(*got) / 257.0 - want).abs() <= 1.0, "{:?} vs {expected:?}", &d.data[..3]); - } - assert_eq!(d.colour, crate::Colour { primaries: 1, transfer: 13, matrix: 6, full_range: true }); - - // No nclx and no VUI: the H.265 defaults, limited range (16 → black, 235 → white). - let ends = |x: u32, _: u32| [if x < 16 { 16 } else { 235 }, 128, 128]; - let d = decoded(&Spec::new(32, 32, &ends)); - assert!(!d.colour.full_range); - assert_eq!((d.data[0], d.data[20 * 3]), (0, 65535)); -} - -#[test] -fn ten_bit_samples_keep_their_precision() { - let s = |x: u32, y: u32| [(x * 31 + y) as u16 % 1024, 512, 512]; - let d = decoded(&Spec { bit_depth: 10, props: vec![FULL_601], ..Spec::new(64, 32, &s) }); - assert_eq!(d.bit_depth, 10); - for x in [0, 1, 5, 33, 63] { - let want = ((x * 31) % 1024) as f64 / 1023.0 * 65535.0; - assert!((f64::from(d.data[(x * 3) as usize]) - want).abs() <= 1.0, "x {x}"); - } -} - -#[test] -fn container_transforms_are_applied_like_libheif() { - let (w, h) = (70u32, 40u32); - let spec = |props: Vec| Spec { props: [vec![FULL_601], props].concat(), ..Spec::new(w, h, &grey) }; - // irot: counter-clockwise quarter turns. - let d = decoded(&spec(vec![Prop::Irot(1)])); - assert_eq!((d.width, d.height), (h, w)); - assert_eq!(at(&d, 0, 0), luma(w - 1, 0)); // the right column becomes the top row - assert_eq!(at(&d, h - 1, w - 1), luma(0, h - 1)); - let d = decoded(&spec(vec![Prop::Irot(2)])); - assert_eq!(at(&d, 0, 0), luma(w - 1, h - 1)); - let d = decoded(&spec(vec![Prop::Irot(3)])); - assert_eq!(at(&d, 0, 0), luma(0, h - 1)); - // imir: axis 0 exchanges top and bottom, axis 1 left and right (libheif's reading). - let d = decoded(&spec(vec![Prop::Imir(0)])); - assert_eq!((at(&d, 0, 0), at(&d, 5, 0)), (luma(0, h - 1), luma(5, h - 1))); - let d = decoded(&spec(vec![Prop::Imir(1)])); - assert_eq!((at(&d, 0, 0), at(&d, 0, 5)), (luma(w - 1, 0), luma(w - 1, 5))); - // clap: centred crop moved by its offsets; a half-pixel corner goes left and down. - let d = decoded(&spec(vec![Prop::Clap(31, 21, 3, -2)])); - assert_eq!((d.width, d.height), (31, 21)); - // left = (70 - 31 + 6) / 2 = 22.5 → 22, top = (40 - 21 - 4) / 2 = 7.5 → 8 - assert_eq!(at(&d, 0, 0), luma(22, 8)); - // In association order: crop, then turn, then mirror. - let d = decoded(&spec(vec![Prop::Clap(30, 20, 0, 0), Prop::Irot(1), Prop::Imir(1)])); - assert_eq!((d.width, d.height), (20, 30)); - // The crop is (20, 10) to (49, 29); the turn brings its bottom-right corner to the top-right, - // the left-right mirror to the top-left. - assert_eq!(at(&d, 0, 0), luma(49, 29)); - let info = probe(&build(&spec(vec![Prop::Irot(1)]))).unwrap(); - assert_eq!((info.width, info.height, info.coded_width, info.coded_height), (h, w, w, h)); - // Transforms off: as coded. - let d = decode(&build(&spec(vec![Prop::Irot(1)])), &Options { apply_transforms: false, ..Default::default() }).unwrap(); - assert_eq!((d.width, d.height, at(&d, 3, 2)), (w, h, luma(3, 2))); -} - -#[test] -fn metadata_aux_images_and_thumbnails() { - let icc = b"not parsed here: carried verbatim".to_vec(); - let exif = b"MM\0\x2a\0\0\0\x08\0\0".to_vec(); - let spec = Spec { - props: vec![Prop::Icc(icc.clone()), FULL_601], - exif: Some(exif.clone()), - thumbnail: Some(&|_, _| [77, 128, 128]), - ignored_aux: vec!["urn:com:apple:photo:2020:aux:hdrgainmap", "urn:mpeg:hevc:2015:auxid:2"], - ..Spec::new(64, 64, &grey) - }; - let bytes = build(&spec); - let d = decode(&bytes, &Options::default()).unwrap(); - assert_eq!((d.width, d.height, d.has_alpha), (64, 64, false)); - assert_eq!(d.icc.as_deref(), Some(icc.as_slice())); - assert_eq!(d.exif.as_deref(), Some(exif.as_slice())); - let t = decode_thumbnail(&bytes, 32, &Options::default()).unwrap().unwrap(); - assert_eq!((t.width, t.height, t.data[0]), (32, 32, 77 * 257)); - assert_eq!(t.exif.as_deref(), Some(exif.as_slice())); - assert_eq!(t.icc.as_deref(), Some(icc.as_slice())); - assert!(decode_thumbnail(&bytes, 33, &Options::default()).unwrap().is_none()); -} - -#[test] -fn alpha_comes_from_its_auxiliary_image() { - let alpha = |x: u32, _: u32| (x * 4) as u16; - let d = decoded(&Spec { props: vec![FULL_601], alpha: Some(&alpha), ..Spec::new(64, 32, &grey) }); - assert!(d.has_alpha); - assert_eq!(d.data.len(), 64 * 32 * 4); - assert_eq!((d.data[3], d.data[10 * 4 + 3]), (0, 40 * 257)); - assert_eq!(d.data[..3], [luma(0, 0) * 257; 3]); -} - -#[test] -fn limits_are_checked_before_decoding() { - let bytes = build(&Spec::new(96, 64, &grey)); - let r = decode(&bytes, &Options { max_pixels: 96 * 64 - 1, ..Default::default() }); - assert!(matches!(r, Err(Error::Limit(_))), "{r:?}"); -} - -/// #1518: a grid's tiles together are held to the pixel budget before any is decoded. A -/// 33 × 33 canvas fits 1089 pixels, but its four 32 × 32 tiles hold 4096: over twice the limit. -#[test] -fn grid_tiles_are_held_to_the_pixel_budget_together() { - let bytes = build(&Spec::new(33, 33, &grey)); - let r = decode(&bytes, &Options { max_pixels: 33 * 33, ..Default::default() }); - assert!(matches!(r, Err(Error::Limit(_))), "{r:?}"); - let d = decode(&bytes, &Options { max_pixels: 2 * 32 * 32, ..Default::default() }).unwrap(); - assert_eq!((d.width, d.height), (33, 33)); -} - -#[test] -fn truncated_and_corrupted_files_are_errors_not_panics() { - let bytes = build(&Spec { props: vec![FULL_601, Prop::Irot(1)], thumbnail: Some(&grey), ..Spec::new(64, 64, &grey) }); - let full = decode(&bytes, &Options::default()).unwrap(); - for cut in (0..bytes.len()).step_by(7) { - let b = &bytes[..cut]; - // Cut inside the photo: an error. Cut in the trailing thumbnail: the whole photo. - if let (Ok(_), Ok(d)) = (probe(b), decode(b, &Options::default())) { - assert_eq!(d.data, full.data, "cut at {cut} of {}", bytes.len()); - } - let _ = decode_thumbnail(b, 1, &Options::default()); - } - // Flip bits all over the file: any outcome but a panic. - let mut state = 0x2545_f491_u32; - for _ in 0..400 { - let mut b = bytes.clone(); - for _ in 0..3 { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - let i = state as usize % b.len(); - b[i] ^= 1 << (state % 8); - } - let _ = probe(&b); - let _ = decode(&b, &Options::default()); - let _ = decode_thumbnail(&b, 1, &Options::default()); - } -} - -/// CodeRabbit #44: heic-rs keeps every associated transform and each one re-allocates the -/// whole picture, so 13 of them are over the [`crate::MAX_TRANSFORMS`] cap and refused. -#[test] -fn too_many_transform_properties_are_refused() { - let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 13).collect(), ..Spec::new(32, 32, &grey) }); - let r = decode(&bytes, &Options::default()); - assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("transform")), "{r:?}"); - // At the cap they're not: 12 identity rotations decode normally. - let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 12).collect(), ..Spec::new(32, 32, &grey) }); - let d = decode(&bytes, &Options::default()).unwrap(); - assert_eq!((d.width, d.height), (32, 32)); -} diff --git a/crates/heif/src/vui.rs b/crates/heif/src/vui.rs deleted file mode 100644 index 6bc629fa57..0000000000 --- a/crates/heif/src/vui.rs +++ /dev/null @@ -1,459 +0,0 @@ -//! The colour description in an HEVC sequence parameter set's VUI (Rec. ITU-T H.265, 7.3.2.2 and -//! Annex E): the fallback a HEIF reader uses when the item carries no `colr` box of type `nclx`. -//! iPhone photos are the common case: they label their colour with an ICC profile only and say in -//! the VUI that their YCbCr is full range. -//! -//! Only the syntax up to `matrix_coeffs` is read. Anything this parser can't follow returns `None` -//! and the caller falls back to the H.265 defaults; it never fails a decode. - -/// What the VUI's `video_signal_type` says (H.265 E.3.1). Absent fields keep the defaults the -/// standard infers: limited range, every code point 2 ("unspecified"). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Signal { - pub full_range: bool, - pub primaries: u8, - pub transfer: u8, - pub matrix: u8, -} - -impl Default for Signal { - fn default() -> Self { - Signal { full_range: false, primaries: 2, transfer: 2, matrix: 2 } - } -} - -/// NAL unit type of a sequence parameter set. -const SPS_NUT: u8 = 33; - -/// Reads the signal description from the SPS among `parameter_sets` (NAL units with their -/// two-byte header, as an `hvcC` record stores them). `None`: no SPS, or one this reader can't -/// follow; `Some(Signal::default())`: an SPS without VUI colour fields. -pub fn signal(parameter_sets: &[&[u8]]) -> Option { - let sps = parameter_sets.iter().find(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == SPS_NUT))?; - parse_sps(&unescape(sps.get(2..)?)) -} - -/// The uncropped picture size (`pic_width/height_in_luma_samples`) of every SPS among -/// `parameter_sets`: what the decoder allocates before it applies the conformance window, so the -/// pixel budget is checked against it (heic-rs reports only the first SPS, cropped). `None`: an -/// SPS this reader can't follow. -pub fn coded_sizes(parameter_sets: &[&[u8]]) -> Option> { - parameter_sets - .iter() - .filter(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == SPS_NUT)) - .map(|sps| { - let rbsp = unescape(sps.get(2..)?); - let r = &mut Bits { data: &rbsp, pos: 0 }; - sps_size(r).map(|(w, h, _)| (w, h)) - }) - .collect() -} - -/// Reads an SPS up to and including the picture size, leaving `r` after it: width, height and -/// `sps_max_sub_layers_minus1`. -fn sps_size(r: &mut Bits) -> Option<(u32, u32, u32)> { - r.skip(4)?; // sps_video_parameter_set_id - let max_sub_layers_minus1 = r.u(3)?; - if max_sub_layers_minus1 > 6 { - return None; - } - r.skip(1)?; // sps_temporal_id_nesting_flag - profile_tier_level(r, max_sub_layers_minus1)?; - r.ue()?; // sps_seq_parameter_set_id - if r.ue()? == 3 { - r.skip(1)?; // separate_colour_plane_flag - } - let width = r.ue()?; // pic_width_in_luma_samples - let height = r.ue()?; // pic_height_in_luma_samples - Some((width, height, max_sub_layers_minus1)) -} - -/// Removes emulation prevention bytes (`00 00 03` → `00 00`). -fn unescape(nal: &[u8]) -> Vec { - let mut out = Vec::with_capacity(nal.len()); - let mut zeros = 0usize; - for &b in nal { - if zeros >= 2 && b == 3 { - zeros = 0; - continue; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - out.push(b); - } - out -} - -struct Bits<'a> { - data: &'a [u8], - pos: usize, -} - -impl Bits<'_> { - fn u(&mut self, n: u32) -> Option { - let mut v = 0u32; - for _ in 0..n { - let byte = *self.data.get(self.pos / 8)?; - v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1); - self.pos += 1; - } - Some(v) - } - - fn flag(&mut self) -> Option { - self.u(1).map(|b| b == 1) - } - - fn skip(&mut self, n: usize) -> Option<()> { - self.pos = self.pos.checked_add(n)?; - (self.pos <= self.data.len().saturating_mul(8)).then_some(()) - } - - /// `ue(v)`; values past 32 bits are refused (no valid field here needs them). - fn ue(&mut self) -> Option { - let mut zeros = 0u32; - while !self.flag()? { - zeros += 1; - if zeros > 31 { - return None; - } - } - let rest = self.u(zeros)?; - ((1u64 << zeros) - 1 + u64::from(rest)).try_into().ok() - } - - fn se(&mut self) -> Option<()> { - self.ue().map(|_| ()) - } -} - -/// `profile_tier_level(1, max_sub_layers_minus1)` (7.3.3): only skipped. -fn profile_tier_level(r: &mut Bits, max_sub_layers_minus1: u32) -> Option<()> { - r.skip(88)?; // general profile space .. general_inbld/reserved flag - r.skip(8)?; // general_level_idc - let mut present = [(false, false); 8]; - for p in present.iter_mut().take(max_sub_layers_minus1 as usize) { - *p = (r.flag()?, r.flag()?); - } - if max_sub_layers_minus1 > 0 { - r.skip(2 * (8 - max_sub_layers_minus1 as usize))?; // reserved_zero_2bits - } - for &(profile, level) in present.iter().take(max_sub_layers_minus1 as usize) { - if profile { - r.skip(88)?; - } - if level { - r.skip(8)?; - } - } - Some(()) -} - -/// `scaling_list_data()` (7.3.4): only skipped. -fn scaling_list_data(r: &mut Bits) -> Option<()> { - for size_id in 0..4u32 { - let step = if size_id == 3 { 3 } else { 1 }; - for _ in (0..6).step_by(step) { - if !r.flag()? { - r.ue()?; // scaling_list_pred_matrix_id_delta - } else { - let coefs = 64.min(1 << (4 + (size_id << 1))); - if size_id > 1 { - r.se()?; // scaling_list_dc_coef_minus8 - } - for _ in 0..coefs { - r.se()?; // scaling_list_delta_coef - } - } - } - } - Some(()) -} - -/// `st_ref_pic_set(idx)` (7.3.7) as it appears in an SPS; returns `NumDeltaPocs[idx]`. -fn st_ref_pic_set(r: &mut Bits, idx: usize, num_delta_pocs: &[u32]) -> Option { - if idx != 0 && r.flag()? { - // inter_ref_pic_set_prediction_flag: predicted from the previous set (in an SPS, - // delta_idx_minus1 is absent and RefRpsIdx = idx - 1). - r.skip(1)?; // delta_rps_sign - r.ue()?; // abs_delta_rps_minus1 - let reference = *num_delta_pocs.get(idx - 1)?; - let mut count = 0u32; - for _ in 0..=reference { - let used = r.flag()?; - let kept = used || r.flag()?; // use_delta_flag when not used_by_curr_pic_flag - count += u32::from(kept); - } - return Some(count); - } - let negative = r.ue()?; - let positive = r.ue()?; - let total = negative.checked_add(positive)?; - if total > 32 { - return None; // at most 16 + 16 for any level - } - for _ in 0..total { - r.ue()?; // delta_poc_s*_minus1 - r.skip(1)?; // used_by_curr_pic_s*_flag - } - Some(total) -} - -fn parse_sps(rbsp: &[u8]) -> Option { - let r = &mut Bits { data: rbsp, pos: 0 }; - let (_, _, max_sub_layers_minus1) = sps_size(r)?; - parse_sps_parameters(r, max_sub_layers_minus1)?; - parse_vui(r) -} - -fn parse_sps_parameters(r: &mut Bits<'_>, max_sub_layers_minus1: u32) -> Option<()> { - if r.flag()? { - for _ in 0..4 { - r.ue()?; // conf_win_*_offset - } - } - r.ue()?; // bit_depth_luma_minus8 - r.ue()?; // bit_depth_chroma_minus8 - let log2_max_poc_lsb = r.ue()?.checked_add(4)?; - if log2_max_poc_lsb > 16 { - return None; - } - let first = if r.flag()? { 0 } else { max_sub_layers_minus1 }; - for _ in first..=max_sub_layers_minus1 { - r.ue()?; // sps_max_dec_pic_buffering_minus1 - r.ue()?; // sps_max_num_reorder_pics - r.ue()?; // sps_max_latency_increase_plus1 - } - for _ in 0..6 { - r.ue()?; // coding/transform block sizes, transform hierarchy depths - } - if r.flag()? && r.flag()? { - // scaling_list_enabled_flag, sps_scaling_list_data_present_flag - scaling_list_data(r)?; - } - r.skip(2)?; // amp_enabled_flag, sample_adaptive_offset_enabled_flag - if r.flag()? { - // pcm_enabled_flag - r.skip(8)?; // pcm sample bit depths - r.ue()?; - r.ue()?; - r.skip(1)?; // pcm_loop_filter_disabled_flag - } - let sets = r.ue()? as usize; - if sets > 64 { - return None; - } - let mut num_delta_pocs = Vec::with_capacity(sets); - for idx in 0..sets { - let n = st_ref_pic_set(r, idx, &num_delta_pocs)?; - num_delta_pocs.push(n); - } - if r.flag()? { - // long_term_ref_pics_present_flag - let n = r.ue()?; - if n > 32 { - return None; - } - for _ in 0..n { - r.skip(log2_max_poc_lsb as usize + 1)?; // lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag - } - } - r.skip(2)?; // sps_temporal_mvp_enabled_flag, strong_intra_smoothing_enabled_flag - Some(()) -} - -fn parse_vui(r: &mut Bits<'_>) -> Option { - let mut signal = Signal::default(); - if !r.flag()? { - return Some(signal); // no VUI - } - if r.flag()? && r.u(8)? == 255 { - // aspect_ratio_info_present_flag, aspect_ratio_idc == EXTENDED_SAR - r.skip(32)?; - } - if r.flag()? { - r.skip(1)?; // overscan_appropriate_flag - } - if r.flag()? { - // video_signal_type_present_flag - r.skip(3)?; // video_format - signal.full_range = r.flag()?; - if r.flag()? { - signal.primaries = r.u(8)? as u8; - signal.transfer = r.u(8)? as u8; - signal.matrix = r.u(8)? as u8; - } - } - Some(signal) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A bit writer for building parameter sets in tests. - #[derive(Default)] - pub(crate) struct Writer { - pub bits: Vec, - } - - impl Writer { - pub fn u(&mut self, v: u32, n: u32) { - for i in (0..n).rev() { - self.bits.push(i < 32 && (v >> i) & 1 == 1); - } - } - pub fn ue(&mut self, v: u32) { - let x = u64::from(v) + 1; - let len = 64 - x.leading_zeros(); - self.u(0, len - 1); - for i in (0..len).rev() { - self.bits.push((x >> i) & 1 == 1); - } - } - pub fn bytes(mut self) -> Vec { - self.bits.push(true); // rbsp_stop_one_bit - while !self.bits.len().is_multiple_of(8) { - self.bits.push(false); - } - self.bits.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| (a << 1) | u8::from(b))).collect() - } - } - - fn sps(vui: impl FnOnce(&mut Writer), st_sets: impl FnOnce(&mut Writer)) -> Vec { - let mut w = Writer::default(); - w.u(0, 4); - w.u(1, 3); // one sub-layer above the base - w.u(1, 1); - w.u(0, 88); - w.u(93, 8); - w.u(0b11, 2); // sub-layer profile and level present - w.u(0, 2 * 7); - w.u(0, 88); - w.u(0, 8); - w.ue(0); - w.ue(1); // 4:2:0 - w.ue(4032); - w.ue(3024); - w.u(1, 1); // conformance window - for _ in 0..4 { - w.ue(3); - } - w.ue(0); - w.ue(0); - w.ue(4); - w.u(1, 1); - for _ in 0..2 { - w.ue(1); - w.ue(0); - w.ue(0); - } - for v in [0, 3, 0, 3, 0, 0] { - w.ue(v); - } - w.u(1, 1); // scaling lists, with data - w.u(1, 1); - for size_id in 0..4u32 { - for _ in (0..6).step_by(if size_id == 3 { 3 } else { 1 }) { - w.u(1, 1); - if size_id > 1 { - w.ue(0); - } - for _ in 0..64.min(1 << (4 + (size_id << 1))) { - w.ue(0); - } - } - } - w.u(0, 2); - w.u(1, 1); // pcm - w.u(0x77, 8); - w.ue(0); - w.ue(1); - w.u(1, 1); - st_sets(&mut w); - w.u(1, 1); // long-term pictures - w.ue(1); - w.u(0, 8 + 1); - w.u(0, 2); - vui(&mut w); - let mut nal = vec![SPS_NUT << 1, 1]; - // escape like a real NAL so `signal` has to unescape - let mut zeros = 0; - for b in w.bytes() { - if zeros >= 2 && b <= 3 { - nal.push(3); - zeros = 0; - } - zeros = if b == 0 { zeros + 1 } else { 0 }; - nal.push(b); - } - nal - } - - fn two_rps(w: &mut Writer) { - w.ue(2); - w.ue(1); // set 0: one negative picture - w.ue(0); - w.ue(0); - w.u(1, 1); - w.u(1, 1); // set 1: predicted from set 0 - w.u(0, 1); - w.ue(0); - w.u(0, 1); // not used ... - w.u(1, 1); // ... but kept - w.u(1, 1); - } - - #[test] - fn reads_full_range_and_matrix_from_the_vui() { - let nal = sps( - |w| { - w.u(1, 1); // vui present - w.u(1, 1); - w.u(255, 8); - w.u(0x0001_0001, 32); - w.u(1, 1); - w.u(0, 1); - w.u(1, 1); // video_signal_type_present_flag - w.u(5, 3); - w.u(1, 1); // full range - w.u(1, 1); - w.u(12, 8); - w.u(13, 8); - w.u(6, 8); - }, - two_rps, - ); - let s = signal(&[&[0x40, 1, 0xc], &nal, &[0x44, 1]]); - assert_eq!(s, Some(Signal { full_range: true, primaries: 12, transfer: 13, matrix: 6 })); - } - - #[test] - fn absent_fields_take_the_standard_defaults() { - let no_vui = sps(|w| w.u(0, 1), |w| w.ue(0)); - assert_eq!(signal(&[&no_vui]), Some(Signal::default())); - let range_only = sps( - |w| { - w.u(1, 1); - w.u(0, 2); - w.u(1, 1); - w.u(5, 3); - w.u(1, 1); - w.u(0, 1); // no colour description - }, - |w| w.ue(0), - ); - assert_eq!(signal(&[&range_only]), Some(Signal { full_range: true, ..Signal::default() })); - } - - #[test] - fn missing_or_truncated_sps_is_none() { - assert_eq!(signal(&[]), None); - assert_eq!(signal(&[&[0x40, 1, 2, 3]]), None); - let nal = sps(|w| w.u(0, 1), |w| w.ue(0)); - for cut in 2..nal.len() - 2 { - // never panics; most cuts are None - let _ = signal(&[nal.get(..cut).unwrap_or_default()]); - } - assert_eq!(signal(&[&[SPS_NUT << 1, 1, 0xff, 0xff, 0xff]]), None); - } -} diff --git a/crates/heif/src/ycc.rs b/crates/heif/src/ycc.rs deleted file mode 100644 index 384d25f2ae..0000000000 --- a/crates/heif/src/ycc.rs +++ /dev/null @@ -1,352 +0,0 @@ -//! YCbCr → RGB for decoded HEVC pictures, done here rather than in heic-rs so the result matches -//! libheif (the reference every HEIF tool is checked against) to within one code value: -//! -//! - **Which matrix and range.** The item's `colr` `nclx` box when there is one; otherwise the -//! HEVC VUI ([`crate::vui`]); otherwise the H.265 defaults (limited range). An unspecified matrix -//! is BT.601, as libheif reads it. heic-rs 0.1.1 ignores the VUI and assumes BT.709 limited -//! range for every file without `nclx`, which shifts every iPhone photo (full range, ICC only) -//! by about 8 code values. -//! - **Chroma upsampling.** Nearest neighbour (each chroma sample covers its 2×2 or 2×1 luma -//! block), as libheif does by default. libheif switches to a centred bilinear filter (weights -//! 9/3/3/1 sixteenths, in integers) when a `clap` crop starts at an odd column or row; so does -//! [`Upsampling::Bilinear`]. -//! -//! The arithmetic is floating point and the result 16-bit, whatever the coded depth, so the -//! develop pipeline gets every bit the conversion produces. - -use heic_rs::grid::Mosaic; -use heic_rs::hevc::{ChromaFormat, Frame}; - -/// The coded pictures one image is made of. -pub enum Planes<'a> { - Picture(&'a Frame), - Grid(Mosaic<'a>), -} - -impl Planes<'_> { - pub fn size(&self) -> (usize, usize) { - match self { - Planes::Picture(f) => (f.width as usize, f.height as usize), - Planes::Grid(m) => (m.width() as usize, m.height() as usize), - } - } - - pub fn bit_depth(&self) -> u8 { - match self { - Planes::Picture(f) => f.bit_depth, - Planes::Grid(m) => m.bit_depth(), - } - } - - pub fn chroma(&self) -> ChromaFormat { - match self { - Planes::Picture(f) => f.chroma, - Planes::Grid(m) => m.chroma(), - } - } - - fn chroma_width(&self) -> usize { - let (w, h) = self.size(); - self.chroma().chroma_size(w as u32, h as u32).0 as usize - } - - fn luma_row(&self, y: usize, dst: &mut [u16]) -> Option<()> { - match self { - Planes::Picture(f) => copy_row(&f.y, f.y_stride as usize, y, dst), - Planes::Grid(m) => m.luma_row(y, dst), - } - } - - fn chroma_row(&self, cr: bool, r: usize, dst: &mut [u16]) -> Option<()> { - match self { - Planes::Picture(f) => copy_row(if cr { &f.cr } else { &f.cb }, f.c_stride as usize, r, dst), - Planes::Grid(m) => m.chroma_row(cr, r, dst), - } - } -} - -fn copy_row(plane: &[u16], stride: usize, y: usize, dst: &mut [u16]) -> Option<()> { - let start = y.checked_mul(stride)?; - dst.copy_from_slice(plane.get(start..start.checked_add(dst.len())?)?); - Some(()) -} - -/// How the three coded channels map to R, G, B (H.273 `MatrixCoefficients`). -#[derive(Debug, Clone, Copy, PartialEq)] -enum Matrix { - /// 0: the channels are G, B, R. - Identity, - /// 8: YCgCo. - YCgCo, - /// Every Kr/Kb matrix: R = Y + `cr_r`·Cr, G = Y − `cb_g`·Cb − `cr_g`·Cr, B = Y + `cb_b`·Cb. - Kr { cr_r: f32, cb_g: f32, cr_g: f32, cb_b: f32 }, -} - -impl Matrix { - /// Unknown, reserved and unspecified codes are BT.601, like libheif. - fn from_code(code: u16) -> Matrix { - let (kr, kb) = match code { - 0 => return Matrix::Identity, - 8 => return Matrix::YCgCo, - 1 => (0.2126, 0.0722), - 4 => (0.30, 0.11), - 7 => (0.212, 0.087), - // 10 (BT.2020 constant luminance) is approximated by its non-constant matrix. - 9 | 10 => (0.2627, 0.0593), - _ => (0.299, 0.114), - }; - let kg = 1.0 - kr - kb; - Matrix::Kr { cr_r: 2.0 * (1.0 - kr), cb_g: 2.0 * kb * (1.0 - kb) / kg, cr_g: 2.0 * kr * (1.0 - kr) / kg, cb_b: 2.0 * (1.0 - kb) } - } -} - -/// How the samples are to be read: the matrix and the range. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Signal { - pub matrix: u16, - pub full_range: bool, -} - -/// How subsampled chroma is brought to the luma resolution. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Upsampling { - Nearest, - /// Centred bilinear: chroma sits between its two luma columns (and rows for 4:2:0). - Bilinear, -} - -/// One chroma row brought to the full width `w` of luma row `y`. -fn chroma_at(planes: &Planes<'_>, cr: bool, y: usize, w: usize, mode: Upsampling, buf: &mut [u16], next: &mut [u16]) -> Option> { - let chroma = planes.chroma(); - let (xs, ys) = (chroma.x_shift(), chroma.y_shift()); - let (wf, hf) = planes.size(); - let rows = chroma.chroma_size(wf as u32, hf as u32).1 as usize; - let cy = y >> ys; - planes.chroma_row(cr, cy, buf)?; - let last = buf.len().checked_sub(1)?; - if mode == Upsampling::Nearest || xs == 0 { - return (0..w).map(|x| buf.get(x >> xs).copied()).collect(); - } - // The nearer neighbour on each axis takes a quarter of the weight. - let ny = if ys == 0 { - cy - } else if y.is_multiple_of(2) { - cy.saturating_sub(1) - } else { - (cy + 1).min(rows.checked_sub(1)?) - }; - planes.chroma_row(cr, ny, next)?; - (0..w) - .map(|x| { - let cx = x >> 1; - let nx = if x % 2 == 0 { cx.saturating_sub(1) } else { (cx + 1).min(last) }; - let (a, an) = (u32::from(*buf.get(cx)?), u32::from(*buf.get(nx)?)); - let v = if ys == 0 { - (3 * a + an + 2) >> 2 - } else { - let (b, bn) = (u32::from(*next.get(cx)?), u32::from(*next.get(nx)?)); - (9 * a + 3 * b + 3 * an + bn + 8) >> 4 - }; - u16::try_from(v).ok() - }) - .collect() -} - -/// Converts `planes` to interleaved 16-bit RGB, or RGBA with room left for alpha (filled with -/// 65535 here). `None` when the planes can't supply a row they promised (a malformed grid). -pub fn to_rgb16(planes: &Planes<'_>, signal: Signal, alpha: bool, mode: Upsampling) -> Option> { - let (w, h) = planes.size(); - let ch = if alpha { 4 } else { 3 }; - let bd = u32::from(planes.bit_depth()); - if !(8..=16).contains(&bd) || w == 0 || h == 0 { - return None; - } - // The default caller limit is 2²8 pixels, at most four channels per pixel, so the largest - // legitimate `w·h·ch` is 2²30 samples. Anything more is a malformed or hostile canvas the - // decode path would have refused before calling here (CodeRabbit #48): refuse rather than - // ask for a multi-gigabuffer (or worse, over usize). - if w.checked_mul(h)?.checked_mul(ch)? > 1 << 30 { - return None; - } - let max = ((1u32 << bd) - 1) as f32; - let half = (1u32 << (bd - 1)) as f32; - let scale = (1u32 << (bd - 8)) as f32; - // Normalised Y = (v − y_off)·y_mul, Cb/Cr = (v − half)·c_mul. - let (y_off, y_mul, c_mul) = - if signal.full_range { (0.0, 1.0 / max, 1.0 / max) } else { (16.0 * scale, 1.0 / (219.0 * scale), 1.0 / (224.0 * scale)) }; - let matrix = Matrix::from_code(signal.matrix); - let mono = planes.chroma() == ChromaFormat::Monochrome; - let cw = planes.chroma_width(); - - let mut out = vec![0u16; w.checked_mul(h)?.checked_mul(ch)?]; - let row = |y: usize, dst: &mut [u16]| -> Option<()> { - let mut luma = vec![0u16; w]; - planes.luma_row(y, &mut luma)?; - let (cb, cr) = if mono { - (Vec::new(), Vec::new()) - } else { - let (mut buf, mut next) = (vec![0u16; cw], vec![0u16; cw]); - (chroma_at(planes, false, y, w, mode, &mut buf, &mut next)?, chroma_at(planes, true, y, w, mode, &mut buf, &mut next)?) - }; - for (x, (px, &yv)) in dst.chunks_exact_mut(ch).zip(&luma).enumerate() { - let rgb = if mono { - let v = (f32::from(yv) - y_off) * y_mul; - [v, v, v] - } else { - let (u, v) = (f32::from(*cb.get(x)?), f32::from(*cr.get(x)?)); - match matrix { - // G, B, R all read like luma. - Matrix::Identity => [(v - y_off) * y_mul, (f32::from(yv) - y_off) * y_mul, (u - y_off) * y_mul], - Matrix::YCgCo => { - let (yn, cg, co) = ((f32::from(yv) - y_off) * y_mul, (u - half) * c_mul, (v - half) * c_mul); - let t = yn - cg; - [t + co, yn + cg, t - co] - } - Matrix::Kr { cr_r, cb_g, cr_g, cb_b } => { - let (yn, u, v) = ((f32::from(yv) - y_off) * y_mul, (u - half) * c_mul, (v - half) * c_mul); - [yn + cr_r * v, yn - cb_g * u - cr_g * v, yn + cb_b * u] - } - } - }; - for (o, c) in px.iter_mut().zip(rgb) { - *o = (c.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - } - if alpha && let Some(a) = px.get_mut(3) { - *a = u16::MAX; - } - } - Some(()) - }; - let row_len = w * ch; - #[cfg(not(target_arch = "wasm32"))] - let ok = { - use rayon::prelude::*; - out.par_chunks_mut(row_len).enumerate().all(|(y, dst)| row(y, dst).is_some()) - }; - #[cfg(target_arch = "wasm32")] - let ok = out.chunks_mut(row_len).enumerate().all(|(y, dst)| row(y, dst).is_some()); - ok.then_some(out) -} - -/// Writes an alpha picture's luma, full range, into channel 3 of `rgba`. -pub fn put_alpha(planes: &Planes<'_>, rgba: &mut [u16]) -> Option<()> { - let (w, h) = planes.size(); - let max = ((1u32 << u32::from(planes.bit_depth()).clamp(1, 16)) - 1) as f32; - let mut luma = vec![0u16; w]; - for (y, row) in rgba.chunks_exact_mut(w * 4).enumerate().take(h) { - planes.luma_row(y, &mut luma)?; - for (px, &a) in row.as_chunks_mut::<4>().0.iter_mut().zip(&luma) { - let v = (f32::from(a) / max).clamp(0.0, 1.0); - px[3] = (v * 65535.0 + 0.5) as u16; - } - } - Some(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn frame(w: u32, h: u32, bd: u8, chroma: ChromaFormat, y: u16, cb: u16, cr: u16) -> Frame { - let (cw, chh) = chroma.chroma_size(w, h); - let n = (cw * chh) as usize; - Frame { - width: w, - height: h, - bit_depth: bd, - chroma, - y: vec![y; (w * h) as usize], - cb: vec![cb; n], - cr: vec![cr; n], - y_stride: w, - c_stride: cw, - } - } - - fn rgb(f: &Frame, matrix: u16, full_range: bool) -> [u16; 3] { - let v = to_rgb16(&Planes::Picture(f), Signal { matrix, full_range }, false, Upsampling::Nearest).unwrap(); - [v[0], v[1], v[2]] - } - - #[test] - fn neutral_and_primaries_convert_exactly() { - // Full-range grey stays grey; limited-range black and white reach the ends. - assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128), 6, true), [128 * 257; 3]); - assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 16, 128, 128), 1, false), [0; 3]); - assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 235, 128, 128), 1, false), [65535; 3]); - assert_eq!(rgb(&frame(4, 4, 10, ChromaFormat::Yuv420, 940, 512, 512), 9, false), [65535; 3]); - // BT.601 full-range pure red: Y = 76.245, Cb = 84.97, Cr = 255.5 → (255, 0, 0) within rounding. - let red = rgb(&frame(2, 2, 8, ChromaFormat::Yuv444, 76, 85, 255), 6, true); - assert!(red[0] > 65000 && red[1] < 300 && red[2] < 300, "{red:?}"); - // Identity: the channels are G, B, R. - assert_eq!(rgb(&frame(2, 2, 8, ChromaFormat::Yuv444, 10, 20, 30), 0, true), [30 * 257, 10 * 257, 20 * 257]); - // Monochrome. - assert_eq!(rgb(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0), 6, true), [51 * 257; 3]); - } - - #[test] - fn chroma_is_nearest_neighbour() { - // 4:2:0, 4×2 luma, chroma 2×1: the left chroma sample covers columns 0–1 only. - let mut f = frame(4, 2, 8, ChromaFormat::Yuv420, 128, 128, 128); - f.cr = vec![200, 128]; - let v = to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, false, Upsampling::Nearest).unwrap(); - let red: Vec = v.chunks(3).map(|p| p[0]).collect(); - assert!(red[0] == red[1] && red[1] == red[4] && red[0] > red[2] && red[2] == 128 * 257, "{red:?}"); - } - - #[test] - fn bilinear_chroma_is_centred_9_3_3_1() { - // 4:2:0, 4×4 luma, chroma 2×2 with one bright corner sample. - let mut f = frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128); - f.cr = vec![200, 128, 128, 128]; - let p = Planes::Picture(&f); - let (mut buf, mut next) = (vec![0; 2], vec![0; 2]); - let rows: Vec> = (0..4).map(|y| chroma_at(&p, true, y, 4, Upsampling::Bilinear, &mut buf, &mut next).unwrap()).collect(); - // Row 0 sits nearest chroma row 0 (and clamps upward); row 1 blends a quarter of row 1. - assert_eq!(rows[0], [200, 182, 146, 128]); - assert_eq!(rows[1], [182, 169, 142, 128]); - assert_eq!(rows[2], [146, 142, 133, 128]); - assert_eq!(rows[3], [128; 4]); - assert_eq!(chroma_at(&p, true, 1, 4, Upsampling::Nearest, &mut buf, &mut next).unwrap(), [200, 200, 128, 128]); - } - - #[test] - fn alpha_and_bad_planes() { - let f = frame(2, 2, 8, ChromaFormat::Yuv420, 128, 128, 128); - let mut v = to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, true, Upsampling::Nearest).unwrap(); - assert_eq!(v[3], 65535); - put_alpha(&Planes::Picture(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0)), &mut v).unwrap(); - assert_eq!(v[3], 51 * 257); - let mut short = frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128); - short.y.truncate(5); - assert!(to_rgb16(&Planes::Picture(&short), Signal { matrix: 6, full_range: true }, false, Upsampling::Bilinear).is_none()); - assert!( - to_rgb16( - &Planes::Picture(&frame(2, 2, 7, ChromaFormat::Yuv420, 0, 0, 0)), - Signal { matrix: 6, full_range: true }, - false, - Upsampling::Nearest - ) - .is_none() - ); - } - - /// CodeRabbit #48: a plane claiming 500 000 × 500 000 pixels must be refused without ever - /// allocating for it (before the cap this vec was never built; upper-bounding allocation - /// would have been a 7.5-gibabuffer or a panic instead of an error). - #[test] - fn an_oversized_canvas_is_refused_without_allocation() { - let f = Frame { - width: 500_000, - height: 500_000, - bit_depth: 8, - chroma: ChromaFormat::Yuv420, - y: vec![128], - cb: vec![128; 4], - cr: vec![128; 4], - y_stride: 0, - c_stride: 0, - }; - assert!(to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, false, Upsampling::Nearest).is_none()); - } -} diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index 4f2fad315e..f59f560836 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -17,6 +17,6 @@ chrono = { workspace = true } [dev-dependencies] # Lossless synthetic HEIC files: the HEIF item reader is proved against a real container writer. -lightcraft-heif = { workspace = true, features = ["testdata"] } +craft-heif = { workspace = true, features = ["testdata"] } proptest = { workspace = true } serde_json = { workspace = true } diff --git a/crates/meta/src/heif.rs b/crates/meta/src/heif.rs index 1d768f7a69..453c81c40f 100644 --- a/crates/meta/src/heif.rs +++ b/crates/meta/src/heif.rs @@ -2,7 +2,7 @@ //! (box structure from ISO/IEC 14496-12, item model from ISO/IEC 23008-12). //! //! HEIC is what iPhones and Macs write. Its pixels need an HEVC decoder (the optional -//! `lightcraft-heif` crate), its metadata does not, so this reader is in every build: a HEIC +//! `craft-heif` crate), its metadata does not, so this reader is in every build: a HEIC //! imports with its capture time, camera and lens whether or not the build can show the picture. //! //! The `meta` box holds an item information box (`iinf`, one `infe` per item) naming each item's @@ -390,14 +390,14 @@ mod tests { assert!(embedded(&lying).exif.is_none()); } - /// The real container writer of `lightcraft-heif`, so the reader is proved against the layout + /// The real container writer of `craft-heif`, so the reader is proved against the layout /// a HEIF encoder produces and not only against this module's own test builder. #[test] fn a_synthetic_heif_file_carries_its_exif() { let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00"); - let mut spec = lightcraft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]); + let mut spec = craft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]); spec.exif = Some(tiff.clone()); - let file = lightcraft_heif::testdata::build(&spec); + let file = craft_heif::testdata::build(&spec); assert!(is_heif(&file)); assert_eq!(embedded(&file).exif.as_deref(), Some(tiff.as_slice())); assert_eq!(crate::extract(&file).capture_time.map(|d| d.to_iso()).as_deref(), Some("2026-10-18T13:00:00-05:00")); diff --git a/xtask/src/ci.rs b/xtask/src/ci.rs index 556ea01b12..f5aa147a2d 100644 --- a/xtask/src/ci.rs +++ b/xtask/src/ci.rs @@ -286,10 +286,7 @@ pub(crate) fn cmd_ci(args: &[&str]) -> Result<(), String> { let mut c = cargo(); c.args(["clippy", "-p", "lightcraft-codecs", "--features", "heif", "--all-targets", "--", "-D", "warnings"]); run(c, "cargo clippy -p lightcraft-codecs --features heif --all-targets -- -D warnings")?; - test( - tests(&with_test_targets(&["-p", "lightcraft-codecs", "-p", "lightcraft-heif", "--features", "lightcraft-codecs/heif"])), - "heif", - )?; + test(tests(&with_test_targets(&["-p", "lightcraft-codecs", "--features", "lightcraft-codecs/heif"])), "heif")?; // the engine's HEIC import test, with the decoder (the workspace run checks the error) test(tests(&["-p", "lightcraft-engine", "--lib", "--features", "lightcraft-codecs/heif", "heic"]), "heif") }), diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index 2143d09bbb..21352f2f3b 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -7,7 +7,7 @@ //! - fmt, layers, assets, roots: always (seconds); //! - clippy on the whole workspace (check builds only; catches callers broken by an API change); //! - the tests of the changed packages only (not their dependents); -//! - heif when `lightcraft-codecs` / `lightcraft-heif` changed; +//! - heif when `lightcraft-codecs` changed (or the workspace files, which pin craft-heif); //! - parity when the tracker docs, a command/control crate, or a file's path changed (renames and //! deletions: the tracker cites paths); //! - the wasm check of the changed packages that must build for wasm32. @@ -28,7 +28,7 @@ const WORKSPACE_WIDE_DIRS: &[&str] = &[".cargo/"]; /// Packages whose ids or paths the parity tracker cites (commands, develop controls, UI menus). const PARITY_PACKAGES: &[&str] = &["lightcraft-engine", "lightcraft-develop", "lightcraft-ui-egui", "lightcraft-cli"]; const PARITY_DOCS: &[&str] = &["docs/parity-checklist.md", "docs/gaps.md"]; -const HEIF_PACKAGES: &[&str] = &["lightcraft-codecs", "lightcraft-heif"]; +const HEIF_PACKAGES: &[&str] = &["lightcraft-codecs"]; /// Files outside a package's directory that it compiles in (`include_str!` / `include_bytes!`, /// a build script's `rerun-if-changed`): a change to one counts as a change to those packages. /// An entry ending in `/` covers the directory. `embedded_files_are_mapped` keeps this complete. diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 70597bffbd..d9afb1aa3f 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -43,7 +43,6 @@ pub const TABLE: &[(&str, Class)] = &[ ("fetch", Class::Layer(0)), ("denoise-core", Class::Layer(1)), ("denoise", Class::Layer(1)), - ("heif", Class::Layer(0)), ("raw", Class::Layer(1)), ("codecs", Class::Layer(1)), ("meta", Class::Layer(1)), From 85fda195601592d9f1b5f8f462edeee25bfe1a43 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 01:25:39 +0000 Subject: [PATCH 05/23] Pin craft-tiff to the merge of storytold/craft-libs#795 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 992d833789..cd3c31ba60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1225,7 +1225,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6595c432463d456cf91361d1cab1a4416661a006#6595c432463d456cf91361d1cab1a4416661a006" +source = "git+https://github.com/storytold/craft-libs?rev=3b3104981bb3093904a12e44d6a3b41c6c4c39c8#3b3104981bb3093904a12e44d6a3b41c6c4c39c8" dependencies = [ "serde", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 5fae7a219e..2d2e11ef83 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ lightcraft-wincolor = { path = "crates/wincolor" } lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } # TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783). -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6595c432463d456cf91361d1cab1a4416661a006" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "3b3104981bb3093904a12e44d6a3b41c6c4c39c8" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } From e629da6b393724a89cfe59bac0eb347b0cfea366 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 01:25:45 +0000 Subject: [PATCH 06/23] Pin craft-heif to the merge of storytold/craft-libs#794 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7c4b6ad874..d5897f4568 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1202,7 +1202,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955 [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7e66c62b7a87db26993795a9da7ab35d098805b2#7e66c62b7a87db26993795a9da7ab35d098805b2" +source = "git+https://github.com/storytold/craft-libs?rev=6e21c5b0b1358f7d5505e7ea395948fe21f4d872#6e21c5b0b1358f7d5505e7ea395948fe21f4d872" dependencies = [ "heic-rs", "rayon", diff --git a/Cargo.toml b/Cargo.toml index d3f9bcdcb2..24d54fd84a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,7 +45,7 @@ lightcraft-ui-egui = { path = "crates/ui-egui" } lightcraft-mcp = { path = "crates/mcp" } lightcraft-fetch = { path = "crates/fetch" } # HEIC/HEIF: the shared decoder (moved from crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "7e66c62b7a87db26993795a9da7ab35d098805b2" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "6e21c5b0b1358f7d5505e7ea395948fe21f4d872" } lightcraft-segment = { path = "crates/segment" } lightcraft-geocode = { path = "crates/geocode" } lightcraft-slideshow = { path = "crates/slideshow" } From 5fedd946f34d3548a1f9e57b5a8af03798907234 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 04:29:28 +0000 Subject: [PATCH 07/23] docs: the HEIF rows point at craft-heif, not the removed crates/heif --- docs/file-format-parity.md | 2 +- docs/parity-checklist.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6c5f74ae22..f72a9b235a 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -19,7 +19,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/ | TIFF | ✅ 8/16/32-bit | ✅ 8/16-bit, LZW/ZIP | ✅ 1–64-bit integer, 16–64-bit float, bilevel, CCITT fax, WhiteIsZero | ✅ 8/16-bit, 32-bit float linear, none / LZW / ZIP | `crates/tiff`, `crates/codecs/src/tiff_codec.rs` | | PNG | ✅ | ✅ | ✅ | ✅ | | | PSD / PSB | ✅ (maximized-compatibility composite) | ✅ (Classic: PSD export, edit-in round trip) | ✅ merged composite | ⬜ (external-editor round trip writes 16-bit TIFF) | `crates/codecs/src/psd.rs` | -| HEIC / HEIF | ✅ | ⬜ (Classic) / HDR only | ✅ in every release build (`crates/heif`, heic-rs) | ⬜ | `heif` feature on by packaging scripts | +| HEIC / HEIF | ✅ | ⬜ (Classic) / HDR only | ✅ in every release build (`craft-heif` from craft-libs, heic-rs) | ⬜ | `heif` feature on by packaging scripts | | AVIF | ✅ | ✅ (HDR) | ⬜ recognised, not decoded (no permissive pure-Rust AV1 decoder) | ✅ 8/10-bit, PQ HDR | | | JPEG XL | ✅ | ✅ | ✅ (`jxl-oxide`) incl. DNG 1.7 JXL tiles | ✅ lossy / lossless, 8/16-bit, PQ HDR (`jixel`, native only; ⬜ web) | `crates/engine/src/tests/export.rs` | | WebP | not in its document types | ⬜ | ✅ | ✅ | beyond target | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 7d1ec1a01a..2abf5a2594 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -81,7 +81,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `crates/heif`, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `craft-heif` from craft-libs, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | From 4068e131f755307d662d3a6b0d4ef2d66b654ef4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 00:53:36 +0000 Subject: [PATCH 08/23] Use craft-gainmap from craft-libs for gain map metadata and arithmetic crates/codecs/src/gainmap.rs keeps the JPEG layout (encode_jpeg, read_jpeg, is_gain_map_jpeg) and re-exports GainMapMeta, GainImage, GainMapOptions, ISO_URN, compute and apply from craft-gainmap, which is this file's metadata and arithmetic moved to craft-libs (storytold/craft-libs#904). The tests of the moved code went with it. --- Cargo.lock | 9 + Cargo.toml | 2 + crates/codecs/Cargo.toml | 1 + crates/codecs/src/gainmap.rs | 642 +---------------------------------- docs/file-format-parity.md | 2 +- 5 files changed, 22 insertions(+), 634 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8e2258a983..dbaac1f99e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1199,6 +1199,14 @@ name = "craft-fonts-build" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +[[package]] +name = "craft-gainmap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=119415f46f601e20b9bc6b1b4d6979ceda86d88e#119415f46f601e20b9bc6b1b4d6979ceda86d88e" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-heif" version = "0.1.0" @@ -3677,6 +3685,7 @@ version = "0.21.0" dependencies = [ "avif-serialize", "bytemuck", + "craft-gainmap", "craft-heif", "dhat", "image", diff --git a/Cargo.toml b/Cargo.toml index 6966af4f10..41ba05620b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,8 @@ craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +# HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). +craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "119415f46f601e20b9bc6b1b4d6979ceda86d88e" } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false } diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 2a766aeee7..019009d7c1 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -12,6 +12,7 @@ workspace = true lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } +craft-gainmap = { workspace = true } craft-heif = { workspace = true, optional = true } serde = { workspace = true } bytemuck = { workspace = true } diff --git a/crates/codecs/src/gainmap.rs b/crates/codecs/src/gainmap.rs index 9280314067..4a6f485818 100644 --- a/crates/codecs/src/gainmap.rs +++ b/crates/codecs/src/gainmap.rs @@ -1,547 +1,21 @@ -//! Gain map HDR images (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to -//! rebuild the HDR rendition, so the file looks right everywhere and lights up on HDR displays. +//! Gain map JPEGs (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to rebuild +//! the HDR rendition, so the file looks right everywhere and lights up on HDR displays. +//! +//! The metadata formats and the arithmetic ([`compute`], [`apply`], [`GainMapMeta`]) are +//! `craft-gainmap`'s, re-exported here. This module lays the two images out in a JPEG: //! -//! - [`compute`] measures a gain map from an SDR and an HDR rendition of the same picture (linear -//! light, same primaries). Measure it against the base *as written* (decoded from its 8-bit -//! codes), so quantisation in the base is handed back by the gain map. -//! - [`apply`] rebuilds the HDR rendition from a base and its gain map. //! - [`encode_jpeg`] writes a gain map JPEG: the base with an MPF index (CIPA DC-007), the ISO //! 21496-1 marker and Adobe/Google container XMP, followed by the gain map JPEG carrying the ISO //! 21496-1 metadata, the Adobe `hdrgm` XMP (Android, Chrome) and Apple's description of the same //! map (what survives an iMessage send). //! - [`read_jpeg`] finds and decodes the gain map of a gain map JPEG (ours, cameras, Lightroom), //! from its ISO 21496-1 metadata or, failing that, its `hdrgm` XMP. -//! -//! All gains are log2. A decoder recovers `log2(hdr + offset_hdr) − log2(sdr + offset_sdr)` as -//! `min + (max − min) · (code / 255)^(1 / gamma)`, scaled by a weight in 0..1 that depends on how -//! much headroom the display has between `base_headroom` and `alternate_headroom`. + +pub use craft_gainmap::{GainImage, GainMapMeta, GainMapOptions, ISO_URN, apply, compute}; use crate::encode::{EncodeImage, EncodeMeta, Samples, jpeg_app_segments, xmp_segment}; use crate::{ChromaSubsampling, Error, Format, Result, jpeg, jpeg_par}; -/// The ISO 21496-1 namespace that opens its APP2 payloads (NUL terminated). -pub const ISO_URN: &[u8] = b"urn:iso:std:iso:ts:21496:-1\0"; - -/// Fixed denominator for the metadata's rationals: one value per setting, byte-identical output. -const DENOMINATOR: u32 = 1_000_000; - -/// Gain map parameters (ISO 21496-1 / Adobe `hdrgm`). Per-channel arrays repeat the first value -/// when the map is single-channel. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct GainMapMeta { - /// Three gain channels (R, G, B) instead of one luminance gain. - pub multichannel: bool, - /// The gain applies in the base image's colour space. - pub use_base_colour_space: bool, - /// log2 headroom at which the base is shown as is (0: an SDR base). - pub base_headroom: f32, - /// log2 headroom at which the gain map applies in full. - pub alternate_headroom: f32, - pub min: [f32; 3], - pub max: [f32; 3], - pub gamma: [f32; 3], - pub base_offset: [f32; 3], - pub alternate_offset: [f32; 3], -} - -impl Default for GainMapMeta { - fn default() -> Self { - GainMapMeta { - multichannel: false, - use_base_colour_space: true, - base_headroom: 0.0, - alternate_headroom: 1.0, - min: [0.0; 3], - max: [1.0; 3], - gamma: [1.0; 3], - base_offset: [1.0 / 64.0; 3], - alternate_offset: [1.0 / 64.0; 3], - } - } -} - -impl GainMapMeta { - fn channels(&self) -> usize { - if self.multichannel { 3 } else { 1 } - } - - /// Usable by [`apply`]: finite, positive gammas, max ≥ min, headrooms in order. - pub fn is_valid(&self) -> bool { - let fin = |a: &[f32; 3]| a.iter().all(|v| v.is_finite()); - fin(&self.min) - && fin(&self.max) - && fin(&self.gamma) - && fin(&self.base_offset) - && fin(&self.alternate_offset) - && self.gamma.iter().all(|g| *g > 0.0) - && self.min.iter().zip(&self.max).all(|(a, b)| b >= a) - && self.base_headroom.is_finite() - && self.alternate_headroom.is_finite() - && self.alternate_headroom > self.base_headroom - } - - /// The ISO 21496-1 APP2 payload of the gain map image, URN included. - pub fn to_iso(&self) -> Vec { - let mut p = ISO_URN.to_vec(); - p.extend_from_slice(&0u16.to_be_bytes()); // minimum_version: readers gate on this - p.extend_from_slice(&0u16.to_be_bytes()); // writer_version - let mut flags = 0u8; - if self.multichannel { - flags |= FLAG_MULTICHANNEL; - } - if self.use_base_colour_space { - flags |= FLAG_BASE_COLOUR_SPACE; - } - p.push(flags); - let unsigned = |p: &mut Vec, v: f32| { - let n = (v as f64 * DENOMINATOR as f64).round().clamp(0.0, u32::MAX as f64) as u32; - p.extend_from_slice(&n.to_be_bytes()); - p.extend_from_slice(&DENOMINATOR.to_be_bytes()); - }; - let signed = |p: &mut Vec, v: f32| { - let n = (v as f64 * DENOMINATOR as f64).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32; - p.extend_from_slice(&n.to_be_bytes()); - p.extend_from_slice(&DENOMINATOR.to_be_bytes()); - }; - unsigned(&mut p, self.base_headroom.max(0.0)); - unsigned(&mut p, self.alternate_headroom.max(0.0)); - for c in 0..self.channels() { - signed(&mut p, self.min[c]); - signed(&mut p, self.max[c]); - unsigned(&mut p, self.gamma[c]); - signed(&mut p, self.base_offset[c]); - signed(&mut p, self.alternate_offset[c]); - } - p - } - - /// Parse an ISO 21496-1 payload (the bytes after [`ISO_URN`]). `None` for the versions-only - /// marker a primary image carries, unknown versions, a base that is the HDR rendition, or - /// values no decoder could use. - pub fn from_iso(p: &[u8]) -> Option { - let mut r = Reader { b: p, at: 0 }; - let min_version = r.u16()?; - let _writer_version = r.u16()?; - if min_version != 0 { - return None; - } - let flags = r.u8()?; - if flags & FLAG_BACKWARD != 0 { - return None; - } - let multichannel = flags & FLAG_MULTICHANNEL != 0; - let common = flags & FLAG_COMMON_DENOMINATOR != 0; - let common_d = if common { r.u32()? } else { 0 }; - let unsigned = |r: &mut Reader| -> Option { - let n = r.u32()?; - let d = if common { common_d } else { r.u32()? }; - (d != 0).then(|| (n as f64 / d as f64) as f32) - }; - let signed = |r: &mut Reader| -> Option { - let n = r.u32()? as i32; - let d = if common { common_d } else { r.u32()? }; - (d != 0).then(|| (n as f64 / d as f64) as f32) - }; - let mut m = GainMapMeta { - multichannel, - use_base_colour_space: flags & FLAG_BASE_COLOUR_SPACE != 0, - base_headroom: unsigned(&mut r)?, - alternate_headroom: unsigned(&mut r)?, - ..GainMapMeta::default() - }; - for c in 0..m.channels() { - m.min[c] = signed(&mut r)?; - m.max[c] = signed(&mut r)?; - m.gamma[c] = unsigned(&mut r)?; - m.base_offset[c] = signed(&mut r)?; - m.alternate_offset[c] = signed(&mut r)?; - } - if !multichannel { - m.fill_from_first(); - } - m.is_valid().then_some(m) - } - - fn fill_from_first(&mut self) { - for a in [&mut self.min, &mut self.max, &mut self.gamma, &mut self.base_offset, &mut self.alternate_offset] { - a[1] = a[0]; - a[2] = a[0]; - } - } - - /// The gain parameters from Adobe `hdrgm` XMP (the gain map image's packet), for files - /// without ISO 21496-1 metadata (the first Ultra HDR files). Attributes or `rdf:Seq` lists. - pub fn from_hdrgm_xmp(xmp: &str) -> Option { - if !xmp.contains("hdrgm:") { - return None; - } - let base_rendition_hdr = xmp_values(xmp, "BaseRenditionIsHDR").is_some_and(|v| v.first().is_some_and(|s| s.eq_ignore_ascii_case("true"))); - if base_rendition_hdr { - return None; - } - let get = |name: &str, default: f32| -> Option<([f32; 3], bool)> { - let Some(v) = xmp_values(xmp, name) else { return Some(([default; 3], false)) }; - let f: Vec = v.iter().map(|s| s.trim().parse::().ok()).collect::>()?; - match f.as_slice() { - [a] => Some(([*a; 3], false)), - [a, b, c] => Some(([*a, *b, *c], true)), - _ => None, - } - }; - let (max, m1) = get("GainMapMax", f32::NAN)?; - if max.iter().any(|v| v.is_nan()) { - return None; // the one required parameter - } - let (min, m2) = get("GainMapMin", 0.0)?; - let (gamma, m3) = get("Gamma", 1.0)?; - let (base_offset, m4) = get("OffsetSDR", 1.0 / 64.0)?; - let (alternate_offset, m5) = get("OffsetHDR", 1.0 / 64.0)?; - let (cap_min, _) = get("HDRCapacityMin", 0.0)?; - let max_gain = max.iter().copied().fold(f32::MIN, f32::max); - let (cap_max, _) = get("HDRCapacityMax", max_gain)?; - let m = GainMapMeta { - multichannel: m1 || m2 || m3 || m4 || m5, - use_base_colour_space: true, - base_headroom: cap_min[0].max(0.0), - alternate_headroom: cap_max[0], - min, - max, - gamma, - base_offset, - alternate_offset, - }; - m.is_valid().then_some(m) - } - - /// The gain map image's XMP: the Adobe `hdrgm` parameters (read by Android and Chrome, which - /// ignore the ISO payload) and Apple's description of the same map (what iMessage keeps). - pub fn to_gain_map_xmp(&self) -> String { - let names = ["GainMapMin", "GainMapMax", "Gamma", "OffsetSDR", "OffsetHDR"]; - let values = [&self.min, &self.max, &self.gamma, &self.base_offset, &self.alternate_offset]; - let uniform = |v: &[f32; 3]| !self.multichannel || (v[0] == v[1] && v[1] == v[2]); - let mut s = String::from(XMP_OPEN); - s.push_str(r#"'); - // per-channel values are an rdf:Seq of three, not a comma list: readers parse each item - for (n, v) in names.iter().zip(values) { - if !uniform(v) { - s.push_str(&format!("")); - for x in v { - s.push_str(&format!("{}", num(*x))); - } - s.push_str(&format!("")); - } - } - s.push_str(""); - s.push_str(&self.apple_description()); - s.push_str(XMP_CLOSE); - s - } - - /// Apple's own description of the map (`apdi`, `HDRGainMap`, `HDRToneMap` namespaces). - fn apple_description(&self) -> String { - // 'L008' (8-bit luminance) or '444f'; the stored map must really have that many channels - let format = if self.multichannel { 0x3434_3466u32 } else { 0x4C30_3038 }; - let mut s = String::from( - r#""#, - ); - s.push_str("urn:com:apple:photo:2020:aux:hdrgainmap"); - s.push_str(&format!("{format}{format}")); - s.push_str("131072"); - // linear, not log2: the headroom multiplier itself - s.push_str(&format!("{}", num(self.alternate_headroom.exp2()))); - s.push_str(&format!("{}", num(self.alternate_headroom))); - s.push_str(""); - for c in 0..self.channels() { - s.push_str(&format!( - r#"{}{}{}{}{}"#, - num(self.min[c]), - num(self.max[c]), - num(self.gamma[c]), - num(self.base_offset[c]), - num(self.alternate_offset[c]) - )); - } - s.push_str(""); - s.push_str(&format!("{}", num(self.base_headroom))); - s.push_str("True1"); - s.push_str(""); - s - } -} - -const FLAG_MULTICHANNEL: u8 = 0x80; -const FLAG_BASE_COLOUR_SPACE: u8 = 0x40; -const FLAG_COMMON_DENOMINATOR: u8 = 0x08; -const FLAG_BACKWARD: u8 = 0x04; - -const XMP_OPEN: &str = ""; -const XMP_CLOSE: &str = ""; - -/// A short decimal (up to 6 significant digits, no exponent for ordinary values). -fn num(v: f32) -> String { - if !v.is_finite() { - return "0".into(); - } - let s = format!("{:.6}", v); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s == "-0" || s.is_empty() { "0".into() } else { s.to_string() } -} - -/// The values of `hdrgm:`: an attribute (`name="v"`) or an element holding an `rdf:Seq`. -fn xmp_values(xmp: &str, name: &str) -> Option> { - let attr = format!("hdrgm:{name}="); - if let Some(i) = xmp.find(&attr) { - let rest = xmp.get(i + attr.len()..)?; - let q = rest.chars().next()?; - if q == '"' || q == '\'' { - let body = rest.get(1..)?; - let end = body.find(q)?; - return Some(vec![body.get(..end)?.to_string()]); - } - } - let open = format!(""); - let close = format!(""); - let i = xmp.find(&open)?; - let body = xmp.get(i + open.len()..)?; - let body = body.get(..body.find(&close)?)?; - let mut out = Vec::new(); - let mut rest = body; - while let Some(a) = rest.find("") { - let after = rest.get(a + 8..)?; - let b = after.find("")?; - out.push(after.get(..b)?.to_string()); - rest = after.get(b..)?; - if out.len() > 3 { - return None; - } - } - if out.is_empty() { - // a plain element value - out.push(body.trim().to_string()); - } - Some(out) -} - -struct Reader<'a> { - b: &'a [u8], - at: usize, -} - -impl Reader<'_> { - fn take(&mut self) -> Option<[u8; N]> { - let s = self.b.get(self.at..self.at.checked_add(N)?)?; - self.at += N; - s.try_into().ok() - } - fn u8(&mut self) -> Option { - self.take::<1>().map(|a| a[0]) - } - fn u16(&mut self) -> Option { - self.take().map(u16::from_be_bytes) - } - fn u32(&mut self) -> Option { - self.take().map(u32::from_be_bytes) - } -} - -/// A gain map image: `channels` (1 or 3) interleaved 8-bit codes. -#[derive(Clone, Debug, PartialEq)] -pub struct GainImage { - pub width: usize, - pub height: usize, - pub channels: usize, - pub data: Vec, -} - -impl GainImage { - /// Bilinear code of channel `c` at gain map coordinates (`x`, `y`) (pixel centres at +0.5). - fn sample(&self, x: f32, y: f32, c: usize) -> f32 { - let (w, h) = (self.width, self.height); - let fx = (x - 0.5).clamp(0.0, (w - 1) as f32); - let fy = (y - 0.5).clamp(0.0, (h - 1) as f32); - let (x0, y0) = (fx as usize, fy as usize); - let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); - let (tx, ty) = (fx - x0 as f32, fy - y0 as f32); - let at = |x: usize, y: usize| self.data.get((y * w + x) * self.channels + c).copied().unwrap_or(0) as f32; - let a = at(x0, y0) + (at(x1, y0) - at(x0, y0)) * tx; - let b = at(x0, y1) + (at(x1, y1) - at(x0, y1)) * tx; - a + (b - a) * ty - } -} - -/// How [`compute`] builds the map. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct GainMapOptions { - /// Downscale factor of the map (1, 2 or 4). - pub scale: usize, - /// Three gains (R, G, B) instead of one luminance gain. Apple's readers want a single - /// channel, so this is off by default. - pub multichannel: bool, - pub gamma: f32, - /// Offsets added to SDR and HDR before the ratio (keep blacks finite and noise quiet). - pub offset: f32, -} - -impl Default for GainMapOptions { - fn default() -> Self { - GainMapOptions { scale: 2, multichannel: false, gamma: 1.0, offset: 1.0 / 64.0 } - } -} - -/// Measure the gain map that turns `sdr` into `hdr` (both `width × height` linear RGB in the same -/// primaries; `luma` = that space's luminance weights). -pub fn compute( - sdr: &[[f32; 3]], - hdr: &[[f32; 3]], - width: usize, - height: usize, - luma: [f32; 3], - o: &GainMapOptions, -) -> Result<(GainImage, GainMapMeta)> { - let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?; - if n == 0 || sdr.len() < n || hdr.len() < n { - return Err(Error::Encode("gain map: SDR and HDR renditions must match the image size".into())); - } - if !(matches!(o.scale, 1 | 2 | 4) && o.gamma > 0.0 && o.gamma.is_finite() && o.offset > 0.0 && o.offset.is_finite()) { - return Err(Error::Encode("gain map: scale must be 1, 2 or 4, gamma and offset positive".into())); - } - let s = o.scale; - let (gw, gh) = (width.div_ceil(s), height.div_ceil(s)); - let ch = if o.multichannel { 3 } else { 1 }; - let y = |p: &[f32; 3]| luma[0] * p[0] + luma[1] * p[1] + luma[2] * p[2]; - let ratio = |a: f32, b: f32| ((b.max(0.0) + o.offset) / (a.max(0.0) + o.offset)).log2(); - // block means of the log gains - let mut gains = vec![0f32; gw * gh * ch]; - let mut lo = [f32::MAX; 3]; - let mut hi = [f32::MIN; 3]; - for gy in 0..gh { - for gx in 0..gw { - let mut acc = [0f32; 3]; - let mut count = 0f32; - for yy in gy * s..((gy + 1) * s).min(height) { - for xx in gx * s..((gx + 1) * s).min(width) { - let i = yy * width + xx; - let (Some(a), Some(b)) = (sdr.get(i), hdr.get(i)) else { continue }; - if o.multichannel { - for c in 0..3 { - acc[c] += ratio(a[c], b[c]); - } - } else { - acc[0] += ratio(y(a), y(b)); - } - count += 1.0; - } - } - for c in 0..ch { - let g = if count > 0.0 { acc[c] / count } else { 0.0 }; - let g = if g.is_finite() { g } else { 0.0 }; - gains[(gy * gw + gx) * ch + c] = g; - lo[c] = lo[c].min(g); - hi[c] = hi[c].max(g); - } - } - } - let mut m = GainMapMeta { - multichannel: o.multichannel, - gamma: [o.gamma; 3], - base_offset: [o.offset; 3], - alternate_offset: [o.offset; 3], - ..GainMapMeta::default() - }; - for c in 0..ch { - // the range always includes 0 (no change) so an SDR-only area encodes exactly - m.min[c] = lo[c].min(0.0); - m.max[c] = hi[c].max(m.min[c] + 1e-4); - } - if !o.multichannel { - m.fill_from_first(); - } - m.base_headroom = 0.0; - m.alternate_headroom = m.max.iter().copied().fold(0.0f32, f32::max).max(1e-3); - let data = gains - .iter() - .enumerate() - .map(|(i, g)| { - let c = i % ch; - let norm = ((g - m.min[c]) / (m.max[c] - m.min[c])).clamp(0.0, 1.0); - (norm.powf(o.gamma) * 255.0).round() as u8 - }) - .collect(); - Ok((GainImage { width: gw, height: gh, channels: ch, data }, m)) -} - -/// Rebuild the HDR rendition in place: `base` (`width × height` linear RGB) is replaced by the -/// rendition at `weight` (0 = the base, 1 = the full alternate rendition; a display with headroom -/// `H` uses `(H − base_headroom) / (alternate_headroom − base_headroom)`, clamped). -pub fn apply(base: &mut [[f32; 3]], width: usize, height: usize, gain: &GainImage, m: &GainMapMeta, weight: f32) -> Result<()> { - let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?; - if base.len() < n - || gain.width == 0 - || gain.height == 0 - || !matches!(gain.channels, 1 | 3) - || gain.data.len() < gain.width * gain.height * gain.channels - { - return Err(Error::Encode("gain map: base and gain map sizes don't match".into())); - } - if !m.is_valid() { - return Err(Error::Encode("gain map: unusable metadata".into())); - } - let weight = if weight.is_finite() { weight.clamp(0.0, 1.0) } else { 1.0 }; - let (sx, sy) = (gain.width as f32 / width as f32, gain.height as f32 / height as f32); - let inv_gamma = m.gamma.map(|g| 1.0 / g); - for (i, p) in base.iter_mut().enumerate().take(n) { - let (x, y) = ((i % width) as f32 + 0.5, (i / width) as f32 + 0.5); - let (gx, gy) = (x * sx, y * sy); - let mut g = [0f32; 3]; - for (c, gc) in g.iter_mut().enumerate() { - let src = if gain.channels == 3 { c } else { 0 }; - let norm = (gain.sample(gx, gy, src) / 255.0).clamp(0.0, 1.0).powf(inv_gamma[c]); - *gc = m.min[c] + (m.max[c] - m.min[c]) * norm; - } - for c in 0..3 { - let v = (p[c] + m.base_offset[c]) * (g[c] * weight).exp2() - m.alternate_offset[c]; - p[c] = v.max(0.0); - } - } - Ok(()) -} - -/// The primary image's container XMP: `hdrgm:Version` (marks the file as a gain map image for -/// Adobe/Google readers) and the Container directory naming the gain map and its length. -fn primary_description(gain_len: usize) -> String { - format!( - concat!( - r#""#, - r#""#, - r#""#, - r#""#, - r#""# - ), - gain_len - ) -} - -/// `xmp` with `description` added as another `rdf:Description` (a fresh packet when there is -/// none, or when it has no `rdf:RDF` to add to). -fn merge_xmp(xmp: Option<&str>, description: &str) -> String { - if let Some(x) = xmp - && let Some(i) = x.rfind("") - && let (Some(a), Some(b)) = (x.get(..i), x.get(i..)) - { - return format!("{a}{description}{b}"); - } - format!("{XMP_OPEN}{description}{XMP_CLOSE}") -} - /// Offsets within the MPF payload (from "MPF\0"): the endian field, then the index IFD (3 tags). const MPF_ENTRIES_FROM_ENDIAN: usize = 8 + 2 + 3 * 12 + 4; @@ -598,11 +72,9 @@ pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, qualit let gain_segs = vec![(0xE1, xmp_segment(&m.to_gain_map_xmp())?), (0xE2, m.to_iso())]; let gain_jpeg = jpeg_par::encode(&gain.data, gain.width, gain.height, gain.channels, quality, ChromaSubsampling::S444, &gain_segs); - let xmp = merge_xmp(meta.xmp, &primary_description(gain_jpeg.len())); + let xmp = craft_gainmap::primary_xmp(meta.xmp, gain_jpeg.len()); let mut segs = jpeg_app_segments(&EncodeMeta { xmp: Some(&xmp), ..*meta })?; - let mut iso_marker = ISO_URN.to_vec(); - iso_marker.extend_from_slice(&[0, 0, 0, 0]); // versions only: "this image has a gain map" - segs.push((0xE2, iso_marker)); + segs.push((0xE2, craft_gainmap::primary_iso_marker())); segs.push((0xE2, mpf_placeholder())); let mut primary = jpeg_par::encode(data, w, h, base.channels as usize, quality, sub, &segs); @@ -672,77 +144,6 @@ pub fn is_gain_map_jpeg(bytes: &[u8]) -> bool { mod tests { use super::*; - fn meta3() -> GainMapMeta { - GainMapMeta { - multichannel: true, - use_base_colour_space: true, - base_headroom: 0.0, - alternate_headroom: 2.5, - min: [-0.25, -0.5, 0.0], - max: [2.5, 2.25, 2.0], - gamma: [1.0, 1.25, 0.75], - base_offset: [0.015625; 3], - alternate_offset: [0.015625, 0.03125, 0.015625], - } - } - - #[test] - fn iso_metadata_round_trips() { - for m in [GainMapMeta { alternate_headroom: 3.0, max: [3.0; 3], ..GainMapMeta::default() }, meta3()] { - let p = m.to_iso(); - assert!(p.starts_with(ISO_URN)); - let back = GainMapMeta::from_iso(&p[ISO_URN.len()..]).unwrap(); - for (a, b) in [(back.min, m.min), (back.max, m.max), (back.gamma, m.gamma), (back.alternate_offset, m.alternate_offset)] { - for c in 0..3 { - assert!((a[c] - b[c]).abs() < 1e-6, "{a:?} {b:?}"); - } - } - assert_eq!(back.multichannel, m.multichannel); - assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-6); - } - } - - #[test] - fn iso_common_denominator_and_rejections() { - // common-denominator form, single channel: d = 4, headrooms 0 and 2, min 0, max 2, gamma 1, offsets 0 - let mut p = vec![0, 0, 0, 0, FLAG_COMMON_DENOMINATOR]; - for v in [4u32, 0, 8, 0, 8, 4, 0, 0] { - p.extend_from_slice(&v.to_be_bytes()); - } - let m = GainMapMeta::from_iso(&p).unwrap(); - assert_eq!((m.alternate_headroom, m.max[2], m.gamma[1]), (2.0, 2.0, 1.0)); - // versions only (a primary image's marker), unknown version, truncated, backward - assert!(GainMapMeta::from_iso(&[0, 0, 0, 0]).is_none()); - assert!(GainMapMeta::from_iso(&[0, 1, 0, 0, 0]).is_none()); - assert!(GainMapMeta::from_iso(&p[..p.len() - 1]).is_none()); - let mut back = p.clone(); - back[4] |= FLAG_BACKWARD; - assert!(GainMapMeta::from_iso(&back).is_none()); - // a zero denominator is rejected, not divided by - let mut z = p.clone(); - z[5..9].copy_from_slice(&0u32.to_be_bytes()); - assert!(GainMapMeta::from_iso(&z).is_none()); - } - - #[test] - fn hdrgm_xmp_round_trips_including_per_channel_sequences() { - for m in [GainMapMeta { alternate_headroom: 2.0, max: [2.0; 3], ..GainMapMeta::default() }, meta3()] { - let x = m.to_gain_map_xmp(); - assert!(x.contains("apdi:AuxiliaryImageType")); - if m.multichannel { - assert!(x.contains("2.5"), "{x}"); - } - let back = GainMapMeta::from_hdrgm_xmp(&x).unwrap(); - assert_eq!(back.multichannel, m.multichannel); - for c in 0..3 { - assert!((back.max[c] - m.max[c]).abs() < 1e-5 && (back.gamma[c] - m.gamma[c]).abs() < 1e-5); - } - assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-5); - } - assert!(GainMapMeta::from_hdrgm_xmp("").is_none(), "no GainMapMax"); - assert!(GainMapMeta::from_hdrgm_xmp("hdrgm:GainMapMax=\"nope\"").is_none()); - } - fn renditions(w: usize, h: usize) -> (Vec<[f32; 3]>, Vec<[f32; 3]>) { // a ramp: SDR rolls off at 1, HDR keeps going to 6 let hdr: Vec<[f32; 3]> = (0..w * h) @@ -765,31 +166,6 @@ mod tests { (sdr, hdr) } - #[test] - fn compute_then_apply_recovers_the_hdr_rendition() { - let (w, h) = (64, 8); - let (sdr, hdr) = renditions(w, h); - for multichannel in [false, true] { - let o = GainMapOptions { scale: 1, multichannel, ..GainMapOptions::default() }; - let (g, m) = compute(&sdr, &hdr, w, h, [0.2126, 0.7152, 0.0722], &o).unwrap(); - assert!(m.is_valid() && m.alternate_headroom > 1.0); - let mut out = sdr.clone(); - apply(&mut out, w, h, &g, &m, 1.0).unwrap(); - for (a, b) in out.iter().zip(&hdr) { - for c in 0..3 { - // 8-bit codes over the gain range: within ~2 % in linear light - assert!((a[c] - b[c]).abs() <= 0.03 * b[c] + 0.01, "{multichannel}: {a:?} vs {b:?}"); - } - } - // weight 0 is the base - let mut base = sdr.clone(); - apply(&mut base, w, h, &g, &m, 0.0).unwrap(); - for (a, b) in base.iter().zip(&sdr) { - assert!((a[0] - b[0]).abs() < 1e-5); - } - } - } - #[test] fn a_gain_map_wider_than_a_jpeg_allows_is_refused() { let base = [0u8; 3]; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index f72a9b235a..7f82adf2e9 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -27,7 +27,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/ | DNG (from raw) | ✅ | ✅ incl. lossy, embedded original | ✅ | ✅ uncompressed, LJ92, Deflate or lossy (JPEG tiles, optional long edge); ⬜ embedded original | `crates/raw/src/dngwrite.rs` | | Render to DNG (15.5) | — | ✅ | — | 🟡 export format "Rendered DNG" (linear float DNG, edit baked in); not yet added to the catalog | `crates/raw/src/dngwrite.rs` (`write_rendered_dng`) | | Original + sidecar | — | ✅ | — | ✅ | | -| HDR gain map JPEG (ISO 21496-1) | ✅ | ✅ | ✅ (gain map read) | ✅ | `crates/codecs/src/gainmap.rs` | +| HDR gain map JPEG (ISO 21496-1) | ✅ | ✅ | ✅ (gain map read) | ✅ | `crates/codecs/src/gainmap.rs` (JPEG layout), `craft-gainmap` (metadata, compute, apply) | | PQ / HLG HDR | ✅ | ✅ AVIF, JXL, TIFF | — | 🟡 PQ AVIF, PQ JPEG XL, float TIFF; no HLG | | | Contact sheet / print PDF | — | ✅ (Print module: PDF / JPEG / printer) | — | 🟡 paginated contact-sheet PDF (A4 / Letter, 150 dpi, sRGB) | `crates/engine/src/contact_sheet.rs` | | Video (MP4, MOV, AVCHD…) | ✅ playback, trim, edit | ✅ export | 🟡 catalogued (kind, duration) | ⬜ | see video gap | From f30bd05cfed7262d5b0b58ae618e1d12e682ebf2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 01:05:29 +0000 Subject: [PATCH 09/23] Read the PSD header and image resources with craft-psd lightcraft-meta's EXIF/XMP scan and lightcraft-codecs' PSD probe and decoder take the header, colour mode data and image resources from craft_psd::Head (storytold/craft-libs#885). The merged-image decoder and the flat writer stay. --- Cargo.lock | 32 +++++++++ Cargo.toml | 2 + crates/codecs/Cargo.toml | 1 + crates/codecs/src/psd.rs | 145 ++++++++++++++++++--------------------- crates/meta/Cargo.toml | 1 + crates/meta/src/psd.rs | 63 ++--------------- 6 files changed, 108 insertions(+), 136 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dbaac1f99e..47a44f1def 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1239,6 +1239,16 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=119415f46f601e20b9bc6b1b4d6979ceda86d88e#119415f46f601e20b9bc6b1b4d6979ceda86d88e" +dependencies = [ + "encoding_rs", + "flate2", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1796,6 +1806,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -3687,6 +3711,7 @@ dependencies = [ "bytemuck", "craft-gainmap", "craft-heif", + "craft-psd", "dhat", "image", "image-webp", @@ -3930,6 +3955,7 @@ version = "0.21.0" dependencies = [ "chrono", "craft-heif", + "craft-psd", "craft-tiff", "lightcraft-geom", "proptest", @@ -4309,6 +4335,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" diff --git a/Cargo.toml b/Cargo.toml index 41ba05620b..301ca570e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,8 @@ craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0. craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "119415f46f601e20b9bc6b1b4d6979ceda86d88e" } +# PSD/PSB: the header, colour mode data and image resources (craft-libs#885). +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "119415f46f601e20b9bc6b1b4d6979ceda86d88e" } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false } diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 019009d7c1..15b7fb0557 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -13,6 +13,7 @@ lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } craft-gainmap = { workspace = true } +craft-psd = { workspace = true } craft-heif = { workspace = true, optional = true } serde = { workspace = true } bytemuck = { workspace = true } diff --git a/crates/codecs/src/psd.rs b/crates/codecs/src/psd.rs index 7cccec0f8f..f0422edc13 100644 --- a/crates/codecs/src/psd.rs +++ b/crates/codecs/src/psd.rs @@ -40,36 +40,46 @@ impl<'a> Rd<'a> { } } +/// The header, colour mode data and image resources (`craft-psd`), with a reader at the layer and mask section. +struct Start<'a> { + psb: bool, + channels: usize, + width: usize, + height: usize, + depth: u16, + mode: u16, + head: craft_psd::Head, + r: Rd<'a>, +} + +fn start<'a>(bytes: &'a [u8], opts: &DecodeOptions) -> Result> { + // the size limit first, from the header's fixed fields, so an oversized file is `TooLarge` as for other formats + if let (Some(&[h0, h1, h2, h3]), Some(&[w0, w1, w2, w3])) = (bytes.get(14..18), bytes.get(18..22)) { + check_size(F, u64::from(u32::from_be_bytes([w0, w1, w2, w3])), u64::from(u32::from_be_bytes([h0, h1, h2, h3])), opts)?; + } + let head = craft_psd::Head::from_bytes(bytes).map_err(|e| match e { + craft_psd::PsdError::UnexpectedEof { .. } => err("truncated"), + e => err(&e.to_string()), + })?; + let h = &head.header; + check_size(F, u64::from(h.width), u64::from(h.height), opts)?; + let p = usize::try_from(head.layer_section_offset).map_err(|_| err("truncated"))?; + Ok(Start { + psb: h.version.is_psb(), + channels: usize::from(h.channels), + width: h.width as usize, + height: h.height as usize, + depth: h.depth, + mode: h.color_mode.as_u16(), + r: Rd { b: bytes, p }, + head, + }) +} + pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { - let mut r = Rd { b: bytes, p: 0 }; - if r.take(4)? != b"8BPS" { - return Err(err("bad signature")); - } - let version = r.u16()?; - let psb = match version { - 1 => false, - 2 => true, - _ => return Err(err("bad version")), - }; - r.take(6)?; - let channels = r.u16()? as usize; - let height = r.u32()? as usize; - let width = r.u32()? as usize; - let depth = r.u16()?; - let mode = r.u16()?; - check_size(F, width as u64, height as u64, opts)?; - if channels == 0 || channels > 56 { - return Err(err("bad channel count")); - } - - // Colour mode data (palette for indexed). - let cm_len = r.u32()? as usize; - let color_mode_data = r.take(cm_len)?; - - // Image resources. - let res_len = r.u32()? as usize; - let res = r.take(res_len)?; - let (icc, exif, xmp) = resources(res); + let Start { psb, channels, width, height, depth, mode, head, mut r } = start(bytes, opts)?; + let color_mode_data = head.color_mode_data.as_slice(); + let (icc, exif, xmp) = resources(&head); // Layer and mask information: only the layer count sign matters (merged transparency). let lm_len = if psb { r.u64()? } else { u64::from(r.u32()?) }; @@ -342,29 +352,9 @@ fn packbits(src: &[u8], out: &mut Vec) { /// depth, colour mode or compression, or merged image data that runs past the end of the file /// (truncated). The run-length data itself is not unpacked. pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { - let mut r = Rd { b: bytes, p: 0 }; - if r.take(4)? != b"8BPS" { - return Err(err("bad signature")); - } - let psb = match r.u16()? { - 1 => false, - 2 => true, - _ => return Err(err("bad version")), - }; - r.take(6)?; - let channels = r.u16()? as usize; - let height = r.u32()? as usize; - let width = r.u32()? as usize; - let depth = r.u16()?; - let mode = r.u16()?; - check_size(F, width as u64, height as u64, &DecodeOptions::default())?; - if channels == 0 || channels > 56 { - return Err(err("bad channel count")); - } - let cm_len = r.u32()? as usize; - let color_mode_data = r.take(cm_len)?; - let res_len = r.u32()? as usize; - let (_, exif, _) = resources(r.take(res_len)?); + let Start { psb, channels, width, height, depth, mode, head, mut r } = start(bytes, &DecodeOptions::default())?; + let color_mode_data = head.color_mode_data.as_slice(); + let (_, exif, _) = resources(&head); let lm_len = if psb { r.u64()? as usize } else { r.u32()? as usize }; r.take(lm_len)?; let compression = r.u16()?; @@ -444,28 +434,12 @@ fn unpackbits(mut src: &[u8], row: &mut [u8]) -> Result<()> { Ok(()) } -fn resources(mut b: &[u8]) -> (Option>, Option>, Option) { - let (mut icc, mut exif, mut xmp) = (None, None, None); - while b.len() >= 12 && &b[0..4] == b"8BIM" { - let id = u16::from_be_bytes([b[4], b[5]]); - let name_len = b[6] as usize; - let name_total = (1 + name_len + 1) & !1; - let p = 6 + name_total; - if p + 4 > b.len() { - break; - } - let size = u32::from_be_bytes([b[p], b[p + 1], b[p + 2], b[p + 3]]) as usize; - let start = p + 4; - let Some(data) = start.checked_add(size).and_then(|end| b.get(start..end)) else { break }; - match id { - 1039 => icc = Some(data.to_vec()), - 1058 => exif = Some(if data.starts_with(b"Exif\0\0") { data[6..].to_vec() } else { data.to_vec() }), - 1060 => xmp = Some(String::from_utf8_lossy(data).trim_end_matches('\0').to_string()), - _ => {} - } - let next = start + ((size + 1) & !1); - b = b.get(next..).unwrap_or(&[]); - } +/// ICC (1039), EXIF (1058, without its optional `Exif\0\0` prefix) and XMP (1060) resources; the last of each id. +fn resources(head: &craft_psd::Head) -> (Option>, Option>, Option) { + let last = |id: u16| head.resources.iter().rev().find(|r| r.id == id).map(|r| r.data.as_slice()); + let icc = last(1039).map(<[u8]>::to_vec); + let exif = last(1058).map(|d| d.strip_prefix(b"Exif\0\0").unwrap_or(d).to_vec()); + let xmp = last(1060).map(|d| String::from_utf8_lossy(d).trim_end_matches('\0').to_string()); (icc, exif, xmp) } @@ -514,8 +488,8 @@ mod tests { #[test] fn huge_rle_with_truncated_count_table_is_rejected_before_allocating() { - // 1 × 2^30 px, 56 channels: the row table alone would be 56 Gi entries; the file has 4 bytes. - let mut b = header(56, 1, 1 << 30, 32, 3, 1); + // 1 × 300 000 px, 56 channels: the row table alone would be 16.8 M entries; the file has 4 bytes. + let mut b = header(56, 1, 300_000, 32, 3, 1); b.extend_from_slice(&[0, 0, 0, 0]); let e = decode(&b, &DecodeOptions::default()).unwrap_err(); assert!(matches!(e, Error::Malformed(_, ref m) if m == "truncated"), "{e:?}"); @@ -523,18 +497,29 @@ mod tests { #[test] fn huge_rle_of_empty_rows_is_rejected_before_allocating() { - // 2^30 × 1 px RGB at 32 bits: every row count is 0, which used to zero-pad 3 × 4 GiB. - let mut b = header(3, 1 << 30, 1, 32, 3, 1); + // 300 000 × 1 px RGB at 32 bits: every row count is 0, which used to zero-pad 3 × 1.2 MB. + let mut b = header(3, 300_000, 1, 32, 3, 1); b.extend_from_slice(&[0; 6]); let e = decode(&b, &DecodeOptions::default()).unwrap_err(); assert!(matches!(e, Error::Malformed(_, ref m) if m.contains("too short")), "{e:?}"); - // 1 Gpx RGB 8-bit whose (plausible) row counts claim more data than the file holds. - let mut b = header(3, 1 << 20, 1 << 10, 8, 3, 1); + // 0.27 Gpx RGB 8-bit whose (plausible) row counts claim more data than the file holds. + let mut b = header(3, 1 << 18, 1 << 10, 8, 3, 1); b.extend_from_slice(&[0xFF; 3 * 1024 * 2]); let e = decode(&b, &DecodeOptions::default()).unwrap_err(); assert!(matches!(e, Error::Malformed(_, ref m) if m == "truncated"), "{e:?}"); } + #[test] + fn a_damaged_resource_section_is_malformed() { + // a resource section of 4 bytes that is not an `8BIM` record + let mut b = header(3, 1, 1, 8, 3, 0); + b[30..34].copy_from_slice(&4u32.to_be_bytes()); + b.splice(34..34, *b"JUNK"); + let e = decode(&b, &DecodeOptions::default()).unwrap_err(); + assert!(matches!(e, Error::Malformed(_, ref m) if m.contains("signature")), "{e:?}"); + assert!(super::header(&b).is_err()); + } + #[test] fn rle_repeat_run_past_row_width_is_an_error() { // 4 × 1 gray 8-bit; the single row is a 128-byte repeat run. diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index 1b146c99da..e813d3a2a8 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-tiff = { workspace = true } +craft-psd = { workspace = true } lightcraft-geom = { workspace = true } serde = { workspace = true } quick-xml = { workspace = true } diff --git a/crates/meta/src/psd.rs b/crates/meta/src/psd.rs index ebdbdaf723..8fbe448d55 100644 --- a/crates/meta/src/psd.rs +++ b/crates/meta/src/psd.rs @@ -2,73 +2,24 @@ use crate::container::Embedded; -struct Reader<'a> { - bytes: &'a [u8], - offset: usize, -} - -impl<'a> Reader<'a> { - fn take(&mut self, length: usize) -> Option<&'a [u8]> { - let end = self.offset.checked_add(length)?; - let bytes = self.bytes.get(self.offset..end)?; - self.offset = end; - Some(bytes) - } - - fn u16(&mut self) -> Option { - let bytes = self.take(2)?; - Some(u16::from_be_bytes([*bytes.first()?, *bytes.get(1)?])) - } - - fn u32(&mut self) -> Option { - let bytes = self.take(4)?; - Some(u32::from_be_bytes([*bytes.first()?, *bytes.get(1)?, *bytes.get(2)?, *bytes.get(3)?])) - } -} - pub(crate) fn embedded(bytes: &[u8]) -> Embedded { parse(bytes).unwrap_or_default() } +/// The EXIF (1058) and XMP (1060) resources of the head `craft-psd` reads (header, colour mode data, image +/// resources). `None` for a head that does not parse, a second EXIF or XMP resource, or XMP that is not UTF-8. pub(crate) fn parse(bytes: &[u8]) -> Option { - let mut reader = Reader { bytes, offset: 0 }; - if reader.take(4)? != b"8BPS" || !matches!(reader.u16()?, 1 | 2) { - return None; - } - // The fixed header after the version is reserved bytes, channels, dimensions, depth and colour mode. - reader.take(6 + 2 + 4 + 4 + 2 + 2)?; - let colour_mode_length = usize::try_from(reader.u32()?).ok()?; - reader.take(colour_mode_length)?; - let resource_length = usize::try_from(reader.u32()?).ok()?; - let resources = reader.take(resource_length)?; - parse_resources(resources) -} - -fn parse_resources(bytes: &[u8]) -> Option { - let mut reader = Reader { bytes, offset: 0 }; + let head = craft_psd::Head::from_bytes(bytes).ok()?; let (mut exif, mut xmp) = (None, None); - while reader.offset < bytes.len() { - if reader.take(4)? != b"8BIM" { - return None; - } - let id = reader.u16()?; - let name_length = usize::from(*reader.take(1)?.first()?); - let pascal_length = 1usize.checked_add(name_length)?.checked_add(1)? & !1; - reader.take(pascal_length.checked_sub(1)?)?; - let data_length = usize::try_from(reader.u32()?).ok()?; - let data = reader.take(data_length)?; - if !data_length.is_multiple_of(2) { - reader.take(1)?; - } - match id { + for r in &head.resources { + match r.id { 1058 if exif.is_some() => return None, - 1058 => exif = Some(data), + 1058 => exif = Some(r.data.as_slice()), 1060 if xmp.is_some() => return None, - 1060 => xmp = Some(std::str::from_utf8(data).ok()?), + 1060 => xmp = Some(std::str::from_utf8(&r.data).ok()?), _ => {} } } - Some(Embedded { exif: exif.map(crate::strip_exif_header).map(<[u8]>::to_vec), xmp: xmp.map(|text| text.trim_end_matches('\0').to_string()), From 6aff3fb525144189de8bf96b5c75e507f3a0233a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 01:05:36 +0000 Subject: [PATCH 10/23] WIP: lensdb on craft-xml (not built) --- crates/lensdb/Cargo.toml | 2 +- crates/lensdb/src/lib.rs | 42 ++++----- crates/lensdb/src/tests.rs | 3 +- crates/lensdb/src/xml.rs | 180 +++++++------------------------------ 4 files changed, 55 insertions(+), 172 deletions(-) diff --git a/crates/lensdb/Cargo.toml b/crates/lensdb/Cargo.toml index 0896c2dcc4..f9f986cd26 100644 --- a/crates/lensdb/Cargo.toml +++ b/crates/lensdb/Cargo.toml @@ -11,4 +11,4 @@ workspace = true [dependencies] lightcraft-develop = { workspace = true } lightcraft-geom = { workspace = true } -quick-xml = { workspace = true } +craft-xml = { workspace = true } diff --git a/crates/lensdb/src/lib.rs b/crates/lensdb/src/lib.rs index d03d950407..dfdd769d7b 100644 --- a/crates/lensdb/src/lib.rs +++ b/crates/lensdb/src/lib.rs @@ -148,10 +148,12 @@ impl LensDb { /// Parse one lensfun-format XML document. pub fn parse(xml: &str) -> Result { let root = xml::parse(xml)?; - let Some(top) = root.kid("lensdatabase") else { return Err(Error::Xml("no element".into())) }; - let cameras = top.kids("camera").filter_map(camera).collect(); + if root.name != "lensdatabase" { + return Err(Error::Xml("no element".into())); + } + let cameras = root.children("camera").filter_map(camera).collect(); let mut budget = MAX_PROFILE_COPY_BYTES; - let lenses = top.kids("lens").flat_map(|n| lens(n, &mut budget)).collect(); + let lenses = root.children("lens").flat_map(|n| lens(n, &mut budget)).collect(); Ok(LensDb { cameras, lenses }) } @@ -384,10 +386,10 @@ fn is_teleconverter_marker(t: &str) -> bool { fn camera(n: &xml::Node) -> Option { Some(Camera { - maker: n.kid_text("maker")?.to_string(), - model: n.kid_text("model")?.to_string(), - mount: n.kid_text("mount").unwrap_or_default().to_string(), - crop_factor: crop_of(n.kid_text("cropfactor")), + maker: xml::kid_text(n, "maker")?, + model: xml::kid_text(n, "model")?, + mount: xml::kid_text(n, "mount").unwrap_or_default(), + crop_factor: crop_of(xml::kid_text(n, "cropfactor").as_deref()), }) } @@ -411,15 +413,15 @@ fn positive(v: Option) -> Option { /// One `` element → one profile per `` (newer files give each its own crop factor and aspect). fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec { - let Some(maker) = n.kid_text("maker") else { return Vec::new() }; - let models: Vec = n.kids("model").map(|m| m.text.trim().to_string()).filter(|m| !m.is_empty()).collect(); + let Some(maker) = xml::kid_text(n, "maker") else { return Vec::new() }; + let models: Vec = n.children("model").map(|m| m.text().trim().to_string()).filter(|m| !m.is_empty()).collect(); if models.is_empty() { return Vec::new(); } - let crop = crop_of(n.kid_text("cropfactor")); - let aspect = aspect_of(n.kid_text("aspect-ratio")).unwrap_or(1.5); - let rectilinear = n.kid_text("type").is_none_or(|t| t.eq_ignore_ascii_case("rectilinear")); - let mounts = n.kids("mount").map(|m| m.text.trim().to_string()).filter(|m| !m.is_empty()).collect::>(); + let crop = crop_of(xml::kid_text(n, "cropfactor").as_deref()); + let aspect = aspect_of(xml::kid_text(n, "aspect-ratio").as_deref()).unwrap_or(1.5); + let rectilinear = xml::kid_text(n, "type").is_none_or(|t| t.eq_ignore_ascii_case("rectilinear")); + let mounts = n.children("mount").map(|m| m.text().trim().to_string()).filter(|m| !m.is_empty()).collect::>(); // every kept calibration owns a copy of the lens's names, charged to the document's shared copy budget (the // strings' own allocations count, not only their bytes): when it can't cover another copy, the rest are left out let meta_bytes = std::mem::size_of::() @@ -427,7 +429,7 @@ fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec { + maker.len() + models.iter().chain(&mounts).map(|m| m.len() + NAME_ALLOCATION).sum::(); let mut out = Vec::new(); - for cal in n.kids("calibration") { + for cal in n.children("calibration") { if *copy_budget < meta_bytes { break; } @@ -446,23 +448,23 @@ fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec { tca: Vec::new(), vignetting: Vec::new(), }; - for c in &cal.children { - let Some(focal) = positive(c.num("focal")) else { continue }; - let k = |name: &str| c.num(name).unwrap_or(0.0); + for c in cal.elements() { + let Some(focal) = positive(xml::num(c, "focal")) else { continue }; + let k = |name: &str| xml::num(c, name).unwrap_or(0.0); match (c.name.as_str(), c.attr("model")) { ("distortion", Some("poly3")) => p.distortion.push((focal, Distortion::Poly3 { k1: k("k1") })), ("distortion", Some("poly5")) => p.distortion.push((focal, Distortion::Poly5 { k1: k("k1"), k2: k("k2") })), ("distortion", Some("ptlens")) => p.distortion.push((focal, Distortion::PtLens { a: k("a"), b: k("b"), c: k("c") })), ("tca", Some("linear")) => { - let one = |name: &str| c.num(name).unwrap_or(1.0); + let one = |name: &str| xml::num(c, name).unwrap_or(1.0); p.tca.push((focal, Tca::Linear { kr: one("kr"), kb: one("kb") })); } ("tca", Some("poly3")) => { - let one = |name: &str| c.num(name).unwrap_or(1.0); + let one = |name: &str| xml::num(c, name).unwrap_or(1.0); p.tca.push((focal, Tca::Poly3 { vr: one("vr"), vb: one("vb"), cr: k("cr"), cb: k("cb"), br: k("br"), bb: k("bb") })); } ("vignetting", Some("pa")) => { - let (Some(aperture), distance) = (positive(c.num("aperture")), positive(c.num("distance")).unwrap_or(1000.0)) else { + let (Some(aperture), distance) = (positive(xml::num(c, "aperture")), positive(xml::num(c, "distance")).unwrap_or(1000.0)) else { continue; }; let model = Vignetting { k1: k("k1"), k2: k("k2"), k3: k("k3") }; diff --git a/crates/lensdb/src/tests.rs b/crates/lensdb/src/tests.rs index 2fe7d9f06a..2e32f955ec 100644 --- a/crates/lensdb/src/tests.rs +++ b/crates/lensdb/src/tests.rs @@ -94,7 +94,8 @@ fn rejects_mismatched_xml_closing_tags() { #[test] fn malformed_documents_are_errors_not_panics() { assert!(LensDb::parse("").is_err()); - assert!(LensDb::parse("").is_ok_and(|d| d.lenses.is_empty())); + // a truncated document is an error, not an empty database + assert!(matches!(LensDb::parse(""), Err(Error::Xml(_)))); assert!(LensDb::parse("").is_err()); let deep = "".repeat(100); assert_eq!(LensDb::parse(&deep), Err(Error::TooLarge)); diff --git a/crates/lensdb/src/xml.rs b/crates/lensdb/src/xml.rs index b3a1b520bc..4ba98f451b 100644 --- a/crates/lensdb/src/xml.rs +++ b/crates/lensdb/src/xml.rs @@ -1,147 +1,36 @@ -//! A small, bounded XML tree reader for lensfun-format database files. +//! Reading lensfun-format database files with `craft-xml`, within this crate's limits. -use quick_xml::events::Event; +pub(crate) use craft_xml::El as Node; use crate::Error; -const MAX_NODES: usize = 500_000; +/// Most nodes (elements and their text) one document may hold. +const MAX_NODES: usize = 1_000_000; +/// Deepest element nesting (lensfun files nest four deep). const MAX_DEPTH: usize = 32; -#[derive(Debug, Default)] -pub(crate) struct Node { - pub name: String, - pub attrs: Vec<(String, String)>, - pub text: String, - pub children: Vec, -} - -impl Node { - pub fn attr(&self, k: &str) -> Option<&str> { - self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) - } - pub fn num(&self, k: &str) -> Option { - self.attr(k).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) - } - pub fn kids<'a>(&'a self, name: &'a str) -> impl Iterator + 'a { - self.children.iter().filter(move |c| c.name == name) - } - pub fn kid(&self, name: &str) -> Option<&Node> { - self.children.iter().find(|c| c.name == name) - } - pub fn kid_text(&self, name: &str) -> Option<&str> { - self.kid(name).map(|n| n.text.trim()).filter(|t| !t.is_empty()) - } -} - -fn entity(name: &str) -> Option { - Some(match name { - "amp" => '&', - "lt" => '<', - "gt" => '>', - "quot" => '"', - "apos" => '\'', - _ => { - let n = name.strip_prefix('#')?; - let v = match n.strip_prefix('x') { - Some(h) if h.bytes().all(|b| b.is_ascii_hexdigit()) => u32::from_str_radix(h, 16).ok()?, - Some(_) => return None, - None if n.bytes().all(|b| b.is_ascii_digit()) => n.parse().ok()?, - None => return None, - }; - char::from_u32(v)? - } - }) -} - -/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first -/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as -/// `a` are found and each run of name bytes is read once, not once per `&`. -fn entity_end(rest: &str) -> Option { - let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count(); - (rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1) -} - -fn unescape(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut rest = s; - while let Some(i) = rest.find('&') { - out.push_str(rest.get(..i).unwrap_or_default()); - let tail = rest.get(i..).unwrap_or_default(); - match entity_end(tail).and_then(|j| entity(tail.get(1..j)?).map(|c| (c, j))) { - Some((c, j)) => { - out.push(c); - rest = tail.get(j + 1..).unwrap_or_default(); - } - None => { - out.push('&'); - rest = tail.get(1..).unwrap_or_default(); - } - } - } - out.push_str(rest); - out -} - +/// The document's root element. Malformed markup is an error (strict); an undefined entity is kept as the text +/// `&name;`. pub(crate) fn parse(s: &str) -> Result { - let mut reader = quick_xml::Reader::from_str(s); - let mut stack = vec![Node { name: "#root".into(), ..Default::default() }]; - let mut count = 0usize; - loop { - let ev = reader.read_event().map_err(|e| Error::Xml(e.to_string()))?; - match ev { - Event::Start(ref e) | Event::Empty(ref e) => { - count += 1; - if count > MAX_NODES || stack.len() > MAX_DEPTH { - return Err(Error::TooLarge); - } - let attrs = e - .attributes() - .with_checks(false) - .flatten() - .map(|a| (String::from_utf8_lossy(a.key.as_ref()).into_owned(), unescape(&String::from_utf8_lossy(&a.value)))) - .collect(); - let node = Node { name: String::from_utf8_lossy(e.name().as_ref()).into_owned(), attrs, ..Default::default() }; - if matches!(ev, Event::Empty(_)) { - if let Some(p) = stack.last_mut() { - p.children.push(node); - } - } else { - stack.push(node); - } - } - Event::End(_) => close(&mut stack), - Event::Text(t) => { - if let Some(top) = stack.last_mut() { - top.text.push_str(&t.decode().map_err(|e| Error::Xml(e.to_string()))?); - } - } - Event::CData(t) => { - if let Some(top) = stack.last_mut() { - top.text.push_str(&String::from_utf8_lossy(&t)); - } - } - Event::GeneralRef(r) => { - if let (Some(top), Some(c)) = (stack.last_mut(), entity(&String::from_utf8_lossy(&r))) { - top.text.push(c); - } - } - Event::Eof => break, - _ => {} - } + let limits = craft_xml::Limits { max_depth: MAX_DEPTH, max_nodes: MAX_NODES, ..craft_xml::Limits::DEFAULT }; + let options = craft_xml::Options { + strict: true, + unknown_entity: craft_xml::UnknownEntity::Literal, + drop_blank_text: true, + ..craft_xml::Options::default() } - while stack.len() > 1 { - close(&mut stack); - } - stack.pop().ok_or(Error::Xml("empty document".into())) + .with_limits(limits); + options.parse(s.as_bytes()).map_err(|e| if e.is_limit() { Error::TooLarge } else { Error::Xml(e.to_string()) }) } -fn close(stack: &mut Vec) { - if stack.len() > 1 - && let Some(n) = stack.pop() - && let Some(p) = stack.last_mut() - { - p.children.push(n); - } +/// A finite number in attribute `k`. +pub(crate) fn num(n: &Node, k: &str) -> Option { + n.attr(k).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) +} + +/// The trimmed text of the first child `name`, when not empty. +pub(crate) fn kid_text(n: &Node, name: &str) -> Option { + n.child(name).map(|c| c.text().trim().to_string()).filter(|t| !t.is_empty()) } #[cfg(test)] @@ -149,24 +38,15 @@ mod tests { use super::*; #[test] - fn many_ampersands_before_one_semicolon_are_read_once() { - // 200 000 `&` then a `;`: each `&` once searched the whole rest for the `;` - let hostile = format!("{};&", "&".repeat(200_000)); - assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000))); - assert_eq!(unescape("<a> 􏿿 &unknownreference;"), " \u{10FFFF} &unknownreference;"); + fn references_and_padding_decode_and_unknown_entities_stay() { + let root = parse("A &unknownreference;").unwrap(); + assert_eq!(root.attr("maker"), Some("Canon &")); + assert_eq!(root.text(), "A &unknownreference;"); } #[test] - fn zero_padded_numeric_references_decode() { - assert_eq!(unescape("Canon A A"), "Canon A A"); - assert_eq!(unescape("&abc&#xyz;&;"), "&abc&#xyz;&;"); - } - - #[test] - fn entity_rejects_signed_numeric_references() { - assert_eq!(entity("#+65"), None); - assert_eq!(entity("#x+41"), None); - assert_eq!(entity("#65"), Some('A')); - assert_eq!(entity("#x41"), Some('A')); + fn limits_are_too_large() { + assert!(matches!(parse(&"".repeat(MAX_DEPTH + 1)), Err(Error::TooLarge))); + assert!(matches!(parse(&format!("{}", "".repeat(MAX_NODES))), Err(Error::TooLarge))); } } From c24cf70d4ba0fa862dd929f04cd9220bed974c73 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 01:05:37 +0000 Subject: [PATCH 11/23] WIP: raw decoding through craft-raw (not compiled) --- Cargo.toml | 8 +- crates/engine/src/files/preview.rs | 2 +- crates/raw/Cargo.toml | 8 +- crates/raw/src/binned.rs | 2 +- crates/raw/src/convert.rs | 210 ++++ crates/raw/src/dcp.rs | 80 +- crates/raw/src/dng.rs | 551 ----------- crates/raw/src/gaintable.rs | 138 +-- crates/raw/src/hotpixel.rs | 2 +- crates/raw/src/jxl.rs | 574 ----------- crates/raw/src/lib.rs | 510 +--------- crates/raw/src/ljpeg.rs | 1007 ------------------- crates/raw/src/ljpeg/tests.rs | 311 ------ crates/raw/src/ljpeg_fixtures.rs | 70 ++ crates/raw/src/llvc.rs | 4 +- crates/raw/src/opcodes.rs | 510 +--------- crates/raw/src/opcodes/tests.rs | 4 +- crates/raw/src/preview.rs | 4 +- crates/raw/src/preview/tests.rs | 2 +- crates/raw/src/profile.rs | 233 ++--- crates/raw/src/saturation.rs | 4 +- crates/raw/src/semantic.rs | 136 --- crates/raw/src/sparse.rs | 2 +- crates/raw/src/tests.rs | 10 +- crates/raw/src/tiffraw.rs | 7 +- crates/raw/src/vendor.rs | 18 +- crates/raw/src/vendor/arw.rs | 4 +- crates/raw/src/vendor/arw6.rs | 4 +- crates/raw/src/vendor/arw_lens.rs | 2 +- crates/raw/src/vendor/cr2.rs | 638 ------------ crates/raw/src/vendor/cr2/sraw.rs | 580 ----------- crates/raw/src/vendor/cr3.rs | 2 +- crates/raw/src/vendor/crw.rs | 255 ----- crates/raw/src/vendor/erf.rs | 234 ----- crates/raw/src/vendor/hasselblad.rs | 295 ------ crates/raw/src/vendor/huffman.rs | 106 ++ crates/raw/src/vendor/kodak.rs | 285 ------ crates/raw/src/vendor/mef.rs | 279 ------ crates/raw/src/vendor/mrw.rs | 232 ----- crates/raw/src/vendor/nef.rs | 1429 --------------------------- crates/raw/src/vendor/nef_lens.rs | 259 ----- crates/raw/src/vendor/nefc.rs | 794 --------------- crates/raw/src/vendor/orf.rs | 2 +- crates/raw/src/vendor/pef.rs | 722 -------------- crates/raw/src/vendor/raf.rs | 2 +- crates/raw/src/vendor/rw2.rs | 4 +- crates/raw/src/vendor/srw.rs | 603 ----------- crates/raw/src/wb_estimate.rs | 2 +- 48 files changed, 646 insertions(+), 10494 deletions(-) create mode 100644 crates/raw/src/convert.rs delete mode 100644 crates/raw/src/dng.rs delete mode 100644 crates/raw/src/jxl.rs delete mode 100644 crates/raw/src/ljpeg.rs delete mode 100644 crates/raw/src/ljpeg/tests.rs create mode 100644 crates/raw/src/ljpeg_fixtures.rs delete mode 100644 crates/raw/src/semantic.rs delete mode 100644 crates/raw/src/vendor/cr2.rs delete mode 100644 crates/raw/src/vendor/cr2/sraw.rs delete mode 100644 crates/raw/src/vendor/crw.rs delete mode 100644 crates/raw/src/vendor/erf.rs delete mode 100644 crates/raw/src/vendor/hasselblad.rs create mode 100644 crates/raw/src/vendor/huffman.rs delete mode 100644 crates/raw/src/vendor/kodak.rs delete mode 100644 crates/raw/src/vendor/mef.rs delete mode 100644 crates/raw/src/vendor/mrw.rs delete mode 100644 crates/raw/src/vendor/nef.rs delete mode 100644 crates/raw/src/vendor/nef_lens.rs delete mode 100644 crates/raw/src/vendor/nefc.rs delete mode 100644 crates/raw/src/vendor/pef.rs delete mode 100644 crates/raw/src/vendor/srw.rs diff --git a/Cargo.toml b/Cargo.toml index 301ca570e2..e5f0b6d189 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,8 +12,6 @@ repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } -# Canon CRW decoder shared with the other Craft apps -craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } @@ -31,7 +29,10 @@ lightcraft-wincolor = { path = "crates/wincolor" } lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } # TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783). -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "3b3104981bb3093904a12e44d6a3b41c6c4c39c8" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "119415f46f601e20b9bc6b1b4d6979ceda86d88e" } +# Camera raw files, the format layer: every maker but CR3, ARW, RAF, RW2 and ORF (craft-libs#862 and the maker PRs). +# On the same commit as craft-tiff: its errors and IFDs are shared. +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "119415f46f601e20b9bc6b1b4d6979ceda86d88e" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } @@ -182,6 +183,7 @@ lightcraft-color = { opt-level = 3 } lightcraft-develop = { opt-level = 3 } lightcraft-geom = { opt-level = 3 } lightcraft-raw = { opt-level = 3 } +craft-raw = { opt-level = 3 } lightcraft-codecs = { opt-level = 3 } lightcraft-scenes = { opt-level = 3 } lightcraft-preview = { opt-level = 3 } diff --git a/crates/engine/src/files/preview.rs b/crates/engine/src/files/preview.rs index 85ee2c5fb8..4a18e0997a 100644 --- a/crates/engine/src/files/preview.rs +++ b/crates/engine/src/files/preview.rs @@ -21,7 +21,7 @@ fn stand_in_image(bytes: &[u8], covering: Option) -> Option bool { let Some(cfa) = &self.cfa else { return false }; - if k < 2 || self.cpp != 1 || (self.pixel_aspect - 1.0).abs() >= 0.01 || !cfa.valid() || (cfa.is_bayer() && !k.is_multiple_of(2)) { + if k < 2 || self.cpp != 1 || (self.pixel_aspect - 1.0).abs() >= 0.01 || !crate::cfa_valid(cfa) || (cfa.is_bayer() && !k.is_multiple_of(2)) { return false; } // every window position relative to the pattern diff --git a/crates/raw/src/convert.rs b/crates/raw/src/convert.rs new file mode 100644 index 0000000000..ed1a63a44d --- /dev/null +++ b/crates/raw/src/convert.rs @@ -0,0 +1,210 @@ +//! The makers `craft-raw` decodes (DNG, Hasselblad, CRW, CR2, NEF / NRW, PEF, SRW, MRW, ERF, MEF, Kodak DCS), mapped +//! onto this crate's [`RawImage`]: the colour tags into LightCraft's colour types, and what the format layer leaves +//! to the developer added here: +//! +//! - [`Metadata`] from the file's Exif (a CRW, which has none, from its own records), with the developed size; +//! - DNG and Hasselblad samples stuck below the stated white level raised to it ([`RawImage::lift_clipped_samples`]); +//! - Epson ERF and Mamiya MEF, which record no white balance, get one estimated from their preview +//! ([`crate::wb_estimate`]); their header probe decodes the samples for it, as before; +//! - Nikon bodies whose files record no white-balance presets get LightCraft's built-in ones +//! ([`crate::kelvin_builtin`]). + +use craft_tiff::{Tiff, tags as t}; +use lightcraft_color::Xy; +use lightcraft_meta::{DateTime, Metadata}; + +use crate::{ColorData, Mat3, Mode, Orientation, RawFormat, RawImage, Rect, Result}; + +pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { + let format = crate::probe(bytes); + // the white balance of these two is measured from the samples, so the probe decodes them too + let estimate_wb = matches!(format, Some(RawFormat::Erf | RawFormat::Mef)); + let mut img = if mode == Mode::Full || estimate_wb { + let raw = craft_raw::decode(bytes)?; + let metadata = metadata(bytes, raw.format, &raw.camera, raw.info().developed_size()); + image(raw, metadata) + } else { + let info = craft_raw::probe_info(bytes)?; + let metadata = metadata(bytes, info.format, &info.camera, info.developed_size()); + header_image(info, metadata) + }; + if estimate_wb && img.wb_multipliers.is_none() { + img.wb_multipliers = estimated_wb(bytes, &img); + } + if mode == Mode::Header { + img.data = craft_raw::RawData::U16(Vec::new()); + } + finish(&mut img); + Ok(img) +} + +pub(crate) fn decode_reduced(bytes: &[u8], min_long: usize) -> Result> { + let Some(raw) = craft_raw::decode_reduced(bytes, min_long, &craft_raw::Limits::default())? else { return Ok(None) }; + // the developed size of the whole picture, which the metadata reports whatever copy the samples come from + let full = craft_raw::probe_info(bytes)?; + let metadata = metadata(bytes, full.format, &full.camera, full.developed_size()); + let mut img = image(raw, metadata); + finish(&mut img); + Ok(Some(img)) +} + +/// What LightCraft adds to every decoded file of these makers. +fn finish(img: &mut RawImage) { + // DNG writers state a white level the sensor may never reach; samples stuck at the real saturation point are + // raised to the white level so they count as clipped + if matches!(img.format, RawFormat::Dng | RawFormat::CfaTiff) { + img.lift_clipped_samples(); + } + // a CRW's rotation is its ImageInfo record's, not an Exif tag's + if img.format == RawFormat::Crw { + img.metadata.orientation = Some(img.orientation); + } + if matches!(img.format, RawFormat::Nef | RawFormat::Nrw) && img.color.kelvin_presets.is_none() { + img.color.kelvin_presets = img.metadata.model.as_deref().and_then(|model| crate::kelvin_builtin::find(img.metadata.make.as_deref(), model)); + } +} + +/// The file's Exif as [`Metadata`], with `size` (the developed size) as its width and height. A CRW has no Exif: +/// its make, model and capture time come from its own records. +fn metadata(bytes: &[u8], format: RawFormat, camera: &craft_raw::Camera, size: (usize, usize)) -> Metadata { + let mut m = if format == RawFormat::Crw { + Metadata { + make: camera.make.clone(), + model: camera.model.clone(), + capture_time: camera.capture_unix.and_then(datetime_from_unix), + ..Metadata::default() + } + } else { + // an MRW keeps its Exif TIFF in the `TTW` block + let tiff = match format { + RawFormat::Mrw => lightcraft_meta::mrw::parse(bytes).and_then(|m| m.block(b"TTW")).and_then(|b| Tiff::parse(b).ok()), + _ => Tiff::parse_with(bytes, &craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }).ok(), + }; + tiff.as_ref().map(lightcraft_meta::from_tiff).unwrap_or_default() + }; + m.width = Some(size.0 as u32); + m.height = Some(size.1 as u32); + m +} + +/// Civil date-time from a CRW TimeStamp record's Unix seconds (the camera's local clock, no UTC offset; inverse of +/// [`DateTime::unix_seconds`]). Before 1970 or after 2200 is a garbage clock, not a capture time. +fn datetime_from_unix(t: i64) -> Option { + use chrono::{Datelike, Timelike}; + let c = chrono::DateTime::from_timestamp(t, 0)?.naive_utc(); + let dt = DateTime { + year: u16::try_from(c.year()).ok()?, + month: u8::try_from(c.month()).ok()?, + day: u8::try_from(c.day()).ok()?, + hour: u8::try_from(c.hour()).ok()?, + minute: u8::try_from(c.minute()).ok()?, + second: u8::try_from(c.second()).ok()?, + millis: 0, + offset_minutes: None, + }; + ((1970..=2200).contains(&dt.year)).then_some(dt) +} + +fn orientation(o: craft_raw::Orientation) -> Orientation { + Orientation::from_exif(o.to_exif()) +} + +fn color(c: craft_raw::ColorData) -> ColorData { + let m = |p: [Option; 2]| p.map(|m| m.map(Mat3)); + ColorData { + illuminant: c.illuminant, + color_matrix: m(c.color_matrix), + forward_matrix: m(c.forward_matrix), + camera_calibration: m(c.camera_calibration), + analog_balance: c.analog_balance, + as_shot_neutral: c.as_shot_neutral, + as_shot_white_xy: c.as_shot_white_xy.map(|[x, y]| Xy::new(x, y)), + baseline_exposure: c.baseline_exposure, + baseline_sharpness: c.baseline_sharpness, + profile: c.profile, + kelvin_presets: c.kelvin_presets.and_then(|k| crate::kelvin_presets::KelvinPresets::new(k.points().iter().copied())), + } +} + +fn image(r: craft_raw::RawImage, metadata: Metadata) -> RawImage { + RawImage { + format: r.format, + width: r.width, + height: r.height, + cpp: r.cpp, + data: r.data, + cfa: r.cfa, + bits: r.bits, + black: r.black, + white: r.white, + active_area: r.active_area, + crop: r.crop, + orientation: orientation(r.orientation), + color: color(r.color), + wb_multipliers: r.wb_multipliers, + linearized: r.linearized, + pixel_aspect: r.pixel_aspect, + opcodes: r.opcodes, + metadata, + lens_metadata: Default::default(), + } +} + +/// An image without samples from a header probe; only [`RawImage::into_info`] looks at it. +fn header_image(i: craft_raw::RawInfo, metadata: Metadata) -> RawImage { + RawImage { + format: i.format, + width: i.width, + height: i.height, + cpp: i.cpp, + data: craft_raw::RawData::U16(Vec::new()), + cfa: i.cfa, + bits: i.bits, + black: Default::default(), + white: vec![65535.0], + active_area: i.active_area, + crop: i.crop, + orientation: orientation(i.orientation), + color: color(i.color), + wb_multipliers: i.wb_multipliers, + linearized: false, + pixel_aspect: i.pixel_aspect, + opcodes: i.opcodes, + metadata, + lens_metadata: Default::default(), + } +} + +/// The as-shot white balance of an ERF or MEF, from its preview's neutral pixels (an MEF's uncompressed RGB +/// preview, an ERF's JPEG), else grey world. +fn estimated_wb(bytes: &[u8], img: &RawImage) -> Option<[f32; 3]> { + let craft_raw::RawData::U16(data) = &img.data else { return None }; + let (a, c) = (img.active_area, img.crop); + let crop = Rect::new(a.x.checked_add(c.x)?, a.y.checked_add(c.y)?, c.width, c.height); + let cfa = img.cfa.as_ref()?; + let frame = crate::wb_estimate::Frame { data, width: img.width, crop, cfa, black: &img.black, white: img.white_at(0) }; + match (img.format == RawFormat::Mef).then(|| rgb_preview(bytes)).flatten() { + Some((px, pw, ph)) => crate::wb_estimate::as_shot_rgb(px, pw, ph, &frame), + None => crate::wb_estimate::as_shot(bytes, &frame), + } +} + +/// The largest uncompressed 8-bit RGB sub-IFD of a TIFF (an MEF's preview): its pixels, width and height. +fn rgb_preview(bytes: &[u8]) -> Option<(&[u8], usize, usize)> { + let tiff = Tiff::parse(bytes).ok()?; + tiff.all_ifds() + .into_iter() + .filter_map(|i| { + let info = i.image().ok()?; + let ok = i.u16(t::PHOTOMETRIC) == Some(2) + && i.u16(t::COMPRESSION).unwrap_or(1) == 1 + && i.u16(t::SAMPLES_PER_PIXEL) == Some(3) + && i.u64s(t::BITS_PER_SAMPLE).is_some_and(|b| b.iter().all(|&v| v == 8)); + let (w, h) = (info.width as usize, info.height as usize); + let chunks = info.chunks(bytes.len() as u64); + let [c] = chunks.as_slice() else { return None }; + let px = craft_tiff::image::chunk_bytes(bytes, c)?; + (ok && px.len() >= w.checked_mul(h)?.checked_mul(3)?).then_some((px, w, h)) + }) + .max_by_key(|(_, w, h)| w * h) +} diff --git a/crates/raw/src/dcp.rs b/crates/raw/src/dcp.rs index a577fbe4e5..e0cbea7939 100644 --- a/crates/raw/src/dcp.rs +++ b/crates/raw/src/dcp.rs @@ -4,10 +4,12 @@ //! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the //! hue/saturation map, look table and tone curve. Nothing here ships a profile. -use craft_tiff::{Ifd, ParseOptions, Tiff, tags as t}; +use craft_tiff::{ByteOrder, Ifd, ParseOptions, Tiff, tags as t}; +use lightcraft_color::Xy; -use crate::ColorData; -use crate::dng::color_data; +use crate::gaintable::GainTableMap; +use crate::profile::{HsvTable, ProfileLook, ToneCurve}; +use crate::{ColorData, Mat3}; /// The magic number of a DNG camera profile file (`IIRC` / `MMCR`). pub const DCP_MAGIC: u16 = 0x4352; @@ -171,6 +173,78 @@ pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { Ok(out) } +// The colour tags a profile shares with DNG, read as DNG reads them (a DNG's own are read by `craft-raw`). + +fn mat3(v: Option>) -> Option { + let v = v?; + if v.len() != 9 || v.iter().any(|x| !x.is_finite()) { + return None; + } + let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); + (m.determinant().abs() > 1e-12).then_some(m) +} + +fn vec3(v: Option>) -> Option<[f64; 3]> { + let v = v?; + (v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]]) +} + +/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD. +/// `order` is the file's byte order (for the binary gain-table-map tags). +fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData { + let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag)); + let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag)); + ColorData { + illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)], + color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))], + forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))], + camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))], + analog_balance: vec3(get(t::ANALOG_BALANCE)), + as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)), + as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])), + baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0) + + get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0), + // DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored + baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0), + profile: profile_look(ifd0, raw, order), + kelvin_presets: None, + } +} + +/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`, +/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD +/// first, else IFD 0. +fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook { + let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 }; + let table = |dims: u16, data: u16, enc: u16| { + let ifd = pick(dims); + let dims = ifd.u64s(dims)?; + let data = ifd.f64s(data)?; + HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0)) + }; + ProfileLook { + hue_sat_map: [ + table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING), + table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING), + ], + look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING), + tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)), + gain_table_map: gain_table_map(ifd0, raw, order), + } +} + +/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded +/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG +/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be). +/// A malformed tag falls through to the next one. +fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option { + let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2)); + parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2) + .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2)) + .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP)) + .or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs deleted file mode 100644 index c156e8f4cb..0000000000 --- a/crates/raw/src/dng.rs +++ /dev/null @@ -1,551 +0,0 @@ -//! DNG (Adobe Digital Negative Specification 1.7): raw IFD selection, pixel data (via [`crate::tiffraw`]), -//! linearization, black/white levels, active area, default crop, CFA description, colour tags, opcode lists. - -use crate::gaintable::GainTableMap; -use crate::profile::{HsvTable, ProfileLook, ToneCurve}; -use crate::tiffraw::{Packing, read_image_in}; -use crate::{BlackLevel, Cfa, ColorData, Mat3, Mode, RawData, RawError, RawFormat, RawImage, Rect, Result, opcodes}; -use craft_tiff::tags::{self as t, photometric}; -use craft_tiff::{ByteOrder, Ifd, Tiff}; -use lightcraft_color::Xy; -use lightcraft_geom::Orientation; - -/// The main raw IFD: full-resolution (NewSubfileType 0) CFA or LinearRaw image with the most pixels. -pub(crate) fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> { - tiff.all_ifds() - .into_iter() - .filter(|i| i.u32(t::NEW_SUBFILE_TYPE).unwrap_or(0) == 0) - .filter(|i| matches!(i.u16(t::PHOTOMETRIC), Some(photometric::CFA) | Some(photometric::LINEAR_RAW))) - .max_by_key(|i| i.u64(t::IMAGE_WIDTH).unwrap_or(0).saturating_mul(i.u64(t::IMAGE_LENGTH).unwrap_or(0))) -} - -/// Undo the DNG 1.7 row/column interleave, which reorders the stored raster without changing its -/// size: with `RowInterleaveFactor = n` the rows are stored as `n` consecutive fields, field `g` -/// holding rows `g, g+n, g+2n, …` of the image (and likewise for columns). -/// -/// The tag counts fields, not a divisor of the raster — see [`field_map`] — so a dimension the -/// factor does not divide is decoded, with the trailing fields short, rather than refused. -/// -/// Left alone, a file like this decodes as `n × m` scaled-down copies of the scene, one per -/// field, with the CFA pattern then read across permuted samples — so it is not merely misplaced, -/// it is the wrong colour as well (`RowInterleaveFactor = ColumnInterleaveFactor = 2` is what DNG -/// 1.7 JPEG XL files from Adobe's converter carry). -fn deinterleave(data: &mut RawData, w: usize, h: usize, cpp: usize, rows: usize, cols: usize) -> Result<()> { - if rows <= 1 && cols <= 1 { - return Ok(()); - } - // The spec sets no bound on the value (it is only "the number of interleaved fields"); this - // caps the field table we build and the permutation, and rejects a hostile tag. - if !(1..=16).contains(&rows) || !(1..=16).contains(&cols) { - return Err(RawError::Unsupported(format!("interleave factors {rows} × {cols}"))); - } - let (map_r, map_c) = (field_map(h, rows), field_map(w, cols)); - let dest = |r: usize, c: usize| map_r[r] * w + map_c[c]; - match data { - RawData::U16(v) => permute(v, w, h, cpp, dest), - RawData::F32(v) => permute(v, w, h, cpp, dest), - } -} - -/// The stored-line → image-line map for one axis: a factor of `n` splits `len` lines into `n` -/// interleaved fields, field `g` holding lines `g, g+n, g+2n, …`. The fields are stored -/// consecutively, so field `g` starts at stored line `offs[g]` and its `k`-th line is image line -/// `g + n*k`. Field sizes follow from the round-robin split — field `g` has `ceil((len - g) / n)` -/// lines — so when `n` does not divide `len` the trailing fields are short, and when `n` exceeds -/// `len` the trailing fields are empty. -fn field_map(len: usize, n: usize) -> Vec { - let mut offs = Vec::with_capacity(n + 1); - let mut acc = 0usize; - for g in 0..=n { - offs.push(acc); - if g < n && g < len { - acc += (len - 1 - g) / n + 1; - } - } - let mut map = vec![0usize; len]; - for g in 0..n { - for (k, i) in (offs[g]..offs[g + 1]).enumerate() { - map[i] = g + n * k; - } - } - map -} - -/// Move every `cpp`-sample pixel of `v` from its stored position to `dest(r, c)`, the image -/// position it belongs at. The permutation is not its own inverse, so it needs a destination. -fn permute usize>(v: &mut Vec, w: usize, h: usize, cpp: usize, dest: F) -> Result<()> { - let n = w.checked_mul(h).and_then(|n| n.checked_mul(cpp)).ok_or_else(|| RawError::Corrupt("image too large".into()))?; - if v.len() != n { - return Err(RawError::Corrupt("mosaic size does not match the image".into())); - } - let mut out = vec![T::default(); n]; - for r in 0..h { - for c in 0..w { - let (from, to) = ((r * w + c) * cpp, dest(r, c) * cpp); - out[to..to + cpp].copy_from_slice(&v[from..from + cpp]); - } - } - *v = out; - Ok(()) -} - -fn mat3(v: Option>) -> Option { - let v = v?; - if v.len() != 9 || v.iter().any(|x| !x.is_finite()) { - return None; - } - let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); - (m.determinant().abs() > 1e-12).then_some(m) -} - -fn vec3(v: Option>) -> Option<[f64; 3]> { - let v = v?; - (v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]]) -} - -/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD. -/// `order` is the file's byte order (for the binary gain-table-map tags). -pub(crate) fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData { - let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag)); - let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag)); - ColorData { - illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)], - color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))], - forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))], - camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))], - analog_balance: vec3(get(t::ANALOG_BALANCE)), - as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)), - as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])), - baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0) - + get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0), - // DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored - baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0), - profile: profile_look(ifd0, raw, order), - kelvin_presets: None, - } -} - -/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`, -/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD -/// first, else IFD 0. -pub(crate) fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook { - let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 }; - let table = |dims: u16, data: u16, enc: u16| { - let ifd = pick(dims); - let dims = ifd.u64s(dims)?; - let data = ifd.f64s(data)?; - HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0)) - }; - ProfileLook { - hue_sat_map: [ - table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING), - table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING), - ], - look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING), - tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)), - gain_table_map: gain_table_map(ifd0, raw, order), - } -} - -/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded -/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG -/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be). -/// A malformed tag falls through to the next one. -fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option { - let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2)); - parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2) - .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2)) - .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP)) - .or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP)) -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - decode_as(bytes, mode, RawFormat::Dng) -} - -/// Whether a TIFF that is not a DNG describes a raw image the way DNG does: a full-resolution CFA IFD -/// and DNG's own statement of the white balance (`AsShotNeutral`, in IFD0 or the raw IFD), in a coding -/// [`decode_as`] reads: uncompressed, or lossless JPEG whose scan header the lossless decoder accepts. -/// Such files (Hasselblad 3FR and FFF) carry no DNG version tag, so they are not DNGs, but nothing else -/// in them needs a maker-specific reader. Without the white-balance tag nothing in the file says how -/// to read its colour, and the file stays an undecodable raw. -pub(crate) fn is_plain_cfa_tiff(tiff: &Tiff, bytes: &[u8]) -> bool { - let Some(raw) = raw_ifd(tiff) else { return false }; - if !raw.contains(t::AS_SHOT_NEUTRAL) && !tiff.ifds.first().is_some_and(|i| i.contains(t::AS_SHOT_NEUTRAL)) { - return false; - } - let Ok(info) = raw.image() else { return false }; - if info.samples_per_pixel != 1 || !(1..=16).contains(&info.bits()) || info.sample_format == 3 { - return false; - } - match info.compression { - t::compression::NONE => true, - t::compression::JPEG => info - .chunks(bytes.len() as u64) - .first() - .and_then(|c| craft_tiff::image::chunk_bytes(bytes, c)) - .is_some_and(|src| crate::ljpeg::frame_info(src).is_ok()), - _ => false, - } -} - -/// [`decode`] for the TIFF-based raws that follow the DNG layout without being DNGs (`format` says -/// which). They differ in one respect: when the raw IFD states no `CFAPattern`, the layout is RGGB -/// anchored at the sensor origin. -pub(crate) fn decode_as(bytes: &[u8], mode: Mode, format: RawFormat) -> Result { - let tiff = Tiff::parse(bytes)?; - let raw = raw_ifd(&tiff).ok_or_else(|| RawError::Corrupt("DNG without a raw image IFD".into()))?; - decode_ifd(bytes, &tiff, raw, raw, mode, format) -} - -/// The smallest reduced-resolution copy of a DNG's LinearRaw image whose default crop still has a long edge of -/// `min_long` px: Lightroom keeps 256, 512 and 2048 px copies beside the full image of its HDR and panorama -/// merges, so a thumbnail decodes a 512 px copy instead of a 24k × 7k image (about 19 s). Only a copy that the main -/// image's tags describe as well: same samples per pixel and aspect ratio (within 1 %), and a main image without -/// opcode lists, a linearization table or black-level deltas (all in full-size pixel coordinates). -fn reduced_ifd<'a>(tiff: &'a Tiff, main: &Ifd, min_long: usize) -> Option<&'a Ifd> { - if main.u16(t::PHOTOMETRIC) != Some(photometric::LINEAR_RAW) { - return None; - } - let full_size_tags = - [t::OPCODE_LIST_1, t::OPCODE_LIST_2, t::OPCODE_LIST_3, t::LINEARIZATION_TABLE, t::BLACK_LEVEL_DELTA_H, t::BLACK_LEVEL_DELTA_V]; - if full_size_tags.iter().any(|&tag| main.contains(tag)) { - return None; - } - let (mw, mh) = (main.u64(t::IMAGE_WIDTH)?, main.u64(t::IMAGE_LENGTH)?); - if mw == 0 || mh == 0 { - return None; - } - let crop_long = match main.f64s(t::DEFAULT_CROP_SIZE).as_deref() { - Some([w, h]) if w.is_finite() && h.is_finite() && *w >= 1.0 && *h >= 1.0 => w.max(*h).min(mw.max(mh) as f64), - _ => mw.max(mh) as f64, - }; - let cpp = main.u16(t::SAMPLES_PER_PIXEL).unwrap_or(1); - tiff.all_ifds() - .into_iter() - .filter(|i| i.u32(t::NEW_SUBFILE_TYPE) == Some(1) && i.u16(t::PHOTOMETRIC) == Some(photometric::LINEAR_RAW)) - .filter(|i| i.u16(t::SAMPLES_PER_PIXEL).unwrap_or(1) == cpp) - .filter_map(|i| { - let (w, h) = (i.u64(t::IMAGE_WIDTH)?, i.u64(t::IMAGE_LENGTH)?); - let (a, b) = (w.checked_mul(mh)?, h.checked_mul(mw)?); - let same_aspect = w > 0 && h > 0 && a.abs_diff(b).saturating_mul(100) <= a; - let covers = crop_long * w as f64 / mw as f64 >= min_long as f64; - (same_aspect && covers && w < mw && h < mh).then_some((i, w)) - }) - .min_by_key(|&(_, w)| w) - .map(|(i, _)| i) -} - -/// [`decode`] from the smallest reduced-resolution copy of the raw image that covers `min_long` ([`reduced_ifd`]): -/// the main image's levels, colour and metadata, its active area and default crop scaled to the copy. `None` when the -/// file keeps no such copy. -pub(crate) fn decode_reduced(bytes: &[u8], min_long: usize) -> Result> { - let tiff = Tiff::parse(bytes)?; - let Some(main) = raw_ifd(&tiff) else { return Ok(None) }; - let Some(small) = reduced_ifd(&tiff, main, min_long) else { return Ok(None) }; - decode_ifd(bytes, &tiff, small, main, Mode::Full, RawFormat::Dng).map(Some) -} - -/// [`decode_as`] of the samples in `pixels`, described by the raw IFD `main`: the same IFD, or (see -/// [`decode_reduced`]) a reduced-resolution copy of it, whose own level tags win and whose geometry is `main`'s -/// scaled to its size. -fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, format: RawFormat) -> Result { - let ifd0 = &tiff.ifds[0]; - let raw = main; - // GoPro's GPR: a DNG whose raw data is VC-5 coded, which is not decoded (yet). Named here, before - // the generic "TIFF compression 9" of the chunk decoder. Header mode still describes the file - // (a GPR has no embedded preview, and a library keeps the photo with this reason shown, as it - // does for any file whose pixels fail to decode, rather than refusing to import it). - if mode == Mode::Full - && let Some(c) = pixels.u16(t::COMPRESSION).filter(|&c| c == t::compression::VC5) - { - return Err(RawError::Unsupported(format!("DNG compression {c} (GoPro VC-5) is not decoded yet"))); - } - let info = pixels.image()?; - let (w, h, cpp) = (info.width as usize, info.height as usize, info.samples_per_pixel as usize); - // one sample (CFA or monochrome), RGB or four colours; two are neither and can't be developed (issue #1511) - if !matches!(cpp, 1 | 3 | 4) { - return Err(RawError::Unsupported(format!("{cpp} samples per pixel"))); - } - let mut data = read_image_in(mode, bytes, &info, tiff.order, Packing::Msb)?; - let bits = info.bits() as u32; - - // DNG 1.7 interleaved storage: the raster is a permutation of the mosaic, so undo it before - // anything reads a sample as a pixel. - if mode == Mode::Full { - let factor = |tag| pixels.u16(tag).map(usize::from).unwrap_or(1); - deinterleave(&mut data, w, h, cpp, factor(t::ROW_INTERLEAVE_FACTOR), factor(t::COLUMN_INTERLEAVE_FACTOR))?; - } - - // linearization table (integer data only) - let mut linearized = false; - if let (RawData::U16(v), Some(table)) = (&mut data, pixels.u64s(t::LINEARIZATION_TABLE).filter(|t| !t.is_empty())) { - let table: Vec = table.iter().map(|&x| x.min(65535) as u16).collect(); - let last = table.len() - 1; - v.iter_mut().for_each(|s| *s = table[(*s as usize).min(last)]); - linearized = true; - } - - // a reduced copy's own levels, where it states them - let levels = |tag| if pixels.contains(tag) { pixels } else { raw }; - let float = matches!(data, RawData::F32(_)); - let default_white = if float { 1.0 } else { ((1u64 << bits.min(16)) - 1) as f32 }; - let mut white: Vec = - levels(t::WHITE_LEVEL).f64s(t::WHITE_LEVEL).unwrap_or_default().into_iter().map(|v| v as f32).filter(|v| *v > 0.0).collect(); - if white.is_empty() { - white = vec![default_white]; - } - // No sensor records NaN or infinity, so such a float sample is damage. Left in, it turns into NaN in demosaic - // arithmetic and spreads; NaN and −∞ read as black (0), +∞ as the white level (a clipped highlight). Finite - // samples, negative or above white included, are kept as stored. - if let RawData::F32(v) = &mut data { - for (i, s) in v.iter_mut().enumerate() { - if !s.is_finite() { - *s = if *s > 0.0 { white.get(i % cpp).or(white.first()).copied().unwrap_or(default_white) } else { 0.0 }; - } - } - } - - let dim = levels(t::BLACK_LEVEL).u64s(t::BLACK_LEVEL_REPEAT_DIM).unwrap_or_default(); - let (br, bc) = match dim.as_slice() { - [r, c] if (1..=16).contains(r) && (1..=16).contains(c) => (*r as usize, *c as usize), - _ => (1, 1), - }; - // (a FLOAT / DOUBLE tag can hold NaN or infinity: such a level reads as 0, in its place) - let level = |v: f64| Some(v as f32).filter(|v| v.is_finite()).unwrap_or(0.0); - let mut values: Vec = levels(t::BLACK_LEVEL).f64s(t::BLACK_LEVEL).unwrap_or_default().into_iter().map(level).collect(); - if values.len() != br * bc * cpp { - values = vec![values.first().copied().unwrap_or(0.0)]; - } - let (br, bc) = if values.len() == 1 { (1, 1) } else { (br, bc) }; - let floats = |tag| raw.f64s(tag).unwrap_or_default().into_iter().map(level).collect::>(); - let black = - BlackLevel { repeat_rows: br, repeat_cols: bc, values, delta_h: floats(t::BLACK_LEVEL_DELTA_H), delta_v: floats(t::BLACK_LEVEL_DELTA_V) }; - - // geometry in the main image's pixels (a reduced copy's is scaled below) - let (full_w, full_h) = if std::ptr::eq(pixels, raw) { - (w, h) - } else { - (raw.u64(t::IMAGE_WIDTH).unwrap_or(0) as usize, raw.u64(t::IMAGE_LENGTH).unwrap_or(0) as usize) - }; - if full_w == 0 || full_h == 0 { - return Err(RawError::Corrupt("raw image IFD without a size".into())); - } - let active_area = match raw.u64s(t::ACTIVE_AREA).as_deref() { - Some([top, left, bottom, right]) if bottom > top && right > left && (*bottom as usize) <= full_h && (*right as usize) <= full_w => { - Rect::new(*left as usize, *top as usize, (*right - *left) as usize, (*bottom - *top) as usize) - } - _ => Rect::new(0, 0, full_w, full_h), - }; - let crop = match (raw.f64s(t::DEFAULT_CROP_ORIGIN).as_deref(), raw.f64s(t::DEFAULT_CROP_SIZE).as_deref()) { - (Some([x, y]), Some([cw, ch])) if *cw >= 1.0 && *ch >= 1.0 && *x >= 0.0 && *y >= 0.0 => { - Rect::new(x.round() as usize, y.round() as usize, cw.round() as usize, ch.round() as usize).clipped(active_area.width, active_area.height) - } - _ => Rect::new(0, 0, active_area.width, active_area.height), - }; - // the developed size, which the metadata reports whatever copy the samples come from - let developed = (crop.width, crop.height); - let (active_area, crop) = if (full_w, full_h) == (w, h) { - (active_area, crop) - } else { - let (sx, sy) = (w as f64 / full_w as f64, h as f64 / full_h as f64); - let scale = |r: Rect| { - let (x, y) = ((r.x as f64 * sx).round() as usize, (r.y as f64 * sy).round() as usize); - let (x1, y1) = (((r.x + r.width) as f64 * sx).round() as usize, ((r.y + r.height) as f64 * sy).round() as usize); - Rect::new(x, y, x1.saturating_sub(x).max(1), y1.saturating_sub(y).max(1)) - }; - let area = scale(active_area).clipped(w, h); - (area, scale(crop).clipped(area.width, area.height)) - }; - - let cfa = if info.photometric == photometric::CFA { - if raw.u16(t::CFA_LAYOUT).unwrap_or(1) != 1 { - return Err(RawError::Unsupported("non-rectangular CFA layout".into())); - } - let dim = raw.u64s(t::CFA_REPEAT_PATTERN_DIM).unwrap_or_else(|| vec![2, 2]); - let (rows, cols) = match dim.as_slice() { - [r, c] if (1..=16).contains(r) && (1..=16).contains(c) => (*r as usize, *c as usize), - _ => return Err(RawError::Corrupt("bad CFARepeatPatternDim".into())), - }; - // a TIFF that is not a DNG may leave the layout out: RGGB from the sensor origin - let assumed = [0u8, 1, 1, 2]; - let pat = match raw.bytes(t::CFA_PATTERN_EP) { - Some(p) => p, - None if format != RawFormat::Dng && (rows, cols) == (2, 2) => &assumed, - None => return Err(RawError::Corrupt("missing CFAPattern".into())), - }; - if pat.len() != rows * cols { - return Err(RawError::Corrupt("CFAPattern size mismatch".into())); - } - let planes = raw.bytes(t::CFA_PLANE_COLOR).map(|b| b.to_vec()).unwrap_or_else(|| vec![0, 1, 2]); - let pattern: Vec = pat - .iter() - .map(|c| planes.iter().position(|p| p == c).map(|i| i as u8).filter(|&i| i < 3)) - .collect::>() - .ok_or_else(|| RawError::Unsupported("CFA with more than three colours".into()))?; - if cpp != 1 { - return Err(RawError::Unsupported("CFA data with several samples per pixel".into())); - } - // the tag is anchored at the top-left of the ActiveArea (DNG spec); `RawImage::cfa` is anchored at the - // sensor origin (the crop to the active area shifts it back), so move the anchor out by the area's offset - // (LightCraft's own DNGs from before the writer followed the spec carry the sensor-origin pattern; they are marked by - // a bare "LightCraft" Software tag, the writer now says [`crate::dngwrite::SOFTWARE`], and keep their original reading) - let at_origin = Cfa { width: cols, height: rows, pattern }; - let legacy_writer = [raw, ifd0].iter().any(|i| i.string(t::SOFTWARE).as_deref().map(str::trim) == Some("LightCraft")); - Some(if legacy_writer { at_origin } else { at_origin.shifted(cols - active_area.x % cols, rows - active_area.y % rows) }) - } else { - None - }; - - let opcode_list = |tag| raw.bytes(tag).map(opcodes::parse_list).unwrap_or_default(); - let opcodes = - crate::OpcodeLists { list1: opcode_list(t::OPCODE_LIST_1), list2: opcode_list(t::OPCODE_LIST_2), list3: opcode_list(t::OPCODE_LIST_3) }; - - let mut metadata = lightcraft_meta::from_tiff(tiff); - metadata.width = Some(developed.0 as u32); - metadata.height = Some(developed.1 as u32); - let img = RawImage { - format, - width: w, - height: h, - cpp, - data, - cfa, - bits, - black, - white, - active_area, - crop, - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: color_data(ifd0, raw, tiff.order), - wb_multipliers: None, - linearized, - pixel_aspect: default_scale_aspect(raw.f64s(t::DEFAULT_SCALE).as_deref()), - opcodes, - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -/// Pixel height over width from `DefaultScale` (horizontal, vertical): only a clear 1.5 to 4 ratio counts (the rows stretch; a wider-than-tall pixel is left alone). -fn default_scale_aspect(scale: Option<&[f64]>) -> f32 { - match scale { - Some([h, v]) if *h > 0.0 && *v > 0.0 && (1.5..=4.0).contains(&(v / h)) => (v / h) as f32, - _ => 1.0, - } -} - -#[cfg(test)] -mod tests { - #[test] - fn default_scale_makes_tall_pixels() { - assert_eq!(default_scale_aspect(Some(&[1.0, 2.0])), 2.0); - assert_eq!(default_scale_aspect(Some(&[1.0, 1.0])), 1.0); - assert_eq!(default_scale_aspect(Some(&[2.0, 1.0])), 1.0); - assert_eq!(default_scale_aspect(Some(&[1.0, 1.2])), 1.0); - assert_eq!(default_scale_aspect(None), 1.0); - } - - use super::*; - - /// Store `image` the way DNG 1.7 interleaves it: row `r` of the image is written to stored row - /// `(r % rows) * (h / rows) + r / rows`, and columns likewise. This is the inverse of - /// [`deinterleave`]'s destination map for a raster the factor divides, i.e. what a writer - /// produces (the short-trailing-field case is covered by the hand-written fixtures below). - fn interleave(image: &[u16], w: usize, h: usize, rows: usize, cols: usize) -> Vec { - let (gh, gw) = (h / rows, w / cols); - let mut out = vec![0u16; w * h]; - for r in 0..h { - for c in 0..w { - out[((r % rows) * gh + r / rows) * w + (c % cols) * gw + c / cols] = image[r * w + c]; - } - } - out - } - - fn samples(d: &RawData) -> Vec { - match d { - RawData::U16(v) => v.clone(), - RawData::F32(_) => Vec::new(), - } - } - - /// The image `image` laid out in stored order, given the image line each stored row and column - /// holds. Written out by hand from the tag's plain reading, so it does not share a formula with - /// the code under test. - fn store(image: &[u16], w: usize, rows_img: &[usize], cols_img: &[usize]) -> Vec { - let mut out = vec![0u16; image.len()]; - for (sr, &ir) in rows_img.iter().enumerate() { - for (sc, &ic) in cols_img.iter().enumerate() { - out[sr * w + sc] = image[ir * w + ic]; - } - } - out - } - - #[test] - fn deinterleaves_an_interleaved_raster() { - // 3×3 rather than 2×2 on purpose: the 2×2 permutation is its own inverse, so a 2×2 fixture - // would pass even with the direction of the permutation reversed. This is the shape a DNG - // 1.7 file caught in the wild carried (JPEG XL, `RowInterleaveFactor`/`ColumnInterleaveFactor` - // both 2) — its real-file ground truth is that it renders bit-identical to its - // non-interleaved twin. - let (w, h, rows, cols) = (12, 9, 3, 3); - let image: Vec = (0..w * h).map(|i| i as u16).collect(); - let mut data = RawData::U16(interleave(&image, w, h, rows, cols)); - assert_ne!(samples(&data), image, "the fixture has to actually be permuted"); - deinterleave(&mut data, w, h, 1, rows, cols).unwrap(); - assert_eq!(samples(&data), image); - - // 2×2 as well, the shape Adobe's converter writes. - let (w2, h2) = (12, 8); - let image2: Vec = (0..w2 * h2).map(|i| i as u16).collect(); - let mut two = RawData::U16(interleave(&image2, w2, h2, 2, 2)); - deinterleave(&mut two, w2, h2, 1, 2, 2).unwrap(); - assert_eq!(samples(&two), image2); - } - - #[test] - fn deinterleave_pins_the_field_direction() { - // Hand-computed ground truth for the tag's plain reading ("field g holds lines g, g+n, - // g+2n, …"). The 3×3 test above round-trips against a helper written from the same reading - // of the tag, so it fixes consistency but not the direction; and a 2×2 fixture cannot tell - // the two directions apart, being its own inverse. These maps are written out literally so - // a reversed permutation fails here. 3 row fields of h = 9 start at stored rows 0, 3, 6 and - // hold image rows [0,3,6,1,4,7,2,5,8]; 2 column fields of w = 4 give [0,2,1,3]. - let (w, h) = (4, 9); - let image: Vec = (0..(w * h) as u16).collect(); - let mut data = RawData::U16(store(&image, w, &[0, 3, 6, 1, 4, 7, 2, 5, 8], &[0, 2, 1, 3])); - assert_ne!(samples(&data), image, "the fixture has to actually be permuted"); - deinterleave(&mut data, w, h, 1, 3, 2).unwrap(); - assert_eq!(samples(&data), image); - } - - #[test] - fn deinterleaves_a_raster_the_factor_does_not_divide() { - // The spec fixes the number of fields, not that the size is a multiple of it: h = 7 over 3 - // row fields is 3 + 2 + 2 (the round-robin split), so field 0 starts at stored row 0 holding - // image rows 0, 3, 6; field 1 at stored row 3 holding 1, 4; field 2 at stored row 5 holding - // 2, 5. Columns: w = 5 over 2 fields is 3 + 2 → image columns [0,2,4,1,3]. - let (w, h) = (5, 7); - let image: Vec = (0..(w * h) as u16).collect(); - let mut data = RawData::U16(store(&image, w, &[0, 3, 6, 1, 4, 2, 5], &[0, 2, 4, 1, 3])); - assert_ne!(samples(&data), image, "the fixture has to actually be permuted"); - deinterleave(&mut data, w, h, 1, 3, 2).unwrap(); - assert_eq!(samples(&data), image); - } - - #[test] - fn deinterleave_is_a_no_op_at_one_and_refuses_a_hostile_factor() { - let image: Vec = (0..48).collect(); - let mut plain = RawData::U16(image.clone()); - deinterleave(&mut plain, 8, 6, 1, 1, 1).unwrap(); - assert_eq!(samples(&plain), image); - - // A hostile factor is an error, not a scrambled image. - let mut hostile = RawData::U16(image); - assert!(deinterleave(&mut hostile, 8, 6, 1, 1 << 20, 1).is_err()); - } -} diff --git a/crates/raw/src/gaintable.rs b/crates/raw/src/gaintable.rs index c6a1b4c91e..284f3f1586 100644 --- a/crates/raw/src/gaintable.rs +++ b/crates/raw/src/gaintable.rs @@ -40,144 +40,34 @@ //! `MapPointsV` / `MapPointsH` is below 256 (their product is at most [`MAX_TABLES`]), so swapped //! it is at least 2^24 and the size checks reject it. We write in the file's byte order. -use craft_tiff::ByteOrder; +pub use craft_raw::gaintable::GainTableMap; use serde::{Deserialize, Serialize}; -/// Upper bound on `MapPointsV × MapPointsH` (Apple uses 6 × 8). -const MAX_TABLES: usize = 1 << 12; -/// Upper bound on the total number of gains (Apple: 6 × 8 × 257 = 12 336). -const MAX_GAINS: usize = 1 << 22; -/// A parsed `ProfileGainTableMap` / `ProfileGainTableMap2`. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct GainTableMap { - /// Tables vertically (`MapPointsV`) and horizontally (`MapPointsH`), and points per table (`MapPointsN`). - pub points_v: usize, - pub points_h: usize, - pub points_n: usize, - /// Grid spacing and origin, relative to the active area's height (`_v`) and width (`_h`). - pub spacing_v: f64, - pub spacing_h: f64, - pub origin_v: f64, - pub origin_h: f64, - /// Weights of (R, G, B, min, max) for the table input. - pub weights: [f32; 5], - /// Exponent for the table input (1.0 for the version-1 tag). - pub gamma: f32, - /// `points_v × points_h × points_n` gains, row-major with the table points innermost. Integer - /// storage has already been mapped onto `GainMin..=GainMax`. Mapping before interpolating is - /// the same as mapping after, because the mapping is linear. - pub gains: Vec, -} -impl GainTableMap { - /// Parse the tag's bytes from a file in byte order `order` (`version2`: `ProfileGainTableMap2`): - /// in that order, else big-endian (see the module docs). `None` when malformed. - pub fn parse(b: &[u8], order: ByteOrder, version2: bool) -> Option { - Self::parse_in(b, order, version2).or_else(|| if order == ByteOrder::Big { None } else { Self::parse_in(b, ByteOrder::Big, version2) }) - } - - /// Parse the tag's bytes with every multi-byte field in `order`. - fn parse_in(b: &[u8], order: ByteOrder, version2: bool) -> Option { - let take = |o: usize, n: usize| b.get(o..o.checked_add(n)?); - let u32_at = |o: usize| take(o, 4).and_then(|s| s.try_into().ok()).map(|a: [u8; 4]| order.u32(a)); - let f32_at = |o: usize| u32_at(o).map(f32::from_bits); - let f64_at = |o: usize| take(o, 8).and_then(|s| s.try_into().ok()).map(|a: [u8; 8]| f64::from_bits(order.u64(a))); - let (points_v, points_h) = (u32_at(0)? as usize, u32_at(4)? as usize); - let (spacing_v, spacing_h, origin_v, origin_h) = (f64_at(8)?, f64_at(16)?, f64_at(24)?, f64_at(32)?); - let points_n = u32_at(40)? as usize; - let mut weights = [0f32; 5]; - for (i, w) in weights.iter_mut().enumerate() { - *w = f32_at(44 + 4 * i)?; - } - let tables = points_v.checked_mul(points_h).filter(|&t| t > 0 && t <= MAX_TABLES)?; - let count = tables.checked_mul(points_n).filter(|&c| c > 0 && c <= MAX_GAINS)?; - let spacing_ok = |s: f64, points: usize| s.is_finite() && (s > 0.0 || points == 1); - if !spacing_ok(spacing_v, points_v) - || !spacing_ok(spacing_h, points_h) - || !origin_v.is_finite() - || !origin_h.is_finite() - || !weights.iter().all(|w| w.is_finite()) - { - return None; - } - let (header, data_type, gamma, gain_min, gain_max) = - if version2 { (80, u32_at(64)?, f32_at(68)?, f32_at(72)?, f32_at(76)?) } else { (64, 3, 1.0, 0.0, 1.0) }; - if !(0.25..=4.0).contains(&gamma) { - return None; - } - let width = match data_type { - 0 => 1, - 1 | 2 => 2, - 3 => 4, - _ => return None, - }; - if b.len() != count.checked_mul(width)?.checked_add(header)? { - return None; - } - let data = b.get(header..)?; - let scaled = |q: f32, max: f32| gain_min + q / max * (gain_max - gain_min); - let gains: Vec = match data_type { - 0 => data.iter().map(|&q| scaled(q as f32, 255.0)).collect(), - 1 => data.as_chunks::<2>().0.iter().map(|c| scaled(order.u16(*c) as f32, 65535.0)).collect(), - 2 => data.as_chunks::<2>().0.iter().map(|c| crate::unpack::f16_to_f32(order.u16(*c))).collect(), - _ => data.as_chunks::<4>().0.iter().map(|c| f32::from_bits(order.u32(*c))).collect(), - }; - if gains.len() != count || !gains.iter().all(|g| g.is_finite() && *g >= 0.0) { - return None; - } - Some(GainTableMap { points_v, points_h, points_n, spacing_v, spacing_h, origin_v, origin_h, weights, gamma, gains }) - } - - /// The tag's bytes in `order`: version 1 (DNG 1.6, f32 gains) when the gamma is 1, else - /// version 2 with f32 gains. Returns `(version2, bytes)`. - pub fn to_bytes(&self, order: ByteOrder) -> (bool, Vec) { - let version2 = self.gamma != 1.0; - let mut out = Vec::with_capacity(80 + 4 * self.gains.len()); - let u32b = |v: u32| match order { - ByteOrder::Big => v.to_be_bytes(), - ByteOrder::Little => v.to_le_bytes(), - }; - let f64b = |v: f64| match order { - ByteOrder::Big => v.to_be_bytes(), - ByteOrder::Little => v.to_le_bytes(), - }; - let dim = |v: usize| u32b(u32::try_from(v).unwrap_or(u32::MAX)); - out.extend_from_slice(&dim(self.points_v)); - out.extend_from_slice(&dim(self.points_h)); - for v in [self.spacing_v, self.spacing_h, self.origin_v, self.origin_h] { - out.extend_from_slice(&f64b(v)); - } - out.extend_from_slice(&dim(self.points_n)); - for w in self.weights { - out.extend_from_slice(&u32b(w.to_bits())); - } - if version2 { - // DataType 3 (f32); GainMin/GainMax are ignored for float data - for v in [3, self.gamma.to_bits(), 0f32.to_bits(), 1f32.to_bits()] { - out.extend_from_slice(&u32b(v)); - } - } - for g in &self.gains { - out.extend_from_slice(&u32b(g.to_bits())); - } - (version2, out) - } +/// Applying a gain table map (the map, and reading and writing its tag, is `craft-raw`'s). +pub trait GainTableMapApply { + /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) + /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, + /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. + fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32; + /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). + fn evaluator(&self) -> Option>; } /// Applying the map (see the module docs). Index arithmetic saturates and every lookup is /// checked: the fields are public and the struct is deserializable, so a hand-built or damaged map /// must not overflow or panic, whatever it holds. -impl GainTableMap { +impl GainTableMapApply for GainTableMap { /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. - pub fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { + fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { self.evaluator().map_or(1.0, |e| e.gain(p, x, y)) } /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). - pub fn evaluator(&self) -> Option> { + fn evaluator(&self) -> Option> { let n = self.points_n; let tables = self.points_v.saturating_mul(self.points_h); if n == 0 || tables == 0 || tables.saturating_mul(n) != self.gains.len() { @@ -234,7 +124,7 @@ pub struct GainEval<'a> { } impl GainEval<'_> { - /// [`GainTableMap::gain`]. + /// [`GainTableMapApply::gain`]. #[inline] pub fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { let m = self.map; @@ -274,7 +164,7 @@ fn input(m: &GainTableMap, p: [f32; 3]) -> f32 { if m.gamma == 1.0 { x } else { x.powf(m.gamma) } } -/// Where the pixels of a developed source sit in the raw's active area, for [`GainTableMap::gain`]. +/// Where the pixels of a developed source sit in the raw's active area, for [`GainTableMapApply::gain`]. /// The source is the default crop of the active area (`rect`, relative to the active area), /// then EXIF-`orientation`ed. Resolution independent. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/raw/src/hotpixel.rs b/crates/raw/src/hotpixel.rs index aa6131b18b..e0768eec40 100644 --- a/crates/raw/src/hotpixel.rs +++ b/crates/raw/src/hotpixel.rs @@ -140,7 +140,7 @@ impl RawImage { let black = self.black.mean(); let RawData::U16(d) = &mut self.data else { return 0 }; if self.cpp != 1 - || !cfa.valid() + || !crate::cfa_valid(cfa) || w.checked_mul(h) != Some(d.len()) || a.width < 4 * MARGIN || a.height < 4 * MARGIN diff --git a/crates/raw/src/jxl.rs b/crates/raw/src/jxl.rs deleted file mode 100644 index 128f4eeea9..0000000000 --- a/crates/raw/src/jxl.rs +++ /dev/null @@ -1,574 +0,0 @@ -//! JPEG XL tiles and strips (DNG 1.7 compression 52546), decoded with `jxl-oxide` (pure Rust). -//! -//! Per the DNG 1.7 specification a JPEG XL chunk holds N-bit unsigned integers (8 ≤ N ≤ 16) or 16-bit -//! floats, in 1 or 3 planes, as either a bare codestream or an ISO-BMFF container; jxl-oxide reads both. -//! -//! jxl-oxide renders every channel as `f32`: integer samples come out as `value / (2^bits − 1)` with -//! `bits` the codestream's own declared bit depth, so scaling back by that maximum and rounding gives the -//! stored integers exactly (an `f32` holds `v / 65535` to far better than half a code value) — lossless -//! tiles decode bit-exactly, whatever bit depth the encoder declared relative to the IFD's -//! `BitsPerSample`. Float samples are returned as decoded. -//! -//! Lossless (non-XYB) tiles are rendered in the codestream's own colour encoding, which is the identity, -//! keeping the values in the raw IFD's sample space. Lossy (XYB) tiles are decoded by jxl-oxide to linear -//! sRGB primaries; the codestream's declared encoding is then restored by hand: its primaries with a -//! plain 3×3 matrix, then its transfer curve. A grey (single-plane) lossy tile is still coded as three -//! XYB channels; its declared grey encoding is restored as the luminance (CIE Y, D65 white) of the -//! linear sRGB output, then its transfer curve. The samples of a lossy tile mean what they would in a -//! lossless one with the same header, so a declared transfer curve is part of the stored values, not a -//! display hint. Lightroom Classic's lossy LinearRaw DNGs (Convert to DNG with lossy compression) store -//! perceptually shaped samples, label them with the sRGB curve and linearise them with a cubic -//! `MapPolynomial` per plane in `OpcodeList2`. Measured against Lightroom's own preview of two such -//! files, the polynomial applied to the samples in the declared encoding tracks Lightroom's rendering -//! (midtone log-log slope 0.98 and 1.38, about 1 EV apart); applied to the decoder's linear output it is -//! 3.6 EV too dark. We never let jxl-oxide convert to the declared encoding itself: -//! that step gamut-maps and clips to [0, 1], which destroys raw values above 1.0 (a `WhiteLevel` of -//! 32768 puts them far above) and desaturates. The result is the sample space the DNG's `WhiteLevel` -//! refers to, up to the codec's loss, and can exceed 1.0 or dip below 0. -//! -//! Every tile is decoded with wide (32-bit) modular buffers. A lossy tile whose header sets -//! `modular_16bit_buffers` can still carry values that need more than 16 bits; the narrow buffers then -//! fail with `InvalidAnsStream` or `UnexpectedEof`. - -use crate::tiffraw::ChunkPx; -use crate::{RawError, Result}; -use jxl_oxide::color::{ColourEncoding, ColourSpace, Primaries, TransferFunction, WhitePoint}; -use jxl_oxide::frame::Encoding; -use jxl_oxide::image::BitDepth; -use jxl_oxide::{AllocTracker, EnumColourEncoding, JxlImage, JxlThreadPool, RenderingIntent}; - -/// Decoder memory (bytes) allowed per sample of a tile. jxl-oxide 0.12 peaks at about three 32-bit -/// buffers per sample: measured ≤ 10.3 bytes for lossless (modular) tiles and ≤ 13.5 bytes per -/// colour sample for lossy (VarDCT) ones, photon noise included. -const BYTES_PER_SAMPLE: usize = 16; -/// Fixed decoder overhead on top (headers, entropy-coding tables, group metadata): under 10 KiB -/// on a 16 × 16 tile. -const MARGIN_BYTES: usize = 64 << 10; - -/// Linear sRGB primaries with a D65 white point (the space jxl-oxide decodes XYB to) and the matrix that -/// takes a linear colour in it to the codestream's declared primaries (row-major, D65 white point). -type Matrix = [[f64; 3]; 3]; - -const D65: [f64; 2] = [0.3127, 0.3290]; -const SRGB: [[f64; 2]; 3] = [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]]; -const BT2100: [[f64; 2]; 3] = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]]; -const P3: [[f64; 2]; 3] = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]]; - -fn inverse(m: Matrix) -> Matrix { - let c = - |i: usize, j: usize| m[(i + 1) % 3][(j + 1) % 3] * m[(i + 2) % 3][(j + 2) % 3] - m[(i + 1) % 3][(j + 2) % 3] * m[(i + 2) % 3][(j + 1) % 3]; - let det = m[0][0] * c(0, 0) + m[0][1] * c(0, 1) + m[0][2] * c(0, 2); - let mut out = [[0.0; 3]; 3]; - for (i, row) in out.iter_mut().enumerate() { - for (j, v) in row.iter_mut().enumerate() { - *v = c(j, i) / det; - } - } - out -} - -fn mul(a: Matrix, b: Matrix) -> Matrix { - let mut out = [[0.0; 3]; 3]; - for (i, row) in out.iter_mut().enumerate() { - for (j, v) in row.iter_mut().enumerate() { - *v = (0..3).map(|k| a[i][k] * b[k][j]).sum(); - } - } - out -} - -/// Linear RGB → XYZ for primaries `p` (xy) and the D65 white point. -fn rgb_to_xyz(p: [[f64; 2]; 3]) -> Matrix { - let xyz = |[x, y]: [f64; 2]| [x / y, 1.0, (1.0 - x - y) / y]; - let cols = [xyz(p[0]), xyz(p[1]), xyz(p[2])]; - let prim = [[cols[0][0], cols[1][0], cols[2][0]], [1.0, 1.0, 1.0], [cols[0][2], cols[1][2], cols[2][2]]]; - let w = xyz(D65); - let inv = inverse(prim); - let s: [f64; 3] = std::array::from_fn(|i| (0..3).map(|k| inv[i][k] * w[k]).sum()); - std::array::from_fn(|i| std::array::from_fn(|j| prim[i][j] * s[j])) -} - -/// A declared transfer curve, applied to linear values (linear → coded). Mirrored for negative values -/// and not clipped above 1.0, so lossy undershoot and raw values above white survive. -#[derive(Debug, Clone, Copy, PartialEq)] -enum Curve { - Linear, - /// IEC 61966-2-1 (sRGB). - Srgb, - /// ITU-R BT.709. - Bt709, - /// A pure power: coded = linear^exponent. - Power(f32), -} - -impl Curve { - fn encode(self, v: f32) -> f32 { - let a = v.abs(); - let e = match self { - Curve::Linear => return v, - Curve::Srgb if a <= 0.003_130_8 => 12.92 * a, - Curve::Srgb => 1.055 * a.powf(1.0 / 2.4) - 0.055, - Curve::Bt709 if a < 0.018 => 4.5 * a, - Curve::Bt709 => 1.099 * a.powf(0.45) - 0.099, - Curve::Power(p) => a.powf(p), - }; - e.copysign(v) - } -} - -/// How a chunk is rendered by jxl-oxide. -#[derive(Debug, Clone, Copy, PartialEq)] -enum Output { - /// In the codestream's own colour encoding (non-XYB: the identity). - AsCoded, - /// XYB (lossy) data: linear sRGB primaries from the decoder, then `matrix` to the declared - /// primaries (`None` when those are sRGB's), then the declared transfer `curve`. - FromXyb { matrix: Option<[[f32; 3]; 3]>, curve: Curve }, -} - -/// Decide how to render a chunk from its header: whether it is XYB-coded, the declared colour -/// encoding and the intensity target. Lossy data is only accepted when the declared encoding is an RGB -/// one (three planes) or a grey one (one plane) with a D65 white point and an SDR transfer curve (linear, sRGB, BT.709 or a power: what raw DNG -/// writers signal) and no HDR tone mapping would apply, otherwise the samples cannot be restored -/// faithfully. -fn output_for(xyb: bool, encoding: &ColourEncoding, intensity_target: f32, planes: usize) -> Result { - if !xyb { - return Ok(Output::AsCoded); - } - let unsupported = |what: &str| RawError::Unsupported(format!("lossy JPEG XL tile with {what}")); - let ColourEncoding::Enum(e) = encoding else { - return Err(unsupported("an ICC profile instead of a colour encoding")); - }; - // a single plane is declared grey, three are declared RGB (the header's grey flag is the colour space) - let grey = planes == 1; - if grey && e.colour_space != ColourSpace::Grey { - return Err(unsupported("a single colour plane that is not declared grey")); - } - if !grey && e.colour_space != ColourSpace::Rgb { - return Err(unsupported("a declared encoding that is not RGB")); - } - let curve = match e.tf { - TransferFunction::Linear => Curve::Linear, - TransferFunction::Srgb => Curve::Srgb, - TransferFunction::Bt709 => Curve::Bt709, - TransferFunction::Dci => Curve::Power(1.0 / 2.6), - // as jxl-oxide reads it: a codestream's gamma is the encoding exponent (×1e7) with `inverted` - TransferFunction::Gamma { g, inverted } => { - let g = g as f32 / 1e7; - Curve::Power(if inverted { g } else { 1.0 / g }) - } - TransferFunction::Pq | TransferFunction::Hlg => return Err(unsupported("an HDR transfer curve (PQ or HLG)")), - TransferFunction::Unknown => return Err(unsupported("an unknown transfer curve")), - }; - if let Curve::Power(p) = curve - && !(p.is_finite() && p > 0.0) - { - return Err(unsupported("an invalid gamma")); - } - if e.white_point != WhitePoint::D65 { - return Err(unsupported("a white point other than D65")); - } - if intensity_target > 255.0 { - return Err(unsupported("an intensity target above 255 nits")); - } - if grey { - // a grey encoding has no primaries, only the white point: its single plane is the luminance (CIE Y) - // of the decoder's linear sRGB, which is the row of sRGB → XYZ that gives Y. The rows of the - // matrix are all that row; only the first is used for one plane. - let y = rgb_to_xyz(SRGB)[1].map(|v| v as f32); - return Ok(Output::FromXyb { matrix: Some([y; 3]), curve }); - } - let primaries = match e.primaries { - Primaries::Srgb => return Ok(Output::FromXyb { matrix: None, curve }), - Primaries::Bt2100 => BT2100, - Primaries::P3 => P3, - Primaries::Custom { red, green, blue } => [red, green, blue].map(|c| c.as_float().map(f64::from)), - }; - if primaries.iter().any(|p| p[1] <= 0.0) { - return Err(unsupported("invalid primaries")); - } - let m = mul(inverse(rgb_to_xyz(primaries)), rgb_to_xyz(SRGB)); - if m.iter().flatten().any(|v| !v.is_finite()) { - return Err(unsupported("degenerate primaries")); - } - Ok(Output::FromXyb { matrix: Some(m.map(|r| r.map(|v| v as f32))), curve }) -} - -fn corrupt(e: impl std::fmt::Display) -> RawError { - RawError::Corrupt(format!("JPEG XL tile: {e}")) -} - -/// Parse a chunk's headers (no pixel decoding) and check them against the chunk it must fill: -/// nominal `cw × ch`, or the part of it inside the image `vw × vh` (edge tiles), `cpp` colour planes, -/// a sample type matching the IFD. Returns the decoder and the codestream's integer maximum (0 for float). -#[allow(clippy::too_many_arguments)] -fn open(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result<(JxlImage, f32, Output)> { - if !matches!(cpp, 1 | 3) { - return Err(RawError::Unsupported(format!("JPEG XL with {cpp} samples per pixel"))); - } - if float && bits != 16 || !float && !(8..=16).contains(&bits) { - return Err(RawError::Unsupported(format!("JPEG XL with {bits}-bit {} samples", if float { "float" } else { "integer" }))); - } - // The decoder's memory is bounded by the tile itself: a codestream that needs more (extra - // channels, layers, …) fails to decode instead of allocating what its header asks for. - let pixels = cw.saturating_mul(ch); - let budget = |planes: usize| pixels.saturating_mul(planes).saturating_mul(BYTES_PER_SAMPLE); - let tracker = AllocTracker::with_limit(budget(cpp).saturating_add(MARGIN_BYTES)); - let mut img = JxlImage::builder() - .pool(JxlThreadPool::none()) // chunks are already decoded in parallel - .force_wide_buffers(true) // see the module documentation - .alloc_tracker(tracker.clone()) - .read(std::io::Cursor::new(src)) - .map_err(corrupt)?; - // lossy (VarDCT) decoding always works on three colour channels, even for a grey tile - if cpp == 1 && img.frame_header(0).is_some_and(|f| f.encoding == Encoding::VarDct) { - tracker.expand_limit(budget(2)); - } - let header = img.image_header(); - let (jw, jh) = (img.width() as usize, img.height() as usize); - if (jw, jh) != (cw, ch) && (jw, jh) != (vw, vh) { - return Err(RawError::Corrupt(format!("JPEG XL tile is {jw}×{jh}, expected {cw}×{ch} (or {vw}×{vh} at the image edge)"))); - } - if header.metadata.orientation != 1 { - return Err(RawError::Corrupt("JPEG XL tile with a non-identity orientation".into())); - } - let planes = if header.metadata.grayscale() { 1 } else { 3 }; - if planes != cpp { - return Err(RawError::Corrupt(format!("JPEG XL tile has {planes} colour planes, the IFD {cpp} samples per pixel"))); - } - let max = match header.metadata.bit_depth { - BitDepth::IntegerSample { bits_per_sample } if !float && (1..=16).contains(&bits_per_sample) => ((1u32 << bits_per_sample) - 1) as f32, - BitDepth::FloatSample { .. } if float => 0.0, - d => return Err(RawError::Corrupt(format!("JPEG XL tile sample type {d:?} does not match the IFD"))), - }; - let output = output_for(header.metadata.xyb_encoded, &header.metadata.colour_encoding, header.metadata.tone_mapping.intensity_target, planes)?; - if matches!(output, Output::FromXyb { .. }) { - img.request_color_encoding(EnumColourEncoding::srgb_linear(RenderingIntent::Relative)); - } - Ok((img, max, output)) -} - -/// Check the first chunk's headers ([`open`]) without decoding pixels (header-only probing). -#[allow(clippy::too_many_arguments)] -pub(crate) fn check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result<()> { - open(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ()) -} - -/// Decode one chunk into `cw × ch × cpp` samples (row-major, interleaved); a chunk coded at its -/// in-image size `vw × vh` fills the top-left of that, the rest stays 0. -#[allow(clippy::too_many_arguments)] -pub(crate) fn decode(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result { - let (img, max, output) = open(src, cw, ch, vw, vh, cpp, bits, float)?; - if img.num_loaded_keyframes() == 0 { - return Err(corrupt("no complete frame")); - } - let render = img.render_frame(0).map_err(corrupt)?; - let fb = render.image_all_channels(); - let (jw, jh, fc) = (fb.width(), fb.height(), fb.channels()); - if jw == 0 || jh == 0 || jw > cw || jh > ch || fc < cpp { - return Err(corrupt(format!("rendered {jw}×{jh}×{fc}, expected {cw}×{ch}×{cpp}"))); - } - let n = cw.saturating_mul(ch).saturating_mul(cpp); - let rows = fb.buf().chunks_exact(jw * fc); - // lossy data: restore the declared primaries and transfer curve (see the module documentation) - let (matrix, curve) = match output { - Output::FromXyb { matrix, curve } => (matrix, curve), - Output::AsCoded => (None, Curve::Linear), - }; - let restore = |s: &[f32], d: &mut [f32]| { - match matrix { - Some(m) => { - for (d, row) in d.iter_mut().zip(&m) { - *d = row[0] * s[0] + row[1] * s[1] + row[2] * s[2]; - } - } - None => d.copy_from_slice(&s[..cpp]), - } - if curve != Curve::Linear { - d.iter_mut().for_each(|v| *v = curve.encode(*v)); - } - }; - Ok(if float { - let mut out = vec![0f32; n]; - for (dst, src) in out.chunks_exact_mut(cw * cpp).zip(rows) { - for (d, s) in dst.chunks_exact_mut(cpp).zip(src.chunks_exact(fc)) { - restore(s, d); - } - } - ChunkPx::F32(out) - } else { - let mut out = vec![0u16; n]; - let mut px = [0f32; 3]; - for (dst, src) in out.chunks_exact_mut(cw * cpp).zip(rows) { - for (d, s) in dst.chunks_exact_mut(cpp).zip(src.chunks_exact(fc)) { - restore(s, &mut px[..cpp]); - // `as` saturates (NaN → 0): lossy overshoot clips to the integer range - d.iter_mut().zip(&px).for_each(|(d, s)| *d = (s * max).round() as u16); - } - } - ChunkPx::U16(out) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use jxl_oxide::color::Customxy; - - fn linear(primaries: Primaries) -> ColourEncoding { - ColourEncoding::Enum(EnumColourEncoding { - colour_space: ColourSpace::Rgb, - white_point: WhitePoint::D65, - primaries, - tf: TransferFunction::Linear, - rendering_intent: RenderingIntent::Perceptual, - }) - } - - fn matrix(o: Output) -> [[f32; 3]; 3] { - match o { - Output::FromXyb { matrix: Some(m), .. } => m, - other => panic!("expected a matrix, got {other:?}"), - } - } - - #[test] - fn data_that_is_not_xyb_is_rendered_as_coded() { - // lossless tiles: whatever the header declares, the decoder must not convert anything - for e in - [linear(Primaries::Srgb), linear(Primaries::Bt2100), ColourEncoding::Enum(EnumColourEncoding::srgb_gamma22(RenderingIntent::Relative))] - { - assert_eq!(output_for(false, &e, 255.0, 3).unwrap(), Output::AsCoded); - assert_eq!(output_for(false, &e, 10_000.0, 1).unwrap(), Output::AsCoded); - } - } - - #[test] - fn lossy_data_with_srgb_primaries_needs_no_matrix() { - assert_eq!(output_for(true, &linear(Primaries::Srgb), 255.0, 3).unwrap(), Output::FromXyb { matrix: None, curve: Curve::Linear }); - } - - #[test] - fn lossy_grey_data_is_the_luminance_in_the_declared_curve() { - // Lightroom Classic's merged monochrome LinearRaw DNGs: one plane, declared grey with a linear - // (16-bit float) or an sRGB (16-bit integer) curve - let grey = |tf| { - let mut e = EnumColourEncoding::srgb_linear(RenderingIntent::Perceptual); - e.colour_space = ColourSpace::Grey; - e.tf = tf; - output_for(true, &ColourEncoding::Enum(e), 255.0, 1).unwrap() - }; - let Output::FromXyb { matrix: Some(m), curve: Curve::Linear } = grey(TransferFunction::Linear) else { panic!("grey, linear") }; - // the luminance of linear sRGB (IEC 61966-2-1: 0.2126, 0.7152, 0.0722); white stays white - for (v, e) in m[0].iter().zip([0.2126, 0.7152, 0.0722]) { - assert!((v - e).abs() < 1e-4, "{m:?}"); - } - assert!((m[0].iter().sum::() - 1.0).abs() < 1e-5, "{m:?}"); - assert!(matches!(grey(TransferFunction::Srgb), Output::FromXyb { curve: Curve::Srgb, .. })); - } - - #[test] - fn lossy_data_keeps_the_declared_transfer_curve() { - // Lightroom Classic's lossy LinearRaw DNGs: Rec.2100 primaries, sRGB transfer curve - let mut e = EnumColourEncoding::srgb_linear(RenderingIntent::Perceptual); - e.primaries = Primaries::Bt2100; - e.tf = TransferFunction::Srgb; - let curve = |tf| { - let mut e = e.clone(); - e.tf = tf; - match output_for(true, &ColourEncoding::Enum(e), 255.0, 3).unwrap() { - Output::FromXyb { matrix: Some(_), curve } => curve, - other => panic!("expected a matrix and a curve, got {other:?}"), - } - }; - assert_eq!(curve(TransferFunction::Srgb), Curve::Srgb); - assert_eq!(curve(TransferFunction::Bt709), Curve::Bt709); - assert_eq!(curve(TransferFunction::Dci), Curve::Power(1.0 / 2.6)); - // a codestream's gamma (as read: inverted) is the encoding exponent; jxl-oxide's own γ 2.2 is not - assert_eq!(curve(TransferFunction::Gamma { g: 4_545_455, inverted: true }), Curve::Power(0.454_545_5)); - assert_eq!(curve(TransferFunction::Gamma { g: 22_000_000, inverted: false }), Curve::Power(1.0 / 2.2)); - } - - #[test] - fn transfer_curves_encode_unclipped_and_mirrored() { - let close = |a: f32, b: f32| (a - b).abs() < 1e-4; - // sRGB: linear toe, 18 % grey, white, and the toe/power junction is continuous - assert!(close(Curve::Srgb.encode(0.002), 0.002 * 12.92)); - assert!(close(Curve::Srgb.encode(0.18), 0.461_356)); - assert!(close(Curve::Srgb.encode(1.0), 1.0)); - assert!(close(Curve::Srgb.encode(0.003_130_8), Curve::Srgb.encode(0.003_130_9))); - assert!(close(Curve::Bt709.encode(1.0), 1.0)); - assert!((Curve::Bt709.encode(0.017_999) - Curve::Bt709.encode(0.018)).abs() < 1e-3); - assert!(close(Curve::Power(0.5).encode(0.25), 0.5)); - // raw values above white keep growing, lossy undershoot keeps its sign, linear is the identity - assert!(Curve::Srgb.encode(2.0) > 1.3); - assert!(close(Curve::Srgb.encode(-0.18), -0.461_356)); - assert_eq!(Curve::Linear.encode(-3.5), -3.5); - assert_eq!(Curve::Power(0.5).encode(0.0), 0.0); - } - - #[test] - fn lossy_data_is_restored_to_the_declared_primaries() { - // linear sRGB to linear BT.2020/BT.2100 primaries (D65), as published in ITU-R BT.2087 - let expect = [[0.6274, 0.3293, 0.0433], [0.0691, 0.9195, 0.0114], [0.0164, 0.0880, 0.8956]]; - let m = matrix(output_for(true, &linear(Primaries::Bt2100), 255.0, 3).unwrap()); - for (r, e) in m.iter().zip(&expect) { - for (v, e) in r.iter().zip(e) { - assert!((v - e).abs() < 1e-3, "{m:?}"); - } - // the white point maps to itself: rows sum to one - assert!((r.iter().sum::() - 1.0).abs() < 1e-5, "{m:?}"); - } - // custom primaries equal to the named ones give the same matrix - let xy = |[x, y]: [f64; 2]| Customxy { x: (x * 1e6) as i32, y: (y * 1e6) as i32 }; - let custom = Primaries::Custom { red: xy(BT2100[0]), green: xy(BT2100[1]), blue: xy(BT2100[2]) }; - let c = matrix(output_for(true, &linear(custom), 255.0, 3).unwrap()); - assert!(c.iter().flatten().zip(m.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-5), "{c:?} {m:?}"); - // the sRGB primaries lie inside the wider P3 gamut: the full-saturation sRGB green is a valid P3 colour - let inv = matrix(output_for(true, &linear(Primaries::P3), 255.0, 3).unwrap()); - let srgb_green_in_p3 = [inv[0][1], inv[1][1], inv[2][1]]; - assert!(srgb_green_in_p3.iter().all(|v| (0.0..=1.0).contains(v)), "sRGB green lies inside P3"); - } - - // 16 × 16 RGB tiles of 16-bit samples coded lossily (XYB) by libjxl at distance 0.5, each declaring BT.2020 - // primaries, a D65 white point and the named transfer curve. The samples are [`gradient`]; generated for these - // tests (original work). - const SRGB_TILE: &[u8] = &[ - 0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0xc7, 0x8d, 0x00, 0x13, 0x08, 0x00, 0xf0, 0x01, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50, 0xa1, 0x32, 0xca, - 0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36, 0xdb, 0x0b, 0x83, - 0x84, 0x84, 0x33, 0x70, 0xde, 0x90, 0x97, 0xbd, 0x79, 0x64, 0xe4, 0x3b, 0x62, 0xaf, 0x1b, 0xb2, 0x74, 0xf6, 0x36, 0x43, 0x17, 0x72, 0xe7, - 0x31, 0x86, 0xb6, 0x41, 0x1c, 0x00, 0x15, 0x52, 0x20, 0x11, 0x70, 0xcb, 0x46, 0x32, 0x92, 0x65, 0xcd, 0xc8, 0x18, 0xc9, 0x48, 0xe6, 0x49, - 0xe6, 0x4f, 0x94, 0x35, 0xc7, 0x5c, 0x91, 0xb0, 0x5d, 0xdf, 0x2b, 0x9b, 0x93, 0x3b, 0xb6, 0x70, 0x7d, 0x24, 0xf0, 0xdd, 0x26, 0xb2, 0x26, - 0xdf, 0x49, 0x5f, 0xd4, 0xaa, 0x1c, 0x8f, 0x7d, 0xc4, 0xf2, 0x6a, 0xd2, 0x27, 0x86, 0x93, 0xe7, 0x15, 0x9a, 0x01, 0x60, 0x84, 0xc0, 0x09, - ]; - const BT709_TILE: &[u8] = &[ - 0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0xa7, 0x08, 0x00, 0x13, 0x08, 0x00, 0xe8, 0x01, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50, 0xa1, 0x32, 0xca, - 0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36, 0xdb, 0x0b, 0x83, - 0x84, 0x84, 0x33, 0xd8, 0x9c, 0x32, 0xe2, 0x85, 0x6f, 0x3e, 0x6c, 0xa2, 0x1c, 0xaa, 0xdf, 0x1b, 0x32, 0xf4, 0xef, 0x36, 0xe3, 0x96, 0xf2, - 0xe0, 0x65, 0xe8, 0x15, 0xc4, 0x01, 0x50, 0x21, 0x05, 0xd2, 0x00, 0xd8, 0x8c, 0x8c, 0x14, 0x59, 0xc9, 0x31, 0x32, 0x46, 0x52, 0x60, 0x82, - 0x71, 0x03, 0xd9, 0xff, 0x8a, 0x3e, 0x7c, 0xb4, 0xc1, 0xa8, 0x49, 0xfa, 0x83, 0xa8, 0x74, 0xd7, 0x1d, 0xa8, 0xb4, 0x25, 0x67, 0xc1, 0x83, - 0x93, 0x3a, 0xf3, 0x81, 0xb5, 0x2f, 0x44, 0x50, 0x35, 0x36, 0x68, 0x1c, 0xf9, 0x20, 0x17, 0x98, 0x87, 0x1d, 0x83, 0xb0, 0x02, - ]; - const GAMMA22_TILE: &[u8] = &[ - 0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0xf7, 0x75, 0xab, 0x28, 0x02, 0x00, 0x13, 0x08, 0x00, 0xf8, 0x01, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50, - 0xa1, 0x32, 0xca, 0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36, - 0xdb, 0x0b, 0x83, 0x84, 0x84, 0x33, 0xd8, 0x9c, 0x02, 0xed, 0x85, 0x6f, 0x3e, 0x2c, 0x72, 0x1e, 0xb8, 0xe3, 0x3b, 0x12, 0x75, 0xf8, 0x4e, - 0xa3, 0x97, 0x71, 0xea, 0x31, 0x43, 0xa7, 0x20, 0x0e, 0x80, 0x0a, 0x29, 0x90, 0x08, 0xc0, 0x8a, 0x8c, 0x8a, 0x64, 0x74, 0x59, 0x45, 0xc6, - 0x48, 0x46, 0x32, 0x4c, 0x32, 0x4c, 0xa0, 0xa5, 0x39, 0x23, 0xff, 0xdf, 0xcd, 0xf9, 0x33, 0x93, 0x5c, 0xb4, 0xec, 0xc1, 0x06, 0xf5, 0xcc, - 0x92, 0x12, 0xf4, 0xbb, 0xef, 0x15, 0x84, 0xc7, 0xf2, 0xf1, 0x48, 0xfc, 0x80, 0xb9, 0x7a, 0xab, 0x58, 0x3e, 0x79, 0x3a, 0xcf, 0x67, 0xc7, - 0xd3, 0xfc, 0x80, 0x60, 0x00, - ]; - const LINEAR_TILE: &[u8] = &[ - 0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0x47, 0x8b, 0x00, 0x13, 0x08, 0x00, 0x14, 0x02, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50, 0xa1, 0x32, 0xca, - 0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36, 0xdb, 0x0b, 0x83, - 0x84, 0x84, 0x43, 0xd8, 0x36, 0xe1, 0xbe, 0x88, 0x9b, 0x27, 0x48, 0x71, 0x04, 0xe2, 0xeb, 0x4e, 0xf9, 0x74, 0x9d, 0xe7, 0x00, 0x8d, 0x74, - 0xcb, 0xc0, 0xe0, 0x5d, 0x58, 0x10, 0x80, 0x0a, 0x29, 0x90, 0x06, 0xd8, 0xac, 0x18, 0x19, 0x45, 0xc5, 0x28, 0x89, 0x8a, 0x24, 0xd3, 0xff, - 0xff, 0x1c, 0xc4, 0x2f, 0xd8, 0x26, 0x80, 0x6c, 0xe1, 0xc3, 0xbe, 0xef, 0xab, 0xe1, 0x79, 0x1e, 0xff, 0x1b, 0x2e, 0x57, 0xf7, 0x2c, 0x1f, - 0x1f, 0xf8, 0xec, 0xd3, 0x33, 0x21, 0x9e, 0x12, 0x22, 0x43, 0xc2, 0xfd, 0xb3, 0xf2, 0xe0, 0x40, 0xdf, 0x25, 0x0f, 0x67, 0xe7, 0xca, 0x7e, - 0xa5, 0x7f, 0x1f, 0x21, 0xa4, 0x6a, 0x1e, 0xa0, 0x0e, - ]; - - /// The samples the fixture tiles were coded from: `(x, y)` → RGB. - fn gradient(x: usize, y: usize) -> [f32; 3] { - let (x, y) = (x as f32, y as f32); - [4000.0 + x * 3500.0, 6000.0 + y * 3200.0, 30000.0 + (x - y) * 1500.0] - } - - #[test] - fn lossy_tiles_decode_to_their_samples_whatever_sdr_curve_they_declare() { - for (name, tile) in [("sRGB", SRGB_TILE), ("BT.709", BT709_TILE), ("gamma 2.2", GAMMA22_TILE), ("linear", LINEAR_TILE)] { - let ChunkPx::U16(px) = decode(tile, 16, 16, 16, 16, 3, 16, false).unwrap() else { panic!("{name}: integer samples") }; - let (mut sum, mut worst) = (0.0f32, 0.0f32); - for (i, p) in px.as_chunks::<3>().0.iter().enumerate() { - for (got, want) in p.iter().zip(gradient(i % 16, i / 16)) { - let err = (f32::from(*got) - want).abs(); - sum += err; - worst = worst.max(err); - } - } - // the reference decoder (libjxl) lands within 0.5 % on average and 6 % at worst on these tiles - let mean = sum / px.len() as f32; - assert!(mean < 0.01 * 65535.0, "{name}: mean error {mean}"); - assert!(worst < 0.1 * 65535.0, "{name}: worst error {worst}"); - } - } - - /// A fixture tile re-declared grey: its colour encoding's colour space goes from RGB to Grey and, - /// as a grey encoding has no primaries, the 6-bit BT.2100 primaries field is dropped (ISO/IEC 18181-1 - /// ColourEncoding; the bits after it move up and the header's zero padding to the frame grows by 6). - /// The XYB frame data is untouched, so the codestream is one grey plane coded as three XYB channels - /// whose colour is the gradient's, like Lightroom Classic's merged monochrome DNGs. - fn as_grey(tile: &[u8]) -> Vec { - // bit offset of the colour space, read LSB first, and the frame's first byte in these fixture tiles - const AT: usize = 42; - const FRAME: usize = 8; - let mut bits: Vec = tile.iter().flat_map(|b| (0..8).map(move |i| (b >> i) & 1)).collect(); - // colour space Rgb (selector 0), white point D65 (selector 1), primaries Bt2100 (selector 2 + 4 bits of 7) - assert_eq!(bits[AT..AT + 10], [0, 0, 1, 0, 0, 1, 1, 1, 1, 0], "the fixture's colour encoding"); - bits[AT] = 1; // colour space Grey (selector 1) - bits.drain(AT + 4..AT + 10); - bits.splice(FRAME * 8 - 6..FRAME * 8 - 6, [0; 6]); - bits.as_chunks::<8>().0.iter().map(|b| b.iter().enumerate().fold(0, |a, (i, v)| a | v << i)).collect() - } - - #[test] - fn lossy_grey_tiles_decode_to_the_luminance_of_their_colour() { - let srgb_eotf = |v: f32| if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; - let y = rgb_to_xyz(BT2100)[1].map(|v| v as f32); - for (name, tile, curve) in [("linear", LINEAR_TILE, Curve::Linear), ("sRGB", SRGB_TILE, Curve::Srgb)] { - let grey = as_grey(tile); - // the decoder still renders three unequal channels: the restore must reduce them, not pick one - let mut img = JxlImage::builder().read(std::io::Cursor::new(&grey)).unwrap(); - assert!(img.image_header().metadata.grayscale(), "{name}: declared grey"); - img.request_color_encoding(EnumColourEncoding::srgb_linear(RenderingIntent::Relative)); - let render = img.render_frame(0).unwrap(); - let fb = render.image_all_channels(); - assert_eq!(fb.channels(), 3, "{name}"); - assert!((fb.buf()[2] - fb.buf()[0]).abs() > 0.1, "{name}: the rendered channels differ"); - - let ChunkPx::U16(px) = decode(&grey, 16, 16, 16, 16, 1, 16, false).unwrap() else { panic!("{name}: integer samples") }; - assert_eq!(px.len(), 256, "{name}: one plane"); - let (mut sum, mut worst) = (0.0f32, 0.0f32); - for (i, got) in px.iter().enumerate() { - // the gradient's samples are coded in the tile's curve: back to linear for the luminance - let rgb = gradient(i % 16, i / 16).map(|v| if curve == Curve::Srgb { srgb_eotf(v / 65535.0) } else { v / 65535.0 }); - let want = curve.encode(y[0] * rgb[0] + y[1] * rgb[1] + y[2] * rgb[2]) * 65535.0; - let err = (f32::from(*got) - want).abs(); - sum += err; - worst = worst.max(err); - } - let mean = sum / px.len() as f32; - assert!(mean < 0.02 * 65535.0, "{name}: mean error {mean}"); - assert!(worst < 0.1 * 65535.0, "{name}: worst error {worst}"); - } - } - - #[test] - fn lossy_data_that_cannot_be_restored_is_unsupported() { - let bad = |xyb_planes: usize, e: ColourEncoding, it: f32| matches!(output_for(true, &e, it, xyb_planes), Err(RawError::Unsupported(_))); - assert!(bad(1, linear(Primaries::Srgb), 255.0), "one plane declared RGB"); - let mut g = EnumColourEncoding::srgb_linear(RenderingIntent::Relative); - g.colour_space = ColourSpace::Grey; - assert!(bad(1, ColourEncoding::Enum(g.clone()), 10_000.0), "grey with an HDR intensity target"); - g.tf = TransferFunction::Pq; - assert!(bad(1, ColourEncoding::Enum(g.clone()), 255.0), "grey with PQ"); - g.tf = TransferFunction::Linear; - g.white_point = WhitePoint::Dci; - assert!(bad(1, ColourEncoding::Enum(g), 255.0), "grey with a white point other than D65"); - assert!(bad(3, linear(Primaries::Srgb), 10_000.0), "HDR intensity target would tone-map"); - let mut e = EnumColourEncoding::srgb_linear(RenderingIntent::Relative); - for tf in [TransferFunction::Pq, TransferFunction::Hlg, TransferFunction::Unknown, TransferFunction::Gamma { g: 0, inverted: true }] { - e.tf = tf; - assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "{tf:?}"); - } - e.tf = TransferFunction::Linear; - e.white_point = WhitePoint::Dci; - assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "white point"); - e.white_point = WhitePoint::D65; - e.primaries = - Primaries::Custom { red: Customxy { x: 0, y: 0 }, green: Customxy { x: 300_000, y: 600_000 }, blue: Customxy { x: 150_000, y: 60_000 } }; - assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "degenerate primaries"); - e.colour_space = ColourSpace::Grey; - assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "grey declared"); - } -} diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index f246612cae..6c35cd1aa9 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -29,25 +29,23 @@ mod binned; pub mod color; +mod convert; pub mod dcp; pub mod demosaic; -mod dng; pub mod dngwrite; pub mod gaintable; pub mod highlight; mod hotpixel; -#[cfg(feature = "jxl")] -mod jxl; pub mod kelvin_builtin; pub mod kelvin_presets; pub mod lens_metadata; -pub mod ljpeg; +#[cfg(test)] +mod ljpeg_fixtures; pub(crate) mod llvc; pub mod opcodes; mod preview; pub mod profile; mod saturation; -pub mod semantic; pub mod sparse; pub mod spectral; mod tiffraw; @@ -55,6 +53,7 @@ mod unpack; mod vendor; mod wb_estimate; +pub use craft_raw::{BlackLevel, Cfa, MAX_SAMPLES, RawData, RawError, RawFormat, Rect, Result, SemanticMask, ljpeg, probe, semantic_masks, stretched_height}; pub use demosaic::{Method, demosaic}; pub use dngwrite::{DngCompression, DngWriteOptions, write_dng, write_rendered_dng}; pub use hotpixel::HOT_PIXEL_MAX_SHARE; @@ -68,15 +67,10 @@ pub use preview::{ PREVIEW_PREFIX, PreviewColorSpace, PreviewRange, bounded_preview, embedded_preview, embedded_preview_color_space, embedded_preview_covering, embedded_preview_dynamic_range_optimized, embedded_preview_from_range, }; -pub use semantic::{SemanticMask, semantic_masks}; -use craft_tiff::{Tiff, TiffError}; use lightcraft_color::Xy; use serde::{Deserialize, Serialize}; -/// Upper bound on decoded samples (guards allocations driven by header values). -pub const MAX_SAMPLES: usize = 1 << 30; - /// Checked product of input-derived dimensions, in u64 so it cannot wrap /// on either 32-bit (wasm32) or 64-bit targets. The arguments are u64 too, so callers can feed /// unchecked products of header values (row bytes, sample counts) without truncating on 32-bit. @@ -86,290 +80,23 @@ pub(crate) fn checked_pixel_count(width: u64, height: u64) -> Option { width.checked_mul(height).filter(|&n| n > 0 && n <= MAX_SAMPLES as u64) } -/// Errors from raw decoding. -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -pub enum RawError { - #[error("not a recognised raw file")] - NotRaw, - #[error("unsupported raw variant: {0}")] - Unsupported(String), - #[error("corrupt raw data: {0}")] - Corrupt(String), - #[error("limit exceeded: {0}")] - Limit(&'static str), - #[error(transparent)] - Tiff(#[from] TiffError), +/// Whether [`decode`] reads this container (possibly not every compression inside it): `craft-raw`'s makers and +/// the ones still decoded here (Canon CR3, Sony ARW, Fujifilm RAF, Panasonic RW2). +pub fn is_supported(format: RawFormat) -> bool { + format.is_supported() || matches!(format, RawFormat::Cr3 | RawFormat::Arw | RawFormat::Raf | RawFormat::Rw2) } -pub type Result = std::result::Result; - -/// Raw container formats recognised by [`probe`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum RawFormat { - Dng, - Cr2, - Cr3, - Nef, - Nrw, - Arw, - Raf, - Orf, - Rw2, - Pef, - Srw, - /// Canon CRW (CIFF heap), the bodies before the CR2 era. - Crw, - /// Minolta MRW (`\0MRM` block container, `vendor::mrw`). - Mrw, - /// Sigma / Foveon X3F (`FOVb`). - X3f, - /// A TIFF-based raw that has no DNG version tag but describes itself the way DNG does (a - /// full-resolution CFA image with black/white levels, a default crop and `AsShotNeutral`): - /// Hasselblad 3FR and FFF. Read by `vendor::hasselblad` (the DNG reader plus what Hasselblad adds). - CfaTiff, - /// Kodak DCS520C TIFF: a two-component lossless JPEG CFA sub-IFD with a response curve (`vendor::kodak`). - KodakDcs, - /// Epson ERF: a CFA sub-IFD of 12-bit samples in 16-byte blocks (`vendor::erf`). - Erf, - /// Mamiya MEF: an uncompressed 12-bit packed CFA sub-IFD (`vendor::mef`). - Mef, - /// Another TIFF-based raw (3FR, IIQ, ERF, KDC, DCR, MOS, …). - OtherTiff, +/// A 2×2 Bayer layout named in code (`"RGGB"`, `"BGGR"`, `"GRBG"`, `"GBRG"`). Only for literal names (tested); +/// anything else falls back to RGGB instead of failing. +pub(crate) fn bayer(s: &'static str) -> Cfa { + Cfa::bayer(s).unwrap_or(Cfa { width: 2, height: 2, pattern: vec![0, 1, 1, 2] }) } -impl RawFormat { - /// Whether [`decode`] supports this container (possibly not every compression inside it). - pub fn is_supported(self) -> bool { - matches!( - self, - RawFormat::Dng - | RawFormat::Cr2 - | RawFormat::Cr3 - | RawFormat::Crw - | RawFormat::Nef - | RawFormat::Nrw - | RawFormat::Arw - | RawFormat::Raf - | RawFormat::Rw2 - | RawFormat::Pef - | RawFormat::CfaTiff - | RawFormat::Srw - | RawFormat::KodakDcs - | RawFormat::Mrw - | RawFormat::Erf - | RawFormat::Mef - ) - } +/// A CFA pattern this crate can address: 1 to 16 sites a side, one colour index per site. +pub(crate) fn cfa_valid(c: &Cfa) -> bool { + c.width > 0 && c.height > 0 && c.width <= 16 && c.height <= 16 && c.pattern.len() == c.width * c.height } -/// Recognise a raw file from its first bytes / TIFF structure. -pub fn probe(bytes: &[u8]) -> Option { - if bytes.len() >= 12 && &bytes[4..12] == b"ftypcrx " { - return Some(RawFormat::Cr3); - } - if bytes.starts_with(b"FUJIFILMCCD-RAW") { - return Some(RawFormat::Raf); - } - if bytes.starts_with(b"IIRO") || bytes.starts_with(b"IIRS") || bytes.starts_with(b"MMOR") { - return Some(RawFormat::Orf); - } - if bytes.starts_with(b"IIU\0") { - return Some(RawFormat::Rw2); - } - if bytes.starts_with(b"\0MRM") { - return Some(RawFormat::Mrw); - } - if bytes.starts_with(b"FOVb") { - return Some(RawFormat::X3f); - } - if bytes.len() >= 14 && bytes.starts_with(b"II") && &bytes[6..14] == b"HEAPCCDR" { - return Some(RawFormat::Crw); - } - if bytes.len() >= 10 && bytes.starts_with(b"II*\0") && &bytes[8..10] == b"CR" { - return Some(RawFormat::Cr2); - } - let (_, _) = Tiff::sniff(bytes)?; - let opts = craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }; - let t = Tiff::parse_with(bytes, &opts).ok()?; - let ifd0 = t.ifds.first()?; - if ifd0.contains(craft_tiff::tags::DNG_VERSION) { - return Some(RawFormat::Dng); - } - let make = t.find(craft_tiff::tags::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default().to_ascii_uppercase(); - let has_cfa = has_raw_ifd(&t); - // Pentax's reader takes the layout from the Exif `CFAPattern` when no IFD has a CFA photometric (uncompressed - // and PackBits PEFs), so for the Pentax family that tag counts as raw evidence too - let pentax_raw = has_cfa || t.exif().is_some_and(|e| e.contains(vendor::EXIF_CFA_PATTERN)); - // Samsung's raw IFD uses private compressions 32769..=32773 (`vendor::srw`), 32773 being PackBits elsewhere - let samsung_raw = has_cfa || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| (32769..=32773).contains(&c))); - // Sony raws without a CFA IFD (#702): SRF (DSC-F828), whose IFD0 looks like RGB but holds 14-bit samples (12 or - // 14 count: raw sensor depths; the raw is in Sony's SRF blocks), and the DSLR-A100, whose IFD0 is an old-style - // JPEG thumbnail (compression 6, which today's TIFF writers don't produce) and whose `SubIFDs` tag addresses its - // raw data. A camera-authored or exported TIFF has 8- or 16-bit samples, and its SubIFDs hold ordinary images - let model = t.find(craft_tiff::tags::MODEL).and_then(|e| e.value.as_str()).unwrap_or_default().trim().to_ascii_uppercase(); - let sony_raw = has_cfa - || ifd0.u64s(craft_tiff::tags::BITS_PER_SAMPLE).is_some_and(|b| b.iter().any(|v| matches!(v, 12 | 14))) - || (model == "DSLR-A100" && ifd0.u16(craft_tiff::tags::COMPRESSION) == Some(6) && ifd0.contains(craft_tiff::tags::SUB_IFDS)); - if make.starts_with("CANON") && t.ifds.len() >= 4 && t.ifds[3].u16(craft_tiff::tags::COMPRESSION) == Some(6) { - return Some(RawFormat::Cr2); - } - if make.starts_with("NIKON") && has_cfa { - return Some(if t.all_ifds().len() > 1 { RawFormat::Nef } else { RawFormat::Nrw }); - } - // Hasselblad's Sony-built bodies (the Lunar is a NEX-7 inside) write a Sony ARW under their own Make. Sony's - // raw coding gives them away: compression 32767 or the raw IFD's tone-curve tag 0x7010, which no 3FR / FFF has - let sony_coded = || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION) == Some(32767) || i.contains(0x7010)); - if (make.starts_with("SONY") && sony_raw) || (make.starts_with("HASSELBLAD") && sony_coded()) { - return Some(RawFormat::Arw); - } - if (make.starts_with("PENTAX") || make.starts_with("RICOH")) && pentax_raw { - return Some(RawFormat::Pef); - } - // a Samsung-branded body built on a Pentax design writes a Pentax-style maker note (the note's own magic) - if make.starts_with("SAMSUNG") && pentax_raw && has_pentax_maker_note(&t, bytes) { - return Some(RawFormat::Pef); - } - if make.starts_with("SAMSUNG") && samsung_raw { - return Some(RawFormat::Srw); - } - if vendor::erf::raw_ifd(&t, bytes.len()).is_some() { - return Some(RawFormat::Erf); - } - if vendor::mef::raw_ifd(&t, bytes.len()).is_some() { - return Some(RawFormat::Mef); - } - if vendor::kodak::raw_ifd(&t, bytes).is_some() { - return Some(RawFormat::KodakDcs); - } - if dng::is_plain_cfa_tiff(&t, bytes) { - return Some(RawFormat::CfaTiff); - } - if has_cfa || thumbnail_shell(&t, bytes.len()).is_some() || is_preview_container(ifd0) || is_leaf_mosaic(ifd0) { - return Some(RawFormat::OtherTiff); - } - None -} - -/// Leaf's private data block in IFD0, tag `0x8606` (`LeafData` in the ExifTool EXIF tag-name documentation, which -/// says the Leaf tags "are found in .MOS images from Leaf digital camera backs"). -const LEAF_DATA: u16 = 0x8606; - -/// An uncompressed Leaf MOS: IFD0 is the 16-bit mosaic itself (compression 1, BlackIsZero, one sample per pixel), -/// with no Make tag and no CFA photometric, so only Leaf's data block marks it as a raw (issue #1275). A rendered -/// RGB image that kept the block stays an ordinary image. -fn is_leaf_mosaic(ifd0: &craft_tiff::Ifd) -> bool { - ifd0.contains(LEAF_DATA) && ifd0.u16(craft_tiff::tags::SAMPLES_PER_PIXEL).unwrap_or(1) == 1 -} - -/// Whether the Exif maker note starts with the signature of the Pentax layouts (`AOC\0` or `PENTAX \0`). -fn has_pentax_maker_note(t: &Tiff, bytes: &[u8]) -> bool { - let Some(e) = t.exif().and_then(|e| e.get(craft_tiff::tags::MAKER_NOTE)) else { return false }; - bytes.get(e.offset as usize..).is_some_and(|n| n.starts_with(b"AOC\0") || n.starts_with(b"PENTAX \0")) -} - -/// Whether some IFD is marked as raw: CFA photometric, or a raw-only compression value (99 is not a -/// registered TIFF compression; Leaf MOS files use it for their tiled 16-bit lossless-JPEG raw), -/// or vendor-specific raw tags (Sony tone curve, CFA pattern, or Pentax compression 65535). -fn has_raw_ifd(t: &Tiff) -> bool { - t.all_ifds().iter().any(|i| { - i.u16(craft_tiff::tags::PHOTOMETRIC) == Some(craft_tiff::tags::photometric::CFA) - || i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| matches!(c, 34713 | 32767 | 32769 | 32770 | 99 | 65535)) - || i.contains(0x7010) - || i.contains(craft_tiff::tags::CFA_PATTERN_EP) - || i.contains(craft_tiff::tags::CFA_REPEAT_PATTERN_DIM) - }) -} - -/// IFD0 that is not an image at all: no `ImageWidth` / `ImageLength`, but a JPEG preview pointer or -/// `SubIFDs` (the layout of Kodak KDC files, whose pictures sit in private tags). A plain TIFF reader -/// rejects such a file as malformed even though it carries a preview. -fn is_preview_container(ifd0: &craft_tiff::Ifd) -> bool { - use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, JPEG_INTERCHANGE_FORMAT, SUB_IFDS}; - !ifd0.contains(IMAGE_WIDTH) && !ifd0.contains(IMAGE_LENGTH) && (ifd0.contains(JPEG_INTERCHANGE_FORMAT) || ifd0.contains(SUB_IFDS)) -} - -/// A TIFF whose first image is only a reduced copy of a picture stored somewhere else. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct ThumbnailShell { - /// Size of the first image (IFD0). - pub thumb: (u32, u32), - /// Size of the picture it stands in for. - pub full: (u32, u32), -} - -/// Some raw files are a TIFF "shell" around a private block: IFD0 holds a small RGB preview and nothing -/// in the TIFF structure marks the real image as raw (no CFA photometric, no raw compression). The -/// structure still gives them away, with a generic rule that names no maker or model: the file -/// declares a picture at least 4x larger than IFD0 in both directions, and either -/// - a `SubIFDs` child of IFD0 is that bigger image (an 8-bit grey mosaic in one such file), or -/// - the Exif `PixelXDimension` / `PixelYDimension` say so *and* the file holds enough bytes outside -/// every IFD's strips and tiles to carry that many pixels at one bit each (a downsized copy that kept -/// its old Exif size has no such block). -/// -/// A multi-page TIFF is not caught (its pages are the IFD chain, not `SubIFDs`), nor a pyramid whose -/// IFD0 is the full image. -fn thumbnail_shell(t: &Tiff, len: usize) -> Option { - use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, PIXEL_X_DIMENSION, PIXEL_Y_DIMENSION}; - let ifd0 = t.ifds.first()?; - let (w0, h0) = (ifd0.u32(IMAGE_WIDTH)?, ifd0.u32(IMAGE_LENGTH)?); - if w0 == 0 || h0 == 0 { - return None; - } - let much_bigger = |(w, h): (u32, u32)| u64::from(w) >= 4 * u64::from(w0) && u64::from(h) >= 4 * u64::from(h0); - let shell = |full| Some(ThumbnailShell { thumb: (w0, h0), full }); - let mut best: Option<(u32, u32)> = None; - for s in &ifd0.sub_ifds { - if s.image().is_ok() - && let (Some(w), Some(h)) = (s.u32(IMAGE_WIDTH), s.u32(IMAGE_LENGTH)) - && much_bigger((w, h)) - && best.is_none_or(|(bw, bh)| u64::from(w) * u64::from(h) > u64::from(bw) * u64::from(bh)) - { - best = Some((w, h)); - } - } - if let Some(full) = best { - return shell(full); - } - let exif = t.exif()?; - let full = (exif.u32(PIXEL_X_DIMENSION)?, exif.u32(PIXEL_Y_DIMENSION)?); - if !much_bigger(full) { - return None; - } - // bytes covered by image data (strips and tiles shared between IFDs, e.g. IFD0 and its thumbnail, count once) - let mut seen = std::collections::BTreeMap::new(); - for ifd in t.all_ifds() { - if let Ok(info) = ifd.image() { - for c in info.chunks(len as u64) { - seen.insert(c.offset, c.len); - } - } - } - let covered = seen.values().fold(0u64, |a, &l| a.saturating_add(l)); - let spare = (len as u64).saturating_sub(covered); - (spare.saturating_mul(8) >= u64::from(full.0) * u64::from(full.1)).then_some(())?; - shell(full) -} - -/// Why [`decode`] gives up on a file [`probe`] called [`RawFormat::OtherTiff`]. -fn other_tiff_reason(bytes: &[u8]) -> String { - let t = Tiff::parse_with(bytes, &craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }).ok(); - // a DNG-style CFA IFD whose lossless JPEG the lossless decoder rejects: say why - if let Some(t) = &t - && let Some(info) = dng::raw_ifd(t).and_then(|i| i.image().ok()) - && info.compression == craft_tiff::tags::compression::JPEG - && let Some(src) = info.chunks(bytes.len() as u64).first().and_then(|c| craft_tiff::image::chunk_bytes(bytes, c)) - && let Err(e) = ljpeg::frame_info(src) - { - return format!("raw image coded as lossless JPEG that is not decoded yet ({e})"); - } - match t.as_ref().filter(|t| !has_raw_ifd(t)).and_then(|t| thumbnail_shell(t, bytes.len())) { - Some(s) => format!( - "{}x{} raw image in a private block, not decoded yet (the file's first image is a {}x{} reduced copy)", - s.full.0, s.full.1, s.thumb.0, s.thumb.1 - ), - None => "OtherTiff files are not decoded yet".to_string(), - } -} /// Decode a raw file. pub fn decode(bytes: &[u8]) -> Result { @@ -381,10 +108,7 @@ pub fn decode(bytes: &[u8]) -> Result { /// px ones) decodes the smallest that covers it. The image has the full one's levels, colour and metadata; its /// active area and crop are scaled to its size. `Ok(None)` when the file keeps no such copy: decode it whole. pub fn decode_reduced(bytes: &[u8], min_long: usize) -> Result> { - if probe(bytes) != Some(RawFormat::Dng) { - return Ok(None); - } - Ok(dng::decode_reduced(bytes, min_long)?.map(lift_clipped)) + convert::decode_reduced(bytes, min_long) } /// Everything [`decode`] learns about a raw file except its samples: geometry, orientation, CFA, @@ -393,13 +117,11 @@ pub fn decode_reduced(bytes: &[u8], min_long: usize) -> Result> /// [`RawImage::info`] of the decoded image. Black and white levels are not included (some formats /// measure them from the samples). /// -/// A few vendor formats derive part of this from the samples themselves (Nikon NEF: optically -/// masked trailing columns; Olympus ORF: the bit depth of 16-bit files, and the CFA phase of files -/// without an Exif `CFAPattern`; Pentax PEF without crop tags: dark borders). Those read the -/// samples they need and drop them: ORF and PEF unpack their uncompressed data; NEF reads only the -/// first 128 rows (`vendor::nef::MASK_ROWS`), which both the probe and the full decode judge the masked -/// columns from, so a compressed NEF probes in a few milliseconds instead of decoding its whole -/// Huffman stream (issue #708). +/// A few formats derive part of this from the samples themselves (Nikon NEF: optically masked trailing columns; +/// Olympus ORF: the bit depth of 16-bit files, and the CFA phase of files without an Exif `CFAPattern`; Pentax PEF +/// without crop tags: dark borders; Epson ERF and Mamiya MEF: the white balance, estimated from the samples). +/// Those read the samples they need and drop them; a compressed NEF reads only the rows its masked columns are +/// judged from (issue #708). pub fn probe_info(bytes: &[u8]) -> Result { decode_with(bytes, Mode::Header).map(RawImage::into_info) } @@ -416,33 +138,16 @@ pub(crate) enum Mode { fn decode_with(bytes: &[u8], mode: Mode) -> Result { match probe(bytes).ok_or(RawError::NotRaw)? { - RawFormat::Dng => dng::decode(bytes, mode).map(lift_clipped), - RawFormat::Cr2 => vendor::cr2::decode(bytes, mode), RawFormat::Cr3 => vendor::cr3::decode(bytes, mode), - RawFormat::Crw => vendor::crw::decode(bytes, mode), - RawFormat::Nef | RawFormat::Nrw => vendor::nef::decode(bytes, mode), RawFormat::Arw => vendor::arw::decode(bytes, mode), RawFormat::Raf => vendor::raf::decode(bytes, mode), RawFormat::Rw2 => vendor::rw2::decode(bytes, mode), - RawFormat::Pef => vendor::pef::decode(bytes, mode), RawFormat::Orf => vendor::orf::decode(bytes, mode), - RawFormat::CfaTiff => vendor::hasselblad::decode(bytes, mode).map(lift_clipped), - RawFormat::Srw => vendor::srw::decode(bytes, mode), - RawFormat::KodakDcs => vendor::kodak::decode(bytes, mode), - RawFormat::Mrw => vendor::mrw::decode(bytes, mode), - RawFormat::Erf => vendor::erf::decode(bytes, mode), - RawFormat::Mef => vendor::mef::decode(bytes, mode), - RawFormat::OtherTiff => Err(RawError::Unsupported(other_tiff_reason(bytes))), - other => Err(RawError::Unsupported(format!("{other:?} files are not decoded yet"))), + // every other maker, and the reasons a file is not decoded, are craft-raw's + _ => convert::decode(bytes, mode), } } -/// DNG writers state a white level the sensor may never reach; samples stuck at the real saturation point are -/// raised to the white level so they count as clipped (see [`RawImage::lift_clipped_samples`]). -fn lift_clipped(mut r: RawImage) -> RawImage { - r.lift_clipped_samples(); - r -} /// A raw file's description without its samples (see [`probe_info`]). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -474,11 +179,6 @@ fn square_pixels() -> f32 { 1.0 } -/// Rows of a picture `height` rows tall once its pixels (taller than wide by `aspect`) are made square. -pub fn stretched_height(height: usize, aspect: f32) -> usize { - if (aspect - 1.0).abs() < 0.01 { height } else { ((height as f32 * aspect).round() as usize).max(1) } -} - impl RawInfo { /// Size of the developed image before orientation: the default crop, else the active area, with the rows /// stretched for non-square pixels. @@ -489,168 +189,6 @@ impl RawInfo { } } -/// Sensor samples. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub enum RawData { - U16(Vec), - /// Floating-point DNGs (already linear, typically white = 1.0). - F32(Vec), -} - -impl RawData { - pub fn len(&self) -> usize { - match self { - RawData::U16(v) => v.len(), - RawData::F32(v) => v.len(), - } - } - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - #[inline] - pub fn get(&self, i: usize) -> f32 { - match self { - RawData::U16(v) => v[i] as f32, - RawData::F32(v) => v[i], - } - } -} - -/// Colour filter array pattern. Colour indices: 0 = red, 1 = green, 2 = blue. -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct Cfa { - pub width: usize, - pub height: usize, - /// `width × height` colour indices, row-major, anchored at image pixel (0, 0). - pub pattern: Vec, -} - -impl Cfa { - /// A 2×2 Bayer pattern from a string such as `"RGGB"`. - pub fn bayer(s: &str) -> Option { - let p: Vec = s - .chars() - .map(|c| { - Some(match c { - 'R' => 0, - 'G' => 1, - 'B' => 2, - _ => return None, - }) - }) - .collect::>()?; - (p.len() == 4).then_some(Cfa { width: 2, height: 2, pattern: p }) - } - /// A 2×2 Bayer layout named in code (`"RGGB"`, `"BGGR"`, `"GRBG"`, `"GBRG"`). Only for literal - /// names (tested below); anything else falls back to RGGB instead of failing. - pub(crate) fn bayer_static(s: &'static str) -> Cfa { - Cfa::bayer(s).unwrap_or(Cfa { width: 2, height: 2, pattern: vec![0, 1, 1, 2] }) - } - /// The Fujifilm X-Trans 6×6 layout (as commonly documented), anchored at (0, 0). - pub fn xtrans() -> Cfa { - let rows = ["GGRGGB", "GGBGGR", "BRGRBG", "GGBGGR", "GGRGGB", "RBGBRG"]; - let pattern = rows - .iter() - .flat_map(|r| { - r.chars().map(|c| match c { - 'R' => 0, - 'G' => 1, - _ => 2, - }) - }) - .collect(); - Cfa { width: 6, height: 6, pattern } - } - #[inline] - pub fn color_at(&self, x: usize, y: usize) -> u8 { - self.pattern[(y % self.height) * self.width + (x % self.width)] - } - /// The same pattern anchored at `(dx, dy)` of the current anchor (e.g. after cropping to an active area). - pub fn shifted(&self, dx: usize, dy: usize) -> Cfa { - let pattern = (0..self.height).flat_map(|y| (0..self.width).map(move |x| (x, y))).map(|(x, y)| self.color_at(x + dx, y + dy)).collect(); - Cfa { width: self.width, height: self.height, pattern } - } - pub fn is_bayer(&self) -> bool { - if self.width != 2 || self.height != 2 { - return false; - } - let mut c = [0; 3]; - for &p in &self.pattern { - if p > 2 { - return false; - } - c[p as usize] += 1; - } - c == [1, 2, 1] - } - /// Pattern name like `"RGGB"` for 2×2 patterns. - pub fn name(&self) -> String { - self.pattern.iter().map(|&c| ['R', 'G', 'B', '?'][c.min(3) as usize]).collect() - } - fn valid(&self) -> bool { - self.width > 0 && self.height > 0 && self.width <= 16 && self.height <= 16 && self.pattern.len() == self.width * self.height - } -} - -/// Integer rectangle (pixels). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct Rect { - pub x: usize, - pub y: usize, - pub width: usize, - pub height: usize, -} - -impl Rect { - pub fn new(x: usize, y: usize, width: usize, height: usize) -> Rect { - Rect { x, y, width, height } - } - /// Clip to a `w × h` area. - pub fn clipped(self, w: usize, h: usize) -> Rect { - let x = self.x.min(w); - let y = self.y.min(h); - Rect { x, y, width: self.width.min(w - x), height: self.height.min(h - y) } - } -} - -/// Black level model (DNG `BlackLevelRepeatDim`, `BlackLevel`, `BlackLevelDeltaH/V`). The repeat pattern and -/// the deltas are anchored at the active area's top-left corner. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct BlackLevel { - pub repeat_rows: usize, - pub repeat_cols: usize, - /// `repeat_rows × repeat_cols × cpp` values. - pub values: Vec, - /// Per active-area column. - pub delta_h: Vec, - /// Per active-area row. - pub delta_v: Vec, -} - -impl Default for BlackLevel { - fn default() -> Self { - BlackLevel { repeat_rows: 1, repeat_cols: 1, values: vec![0.0], delta_h: vec![], delta_v: vec![] } - } -} - -impl BlackLevel { - pub fn uniform(v: f32) -> BlackLevel { - BlackLevel { values: vec![v], ..Default::default() } - } - /// Black level at active-area coordinates (x, y) for sample `s` of `cpp`. - #[inline] - pub fn at(&self, x: usize, y: usize, s: usize, cpp: usize) -> f32 { - let (r, c) = (self.repeat_rows.max(1), self.repeat_cols.max(1)); - let idx = ((y % r) * c + (x % c)) * cpp + s; - let base = self.values.get(idx).or_else(|| self.values.first()).copied().unwrap_or(0.0); - base + self.delta_h.get(x).copied().unwrap_or(0.0) + self.delta_v.get(y).copied().unwrap_or(0.0) - } - /// Mean of the repeat-pattern values (for display / heuristics). - pub fn mean(&self) -> f32 { - if self.values.is_empty() { 0.0 } else { self.values.iter().sum::() / self.values.len() as f32 } - } -} - /// DNG colour tags (DNG 1.7 chapter 6). Matrices are 3×3 (three-colour cameras). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct ColorData { @@ -807,7 +345,7 @@ impl RawImage { } } if let Some(c) = &self.cfa - && (!c.valid() || c.pattern.iter().any(|&p| p > 2)) + && (!cfa_valid(c) || c.pattern.iter().any(|&p| p > 2)) { return Err(RawError::Unsupported(format!("CFA pattern {}", c.name()))); } diff --git a/crates/raw/src/ljpeg.rs b/crates/raw/src/ljpeg.rs deleted file mode 100644 index 922a9fb640..0000000000 --- a/crates/raw/src/ljpeg.rs +++ /dev/null @@ -1,1007 +0,0 @@ -//! Lossless JPEG ("LJ92"): ITU-T T.81 / ISO 10918-1 process 14 (Annex H), Huffman-coded, as used by DNG, -//! Canon CR2 and Sony lossless ARW. -//! -//! - All seven predictors, 2–16 bit precision, 1–4 interleaved components (1×1 sampling), point transform, -//! restart intervals, `SSSS = 16` differences. -//! - [`decode`] returns the frame as interleaved samples in raster order (`width × height × components`), -//! which callers re-tile (DNG tiles, CR2 slices). -//! - Selection value 8, which T.81 leaves undefined, is Hasselblad's coding in 3FR and FFF files -//! ([`decode`] reads it; [`decode_hasselblad`] documents the rule and how it was established). -//! - [`encode`] writes a conforming stream with per-component optimal Huffman tables built with the -//! T.81 Annex K.2 procedure — used by tests (bit-exact round trips) and later by DNG export. - -use crate::RawError; - -/// A decoded lossless-JPEG frame. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Frame { - pub width: usize, - pub height: usize, - pub components: usize, - pub precision: u8, - pub predictor: u8, - pub point_transform: u8, - /// `width × height × components` interleaved samples. - pub data: Vec, -} - -fn err(s: &str) -> RawError { - RawError::Corrupt(format!("lossless JPEG: {s}")) -} - -/// Huffman decoding table (T.81 Annex C "BITS"/"HUFFVAL"). -#[derive(Clone, Debug)] -pub struct Huffman { - /// For peeks of `LOOKUP` bits: (code length, symbol); length 0 = slow path. - fast: Vec<(u8, u8)>, - maxcode: [i32; 18], - valptr: [i32; 17], - mincode: [i32; 17], - values: Vec, -} - -const LOOKUP: u32 = 10; - -impl Huffman { - /// Build from the 16 code-length counts and the symbol list. - pub fn new(counts: &[u8; 16], values: &[u8]) -> Result { - let total: usize = counts.iter().map(|&c| c as usize).sum(); - if total > values.len() || total > 256 || total == 0 { - return Err(err("bad Huffman table")); - } - let mut maxcode = [-1i32; 18]; - let mut valptr = [0i32; 17]; - let mut mincode = [0i32; 17]; - let mut fast = vec![(0u8, 0u8); 1 << LOOKUP]; - let mut code = 0i32; - let mut k = 0usize; - for len in 1..=16usize { - let n = counts[len - 1] as i32; - valptr[len] = k as i32; - mincode[len] = code; - for _ in 0..n { - if len as u32 <= LOOKUP { - let shift = LOOKUP - len as u32; - let base = (code as usize) << shift; - for i in 0..(1usize << shift) { - if let Some(slot) = fast.get_mut(base + i) { - *slot = (len as u8, values[k]); - } - } - } - code += 1; - k += 1; - } - maxcode[len] = if n > 0 { code - 1 } else { -1 }; - if code > (1 << len) { - return Err(err("over-subscribed Huffman table")); - } - code <<= 1; - } - maxcode[17] = i32::MAX; - Ok(Huffman { fast, maxcode, valptr, mincode, values: values[..total].to_vec() }) - } - - #[inline] - pub fn decode(&self, br: &mut B) -> Result { - let peek = br.peek(LOOKUP); - let (len, sym) = self.fast[peek as usize]; - if len > 0 { - br.consume(len as u32); - return Ok(sym); - } - let mut code = br.peek(LOOKUP + 1) as i32; - let mut len = LOOKUP as usize + 1; - while len <= 16 && code > self.maxcode[len] { - len += 1; - code = br.peek(len as u32) as i32; - } - if len > 16 { - return Err(err("invalid Huffman code")); - } - br.consume(len as u32); - let idx = self.valptr[len] + code - self.mincode[len]; - self.values.get(idx as usize).copied().ok_or_else(|| err("invalid Huffman code")) - } -} - -/// A source of entropy-coded bits, first bit most significant. -pub trait Bits { - /// The next `n` (1..=32) bits without consuming them; zeros past the end. - fn peek(&mut self, n: u32) -> u32; - fn consume(&mut self, n: u32); - #[inline] - fn get(&mut self, n: u32) -> u32 { - if n == 0 { - return 0; - } - let v = self.peek(n); - self.consume(n); - v - } -} - -impl Bits for BitReader<'_> { - #[inline] - fn peek(&mut self, n: u32) -> u32 { - BitReader::peek(self, n) - } - #[inline] - fn consume(&mut self, n: u32) { - BitReader::consume(self, n) - } -} - -/// MSB-first bit reader over JPEG entropy-coded data (handles `FF 00` stuffing; stops at markers, feeding zeros). -pub struct BitReader<'a> { - data: &'a [u8], - pos: usize, - buf: u64, - bits: u32, - /// A marker (`FF xx`, xx ≠ 0) was reached. - pub marker: Option, - /// Bits fed past the end of data (for corruption detection). - pub overrun: u32, -} - -impl<'a> BitReader<'a> { - pub fn new(data: &'a [u8]) -> Self { - Self { data, pos: 0, buf: 0, bits: 0, marker: None, overrun: 0 } - } - #[inline] - fn fill(&mut self) { - while self.bits <= 56 { - let byte = if self.marker.is_some() || self.pos >= self.data.len() { - self.overrun += 8; - 0 - } else { - let b = self.data[self.pos]; - if b == 0xff { - let next = self.data.get(self.pos + 1).copied().unwrap_or(0); - if next == 0 { - self.pos += 2; - 0xff - } else { - self.marker = Some(next); - self.overrun += 8; - 0 - } - } else { - self.pos += 1; - b - } - }; - self.buf |= (byte as u64) << (56 - self.bits); - self.bits += 8; - } - } - #[inline] - pub fn peek(&mut self, n: u32) -> u32 { - if self.bits < n { - self.fill(); - } - (self.buf >> (64 - n)) as u32 - } - #[inline] - pub fn consume(&mut self, n: u32) { - self.buf <<= n; - self.bits -= n; - } - #[inline] - pub fn get(&mut self, n: u32) -> u32 { - if n == 0 { - return 0; - } - let v = self.peek(n); - self.consume(n); - v - } - /// Discard buffered bits and skip to just after the next `RSTn` marker. Returns false if none found. - fn restart(&mut self) -> bool { - self.buf = 0; - self.bits = 0; - self.marker = None; - self.overrun = 0; - while self.pos + 1 < self.data.len() { - if self.data[self.pos] == 0xff && (0xd0..=0xd7).contains(&self.data[self.pos + 1]) { - self.pos += 2; - return true; - } - self.pos += 1; - } - false - } - /// Bytes consumed so far (approximate while bits are buffered). - pub fn position(&self) -> usize { - self.pos - } -} - -/// Difference value for category `ssss` (T.81 Table H.2 / F.12 EXTEND). -#[inline] -pub fn diff_value(br: &mut B, ssss: u8) -> i32 { - match ssss { - 0 => 0, - 16 => 32768, - s => { - let s = s.min(16) as u32; - let v = br.get(s) as i32; - if v < (1 << (s - 1)) { v - (1 << s) + 1 } else { v } - } - } -} - -struct Header { - precision: u8, - height: usize, - width: usize, - comps: Vec, - sampling: Vec, - tables: [Option; 4], - table_for: Vec, - predictor: u8, - pt: u8, - restart: usize, - scan_start: usize, -} - -fn be16(d: &[u8], i: usize) -> Result { - d.get(i..i + 2).map(|s| u16::from_be_bytes([s[0], s[1]]) as usize).ok_or_else(|| err("truncated header")) -} - -fn parse_header(d: &[u8]) -> Result { - if d.len() < 4 || d[0] != 0xff || d[1] != 0xd8 { - return Err(err("missing SOI")); - } - let mut h = Header { - precision: 0, - height: 0, - width: 0, - comps: vec![], - sampling: vec![], - tables: [None, None, None, None], - table_for: vec![], - predictor: 1, - pt: 0, - restart: 0, - scan_start: 0, - }; - let mut i = 2; - let mut have_sof = false; - loop { - // skip fill bytes / stray data up to the next marker - while i < d.len() && d[i] != 0xff { - i += 1; - } - while i < d.len() && d[i] == 0xff { - i += 1; - } - let Some(&m) = d.get(i) else { return Err(err("no scan")) }; - i += 1; - if m == 0xd8 || (0xd0..=0xd7).contains(&m) { - continue; - } - if m == 0xd9 { - return Err(err("EOI before scan")); - } - let len = be16(d, i)?; - if len < 2 || i + len > d.len() { - return Err(err("truncated segment")); - } - let seg = &d[i + 2..i + len]; - match m { - 0xc3 => { - if seg.len() < 6 { - return Err(err("short SOF3")); - } - h.precision = seg[0]; - h.height = u16::from_be_bytes([seg[1], seg[2]]) as usize; - h.width = u16::from_be_bytes([seg[3], seg[4]]) as usize; - let n = seg[5] as usize; - if n == 0 || n > 4 || seg.len() < 6 + 3 * n { - return Err(err("bad component count")); - } - for c in 0..n { - let (id, samp) = (seg[6 + 3 * c], seg[7 + 3 * c]); - if !(1..=4).contains(&(samp >> 4)) || !(1..=4).contains(&(samp & 15)) { - return Err(err("invalid sampling factors")); - } - h.comps.push(id); - h.sampling.push(samp); - } - if !(2..=16).contains(&h.precision) { - return Err(err("bad precision")); - } - have_sof = true; - } - 0xc0..=0xc2 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => { - return Err(RawError::Unsupported(format!("JPEG process SOF{:X} (not lossless Huffman)", m - 0xc0))); - } - 0xc4 => { - let mut j = 0; - while j + 17 <= seg.len() { - let (class, id) = (seg[j] >> 4, (seg[j] & 15) as usize); - let mut counts = [0u8; 16]; - counts.copy_from_slice(&seg[j + 1..j + 17]); - let n: usize = counts.iter().map(|&c| c as usize).sum(); - let vals = seg.get(j + 17..j + 17 + n).ok_or_else(|| err("truncated DHT"))?; - if class == 0 && id < 4 { - h.tables[id] = Some(Huffman::new(&counts, vals)?); - } - j += 17 + n; - } - } - 0xdd => h.restart = be16(seg, 0)?, - 0xda => { - if !have_sof { - return Err(err("SOS before SOF3")); - } - let ns = *seg.first().ok_or_else(|| err("short SOS"))? as usize; - if ns != h.comps.len() || seg.len() < 1 + 2 * ns + 3 { - return Err(RawError::Unsupported("lossless JPEG with multiple scans".into())); - } - for c in 0..ns { - let cid = seg[1 + 2 * c]; - let pos = h.comps.iter().position(|&x| x == cid).ok_or_else(|| err("unknown scan component"))?; - if pos != c { - return Err(err("scan component order")); - } - let td = (seg[2 + 2 * c] >> 4) as usize; - if td > 3 || h.tables[td].is_none() { - return Err(err("missing Huffman table")); - } - h.table_for.push(td); - } - h.predictor = seg[1 + 2 * ns]; - h.pt = seg[3 + 2 * ns] & 15; - if h.predictor > 8 { - return Err(RawError::Unsupported(format!( - "lossless JPEG scan with predictor selection value {} (T.81 defines 0 to 7, Hasselblad uses 8)", - h.predictor - ))); - } - if h.pt >= h.precision { - return Err(err("bad point transform")); - } - h.scan_start = i + len; - return Ok(h); - } - _ => {} - } - i += len; - } -} - -/// Parse only the frame header: (width, height, components, precision). -pub fn frame_info(d: &[u8]) -> Result<(usize, usize, usize, u8), RawError> { - let h = parse_header(d)?; - check_full_resolution(&h)?; - if h.predictor == 8 { - check_hasselblad(&h)?; - } - Ok((h.width, h.height, h.comps.len(), h.precision)) -} - -fn check_full_resolution(h: &Header) -> Result<(), RawError> { - if h.sampling.iter().any(|&s| s != 0x11) { - return Err(RawError::Unsupported("lossless JPEG with subsampled components".into())); - } - Ok(()) -} - -/// The layout of every Hasselblad selection-value-8 scan measured; other layouts are not known to follow the rule. -fn check_hasselblad(h: &Header) -> Result<(), RawError> { - if h.comps.len() != 1 || h.precision != 16 || h.pt != 0 || h.restart != 0 || h.width == 0 || !h.width.is_multiple_of(2) { - return Err(RawError::Unsupported(format!( - "lossless JPEG with selection value 8 and {} components, {} bits, point transform {}, restart interval {}, width {}", - h.comps.len(), - h.precision, - h.pt, - h.restart, - h.width - ))); - } - Ok(()) -} - -/// Bits of Hasselblad's entropy data: 32-bit little-endian words, each read from its most significant bit, with -/// no byte stuffing (every byte is data; `FF` bytes are not markers). -struct WordBits<'a> { - data: &'a [u8], - pos: usize, - buf: u64, - bits: u32, - /// Zero bits fed past the last whole word (consumption reached them once `overrun > bits`). - overrun: u32, -} - -impl<'a> WordBits<'a> { - fn new(data: &'a [u8]) -> Self { - Self { data, pos: 0, buf: 0, bits: 0, overrun: 0 } - } - - #[inline] - fn fill(&mut self) { - while self.bits <= 32 { - let word = match self.data.get(self.pos..self.pos + 4) { - Some(w) => { - self.pos += 4; - u32::from_le_bytes([w[0], w[1], w[2], w[3]]) - } - None => { - self.overrun = self.overrun.saturating_add(32); - 0 - } - }; - self.buf |= (word as u64) << (32 - self.bits); - self.bits += 32; - } - } -} - -impl Bits for WordBits<'_> { - #[inline] - fn peek(&mut self, n: u32) -> u32 { - if self.bits < n { - self.fill(); - } - (self.buf >> (64 - n)) as u32 - } - #[inline] - fn consume(&mut self, n: u32) { - self.buf <<= n; - self.bits -= n; - } -} - -/// Hasselblad's lossless JPEG with selection value 8 (3FR and FFF raws). -/// -/// The rule was established by measurement on 14 sample files with the `ljpeg-explorer` tool, which tested it -/// against alternative bit orders, stuffing, sample groupings, category-16 treatments and predictors: -/// - the entropy data are 32-bit little-endian words, each read from its most significant bit, without byte -/// stuffing; -/// - each row is coded in pairs of samples: both Huffman categories (`SSSS`, T.81 table) come first, then both -/// differences; -/// - a difference has `SSSS` extra bits, extended as in T.81 Table H.2; after `SSSS = 16` come sixteen bits that -/// take no part, and the difference is -32768 (equal to T.81's +32768 modulo 2^16); -/// - a sample is the previous sample of the same column parity in its row plus the difference, modulo 2^16; before -/// the first pair of every row both are 32768 (half the 16-bit range). -/// -/// Provenance: the first hypothesis for this rule was recalled by the AI model that wrote this code from its training -/// data, which includes other raw converters; it was treated as one candidate, corrected where the files disagreed -/// (the byte order of the words) and confirmed by an exhaustive black-box search over 17,280 layout hypotheses on the -/// CC0 sample files. No other converter's source was consulted, and the code is original. -pub fn decode_hasselblad(d: &[u8], max_samples: usize) -> Result { - let h = parse_header(d)?; - if h.predictor != 8 { - return Err(err("not a selection value 8 scan")); - } - hasselblad_frame(d, &h, max_samples) -} - -fn hasselblad_frame(d: &[u8], h: &Header, max_samples: usize) -> Result { - check_hasselblad(h)?; - let (w, ht) = (h.width, h.height); - let total = w.checked_mul(ht).ok_or_else(|| err("frame too large"))?; - if total > max_samples { - return Err(RawError::Limit("lossless JPEG frame larger than expected")); - } - let entropy = &d[h.scan_start..]; - if (entropy.len() as u64 + 64) * 8 < total as u64 { - return Err(err("entropy data too short for frame")); - } - let table = - h.table_for.first().and_then(|&t| h.tables.get(t)).and_then(Option::as_ref).ok_or_else(|| err("scan uses an undefined Huffman table"))?; - let mut out = vec![0u16; total]; - let mut br = WordBits::new(entropy); - let start = 1u32 << (h.precision - 1); - for row in out.chunks_exact_mut(w) { - let mut last = [start, start]; - // the width is even (checked), so every sample is in a pair - for pair in row.as_chunks_mut::<2>().0 { - let ssss = [table.decode(&mut br)?, table.decode(&mut br)?]; - for (k, s) in ssss.into_iter().enumerate() { - let diff = match s { - 0..=15 => diff_value(&mut br, s), - 16 => { - br.get(16); - -32768 - } - _ => return Err(err("invalid difference category")), - }; - let v = (last[k] as i32 + diff) as u32 & 0xffff; - last[k] = v; - pair[k] = v as u16; - } - } - // bits consumed beyond the last whole word - if br.overrun > br.bits { - return Err(err("entropy data exhausted")); - } - } - Ok(Frame { width: w, height: ht, components: 1, precision: h.precision, predictor: 8, point_transform: 0, data: out }) -} - -fn check_subsampled(h: &Header) -> Result { - let vertical = match h.sampling.as_slice() { - [0x22, 0x11, 0x11] => 2, - [0x21, 0x11, 0x11] => 1, - _ => return Err(RawError::Unsupported("lossless JPEG subsampling layout".into())), - }; - if h.predictor != 1 || h.restart != 0 { - return Err(RawError::Unsupported("lossless JPEG subsampled predictor / restarts".into())); - } - if h.width == 0 || h.height == 0 || !h.width.is_multiple_of(2) || !h.height.is_multiple_of(vertical) { - return Err(err("subsampled frame dimensions do not match MCU size")); - } - Ok(vertical) -} - -/// Sony M/S tiles and Canon sRAW / mRAW: horizontal prediction, no restart markers. Keep subsampled planes -/// separate; expanding them into a mosaic would silently corrupt the existing CFA callers. -/// Returns (width, height, vertical subsampling of the chroma planes). -pub(crate) fn frame_info_subsampled(d: &[u8]) -> Result<(usize, usize, usize), RawError> { - let h = parse_header(d)?; - let vertical = check_subsampled(&h)?; - Ok((h.width, h.height, vertical)) -} - -/// How the first-column prediction and the running predictor of a subsampled frame are chosen. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Prediction { - /// Sony: the left neighbour in the plane; at the first column the sample above, except that a top luma - /// row of an MCU row reads the previous MCU row's top luma sample. - Geometric, - /// Canon: every component is its own one-dimensional chain in decoding order (the previous sample of the - /// same component, so the second luma row of a 4:2:0 MCU continues from the end of the first); the first - /// sample of each MCU row starts from the first sample of the previous MCU row. - Sequential, -} - -pub(crate) struct FrameSubsampled { - pub width: usize, - pub height: usize, - pub vertical_subsampling: usize, - /// Y at full resolution; Cb and Cr at half width, with 1× or 2× vertical subsampling. - pub planes: [Vec; 3], -} - -/// The 4:2:0 / 4:2:2 LJ92 variants of Sony (M/S ARW) and Canon (sRAW / mRAW): T.81 MCU ordering and differences, -/// modulo 2^16. [`Prediction`] selects the predictor each maker uses. -/// -/// Sony: at the first column, the top luma row predicts from the previous MCU row's top -/// sample (two image rows above), and the bottom row from the current top sample. -/// Observed black-box: using the immediately preceding image row introduces tile seams. -pub(crate) fn decode_subsampled(d: &[u8], max_samples: usize, prediction: Prediction) -> Result { - let h = parse_header(d)?; - let vertical = check_subsampled(&h)?; - let pixels = h.width.checked_mul(h.height).ok_or_else(|| err("frame too large"))?; - let chroma = pixels / (2 * vertical); - let total = pixels.checked_add(chroma.checked_mul(2).ok_or_else(|| err("frame too large"))?).ok_or_else(|| err("frame too large"))?; - if total > max_samples { - return Err(RawError::Limit("lossless JPEG frame larger than expected")); - } - let entropy = &d[h.scan_start..]; - if (entropy.len() as u64 + 64) * 8 < total as u64 { - return Err(err("entropy data too short for frame")); - } - let tables: Vec<&Huffman> = h - .table_for - .iter() - .map(|&t| h.tables.get(t).and_then(Option::as_ref).ok_or_else(|| err("missing Huffman table"))) - .collect::>()?; - let mut planes = [vec![0u16; pixels], vec![0u16; chroma], vec![0u16; chroma]]; - let mut br = BitReader::new(entropy); - let init = 1i32 << (h.precision - h.pt - 1); - // Sequential prediction: the last sample of each component, and the first sample of its previous MCU row - let mut last = [init; 3]; - let mut row_first = [init; 3]; - for my in 0..h.height / vertical { - for mx in 0..h.width / 2 { - for (c, plane) in planes.iter_mut().enumerate() { - let horizontal_factor = if c == 0 { 2 } else { 1 }; - let vertical_factor = if c == 0 { vertical } else { 1 }; - let width = h.width * horizontal_factor / 2; - for dy in 0..vertical_factor { - for dx in 0..horizontal_factor { - let (x, y) = (mx * horizontal_factor + dx, my * vertical_factor + dy); - let i = y * width + x; - let pred = match prediction { - Prediction::Geometric if x > 0 => plane[i - 1] as i32, - Prediction::Geometric if c == 0 && dy == 0 && y >= vertical => plane[i - vertical * width] as i32, - Prediction::Geometric if y > 0 => plane[i - width] as i32, - Prediction::Geometric => init, - Prediction::Sequential if mx == 0 && dx == 0 && dy == 0 => row_first[c], - Prediction::Sequential => last[c], - }; - let ssss = tables[c].decode(&mut br)?; - if ssss > 16 { - return Err(err("invalid difference category")); - } - let value = ((pred + diff_value(&mut br, ssss)) & 0xffff) as u16; - plane[i] = value; - last[c] = i32::from(value); - if mx == 0 && dx == 0 && dy == 0 { - row_first[c] = i32::from(value); - } - } - } - } - } - if br.overrun > br.bits { - return Err(err("entropy data exhausted")); - } - } - if h.pt > 0 { - for plane in &mut planes { - for v in plane { - *v <<= h.pt; - } - } - } - Ok(FrameSubsampled { width: h.width, height: h.height, vertical_subsampling: vertical, planes }) -} - -/// Decode a lossless JPEG stream. `max_samples` bounds the allocation (hostile headers). -pub fn decode(d: &[u8], max_samples: usize) -> Result { - let h = parse_header(d)?; - check_full_resolution(&h)?; - if h.predictor == 8 { - return hasselblad_frame(d, &h, max_samples); - } - let (w, ht, nc) = (h.width, h.height, h.comps.len()); - if w == 0 || ht == 0 { - return Err(err("zero frame size")); - } - let total = w.checked_mul(ht).and_then(|v| v.checked_mul(nc)).ok_or_else(|| err("frame too large"))?; - if total > max_samples { - return Err(RawError::Limit("lossless JPEG frame larger than expected")); - } - // The entropy data must hold at least ~1 bit per sample; reject absurd headers early. - let entropy = &d[h.scan_start..]; - if (entropy.len() as u64 + 64) * 8 < total as u64 { - return Err(err("entropy data too short for frame")); - } - let tables: Vec<&Huffman> = h - .table_for - .iter() - .map(|&t| h.tables.get(t).and_then(Option::as_ref).ok_or_else(|| err("scan uses an undefined Huffman table"))) - .collect::>()?; - let mut out = vec![0u16; total]; - let mut br = BitReader::new(entropy); - let init = 1i32 << (h.precision - h.pt - 1); - let mask = 0xffffi32; - let row_len = w * nc; - let pred = h.predictor; - let mut restart_left = h.restart; - let mut first_line = true; // first line of image or restart interval - let mut reset_pending = true; - for y in 0..ht { - let (prev_rows, cur_rows) = out.split_at_mut(y * row_len); - let cur = &mut cur_rows[..row_len]; - let prev = if y > 0 { &prev_rows[(y - 1) * row_len..] } else { &[][..] }; - for x in 0..w { - if h.restart > 0 { - if restart_left == 0 { - if !br.restart() { - return Err(err("missing restart marker")); - } - restart_left = h.restart; - first_line = true; - reset_pending = true; - } - restart_left -= 1; - } - for c in 0..nc { - let i = x * nc + c; - let p = if reset_pending { - init - } else if first_line { - if x == 0 { prev.get(i).map_or(init, |&v| v as i32) } else { cur[i - nc] as i32 } - } else if x == 0 || pred == 0 { - if pred == 0 { 0 } else { prev[i] as i32 } - } else { - let ra = cur[i - nc] as i32; - let rb = prev[i] as i32; - let rc = prev[i - nc] as i32; - match pred { - 1 => ra, - 2 => rb, - 3 => rc, - 4 => ra + rb - rc, - 5 => ra + ((rb - rc) >> 1), - 6 => rb + ((ra - rc) >> 1), - _ => (ra + rb) >> 1, - } - }; - let ssss = tables[c].decode(&mut br)?; - let diff = diff_value(&mut br, ssss); - cur[i] = ((p + diff) & mask) as u16; - } - reset_pending = false; - } - first_line = false; - if br.overrun > 64 * 8 { - return Err(err("entropy data exhausted")); - } - } - if h.pt > 0 { - for v in &mut out { - *v <<= h.pt; - } - } - Ok(Frame { width: w, height: ht, components: nc, precision: h.precision, predictor: pred, point_transform: h.pt, data: out }) -} - -// ------------------------------------------------------------------------------------------------ encoder - -/// Build Huffman code lengths from frequencies (T.81 Annex K.2, Figures K.1–K.3), limited to 16 bits. -fn code_lengths(freq_in: &[u32; 17]) -> ([u8; 16], Vec) { - let mut freq = [0i64; 18]; - for (i, &f) in freq_in.iter().enumerate() { - freq[i] = f as i64; - } - freq[17] = 1; // reserved symbol so no code is all ones - let mut codesize = [0usize; 18]; - let mut others = [-1i32; 18]; - loop { - // V1: least frequency > 0 (largest index on ties), V2: next least - let mut v1 = -1i32; - let mut v2 = -1i32; - for i in 0..18 { - if freq[i] > 0 && (v1 < 0 || freq[i] <= freq[v1 as usize]) { - v1 = i as i32; - } - } - for i in 0..18 { - if freq[i] > 0 && i as i32 != v1 && (v2 < 0 || freq[i] <= freq[v2 as usize]) { - v2 = i as i32; - } - } - if v2 < 0 { - break; - } - let (a, b) = (v1 as usize, v2 as usize); - freq[a] += freq[b]; - freq[b] = 0; - let mut x = a; - codesize[x] += 1; - while others[x] >= 0 { - x = others[x] as usize; - codesize[x] += 1; - } - others[x] = b as i32; - let mut x = b; - codesize[x] += 1; - while others[x] >= 0 { - x = others[x] as usize; - codesize[x] += 1; - } - } - let mut bits = [0i32; 33]; - for &cs in &codesize { - if cs > 0 { - bits[cs.min(32)] += 1; - } - } - // Adjust_BITS (Figure K.3) - let mut i = 32; - while i > 16 { - while bits[i] > 0 { - let mut j = i - 2; - while bits[j] == 0 { - j -= 1; - } - bits[i] -= 2; - bits[i - 1] += 1; - bits[j + 1] += 2; - bits[j] -= 1; - } - i -= 1; - } - while bits[i] == 0 { - i -= 1; - } - bits[i] -= 1; // remove the reserved code - let mut counts = [0u8; 16]; - for l in 1..=16 { - counts[l - 1] = bits[l] as u8; - } - // Sort_input (Figure K.4): symbols by code size - let mut values = Vec::new(); - for l in 1..=32 { - for (s, &cs) in codesize.iter().enumerate().take(17) { - if cs == l { - values.push(s as u8); - } - } - } - (counts, values) -} - -/// Canonical codes for a table: symbol → (code, length). -fn canonical_codes(counts: &[u8; 16], values: &[u8]) -> [(u32, u8); 17] { - let mut table = [(0u32, 0u8); 17]; - let mut code = 0u32; - let mut k = 0; - for len in 1..=16u8 { - for _ in 0..counts[len as usize - 1] { - if let Some(&s) = values.get(k) - && (s as usize) < 17 - { - table[s as usize] = (code, len); - } - code += 1; - k += 1; - } - code <<= 1; - } - table -} - -struct BitWriter { - out: Vec, - acc: u64, - n: u32, -} - -impl BitWriter { - fn put(&mut self, v: u32, bits: u32) { - if bits == 0 { - return; - } - self.acc = (self.acc << bits) | (v as u64 & ((1u64 << bits) - 1)); - self.n += bits; - while self.n >= 8 { - let b = (self.acc >> (self.n - 8)) as u8; - self.out.push(b); - if b == 0xff { - self.out.push(0); - } - self.n -= 8; - } - } - fn flush(&mut self) { - if self.n > 0 { - let pad = 8 - self.n; - self.put((1 << pad) - 1, pad); - } - } -} - -fn ssss_of(diff: i32) -> u8 { - if diff == 0 { - 0 - } else if diff == 32768 || diff == -32768 { - 16 - } else { - 32 - (diff.unsigned_abs()).leading_zeros() as u8 - } -} - -/// Encode samples (`width × height × components`, interleaved) as a lossless JPEG with `predictor` (1–7) and -/// `precision` bits. `restart` > 0 inserts restart markers every `restart` MCUs (pixels). -pub fn encode(data: &[u16], width: usize, height: usize, components: usize, precision: u8, predictor: u8, restart: usize) -> Vec { - assert!((1..=4).contains(&components) && (2..=16).contains(&precision) && (1..=7).contains(&predictor)); - assert_eq!(data.len(), width * height * components); - let init = 1i32 << (precision - 1); - let row_len = width * components; - // compute differences in the same order as the decoder - let mut diffs = vec![0i32; data.len()]; - let mut restart_left = restart; - let mut first_line = true; - let mut reset_pending = true; - let mut marks = Vec::new(); // sample index where an RST marker precedes - for y in 0..height { - for x in 0..width { - if restart > 0 { - if restart_left == 0 { - marks.push((y * width + x) * components); - restart_left = restart; - first_line = true; - reset_pending = true; - } - restart_left -= 1; - } - for c in 0..components { - let i = y * row_len + x * components + c; - let p = if reset_pending { - init - } else if first_line { - if x == 0 { data[i - row_len] as i32 } else { data[i - components] as i32 } - } else if x == 0 { - data[i - row_len] as i32 - } else { - let ra = data[i - components] as i32; - let rb = data[i - row_len] as i32; - let rc = data[i - row_len - components] as i32; - match predictor { - 1 => ra, - 2 => rb, - 3 => rc, - 4 => ra + rb - rc, - 5 => ra + ((rb - rc) >> 1), - 6 => rb + ((ra - rc) >> 1), - _ => (ra + rb) >> 1, - } - }; - // modulo 2^16 difference mapped into [-32767, 32768] - let mut d = (data[i] as i32 - p) & 0xffff; - if d > 32768 { - d -= 65536; - } - diffs[i] = d; - } - reset_pending = false; - } - first_line = false; - } - let mut tables = Vec::new(); - for c in 0..components { - let mut freq = [0u32; 17]; - for d in diffs.iter().skip(c).step_by(components) { - freq[ssss_of(*d) as usize] += 1; - } - let (counts, values) = code_lengths(&freq); - tables.push((counts, values)); - } - let mut out = vec![0xff, 0xd8]; - // SOF3 - out.extend_from_slice(&[0xff, 0xc3]); - out.extend_from_slice(&((8 + 3 * components) as u16).to_be_bytes()); - out.push(precision); - out.extend_from_slice(&(height as u16).to_be_bytes()); - out.extend_from_slice(&(width as u16).to_be_bytes()); - out.push(components as u8); - for c in 0..components { - out.extend_from_slice(&[c as u8 + 1, 0x11, 0]); - } - // DHT - for (c, (counts, values)) in tables.iter().enumerate() { - out.extend_from_slice(&[0xff, 0xc4]); - out.extend_from_slice(&((2 + 17 + values.len()) as u16).to_be_bytes()); - out.push(c as u8); - out.extend_from_slice(counts); - out.extend_from_slice(values); - } - if restart > 0 { - out.extend_from_slice(&[0xff, 0xdd, 0, 4]); - out.extend_from_slice(&(restart as u16).to_be_bytes()); - } - // SOS - out.extend_from_slice(&[0xff, 0xda]); - out.extend_from_slice(&((6 + 2 * components) as u16).to_be_bytes()); - out.push(components as u8); - for c in 0..components { - out.extend_from_slice(&[c as u8 + 1, (c as u8) << 4]); - } - out.extend_from_slice(&[predictor, 0, 0]); - let codes: Vec<[(u32, u8); 17]> = tables.iter().map(|(c, v)| canonical_codes(c, v)).collect(); - let mut bw = BitWriter { out, acc: 0, n: 0 }; - let mut mark_iter = marks.iter().peekable(); - let mut rst = 0u8; - for (i, &d) in diffs.iter().enumerate() { - if mark_iter.peek().is_some_and(|&&m| m == i) { - mark_iter.next(); - bw.flush(); - bw.out.extend_from_slice(&[0xff, 0xd0 + rst]); - rst = (rst + 1) & 7; - bw.acc = 0; - } - let c = i % components; - let s = ssss_of(d); - let (code, len) = codes[c][s as usize]; - bw.put(code, len as u32); - if s > 0 && s < 16 { - let v = if d < 0 { d - 1 } else { d }; - bw.put(v as u32 & ((1 << s) - 1), s as u32); - } - } - bw.flush(); - let mut out = bw.out; - out.extend_from_slice(&[0xff, 0xd9]); - out -} - -#[cfg(test)] -pub(crate) mod tests; diff --git a/crates/raw/src/ljpeg/tests.rs b/crates/raw/src/ljpeg/tests.rs deleted file mode 100644 index c5c6ccf25c..0000000000 --- a/crates/raw/src/ljpeg/tests.rs +++ /dev/null @@ -1,311 +0,0 @@ -use super::*; - -/// Independent 4×4, 16-bit Sony 4:2:0 stream. Hand-specified differences in MCU order. -pub(crate) fn fixture_420() -> Vec { - fixture_subsampled(4, 4, 0x22, &[-31768, 1, 1000, 1, -16384, -16284, 1, 1, 1, 1, 1, 2, 100, 1, 1000, 1, 100, 100, 1, 1, 1, 1, 1, 2]) -} - -/// A 16-bit three-component frame of `width × height` pixels with the given luma `sampling` (`0x21` / `0x22`) -/// and one shared 5-bit Huffman table, whose differences are written as given (MCU order). -pub(crate) fn fixture_subsampled(width: u8, height: u8, sampling: u8, differences: &[i32]) -> Vec { - let mut out = vec![0xff, 0xd8, 0xff, 0xc3, 0, 17, 16, 0, height, 0, width, 3, 1, sampling, 0, 2, 0x11, 0, 3, 0x11, 0]; - out.extend_from_slice(&[0xff, 0xc4, 0, 36, 0]); - let mut counts = [0; 16]; - counts[4] = 17; - out.extend_from_slice(&counts); - out.extend(0..=16); - out.extend_from_slice(&[0xff, 0xda, 0, 12, 3, 1, 0, 2, 0, 3, 0, 1, 0, 0]); - let mut bw = BitWriter { out, acc: 0, n: 0 }; - for &d in differences { - let s = ssss_of(d); - bw.put(s as u32, 5); - if s > 0 && s < 16 { - let v = if d < 0 { d - 1 } else { d }; - bw.put(v as u32 & ((1 << s) - 1), s as u32); - } - } - bw.flush(); - bw.out.extend_from_slice(&[0xff, 0xd9]); - bw.out -} - -#[test] -fn horizontal_only_subsampling_preserves_rows_and_chroma() { - // Independent 4×2, 16-bit 4:2:2 stream: two luma samples, Cb, Cr per MCU. - let enc = fixture_subsampled(4, 2, 0x21, &[-31768, 1, -16384, -16284, 1, 1, 1, 2, 100, 1, 100, 100, 1, 1, 1, 2]); - let frame = decode_subsampled(&enc, 16, Prediction::Geometric).unwrap(); - assert_eq!((frame.width, frame.height, frame.vertical_subsampling), (4, 2, 1)); - assert_eq!(frame.planes[0], [1000, 1001, 1002, 1003, 1100, 1101, 1102, 1103]); - assert_eq!(frame.planes[1], [16384, 16385, 16484, 16485]); - assert_eq!(frame.planes[2], [16484, 16486, 16584, 16586]); - assert!(decode(&enc, 24).is_err()); - assert!(matches!(decode_subsampled(&enc, 15, Prediction::Geometric), Err(RawError::Limit(_)))); - assert!(decode_subsampled(&enc[..enc.len() - 6], 16, Prediction::Geometric).is_err()); -} - -#[test] -fn subsampled_mcu_order_preserves_each_plane() { - let enc = fixture_420(); - let frame = decode_subsampled(&enc, 24, Prediction::Geometric).unwrap(); - assert_eq!((frame.width, frame.height), (4, 4)); - assert_eq!(frame.planes[0], [1000, 1001, 1002, 1003, 2000, 2001, 2002, 2003, 1100, 1101, 1102, 1103, 2100, 2101, 2102, 2103]); - assert_eq!(frame.planes[1], [16384, 16385, 16484, 16485]); - assert_eq!(frame.planes[2], [16484, 16486, 16584, 16586]); - assert!(decode(&enc, 48).is_err()); // CFA API must keep rejecting subsampling. - assert!(matches!(decode_subsampled(&enc, 23, Prediction::Geometric), Err(RawError::Limit(_)))); - assert!(decode_subsampled(&enc[..enc.len() - 6], 24, Prediction::Geometric).is_err()); - let mut bad = enc.clone(); - bad[10] = 3; // odd frame width - assert!(frame_info_subsampled(&bad).is_err()); - let sos = bad.windows(2).position(|w| w == [0xff, 0xda]).unwrap(); - bad = enc.clone(); - bad[sos + 11] = 2; // unsupported predictor - assert!(frame_info_subsampled(&bad).is_err()); -} - -#[test] -fn sequential_prediction_chains_each_component_in_decoding_order() { - // Canon sRAW / mRAW: the same stream as `subsampled_mcu_order_preserves_each_plane`, but each component - // continues from its previous sample in decoding order (the second luma row of an MCU follows the first), - // and a new MCU row starts from the first sample of the previous one. Worked out by hand from init 32768. - let enc = fixture_420(); - let frame = decode_subsampled(&enc, 24, Prediction::Sequential).unwrap(); - assert_eq!((frame.width, frame.height, frame.vertical_subsampling), (4, 4, 2)); - assert_eq!(frame.planes[0], [1000, 1001, 2003, 2004, 2001, 2002, 2005, 2006, 1100, 1101, 2103, 2104, 2101, 2102, 2105, 2106]); - assert_eq!(frame.planes[1], [16384, 16385, 16484, 16485]); - assert_eq!(frame.planes[2], [16484, 16486, 16584, 16586]); - // 4:2:2 has one luma row per MCU row, so both predictions agree - let enc = fixture_subsampled(4, 2, 0x21, &[-31768, 1, -16384, -16284, 1, 1, 1, 2, 100, 1, 100, 100, 1, 1, 1, 2]); - assert_eq!( - decode_subsampled(&enc, 16, Prediction::Sequential).unwrap().planes, - decode_subsampled(&enc, 16, Prediction::Geometric).unwrap().planes - ); -} - -fn noise(n: usize, bits: u32, seed: u64) -> Vec { - let mut s = seed; - (0..n) - .map(|i| { - s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - let smooth = ((i % 97) as u32 * 37) % (1 << bits); - let jitter = ((s >> 33) as u32) % 64; - ((smooth + jitter) % (1 << bits)) as u16 - }) - .collect() -} - -#[test] -fn roundtrip_all_predictors_components_precisions() { - for pred in 1..=7u8 { - for comps in 1..=4usize { - for bits in [8u8, 12, 14, 16] { - let (w, h) = (13, 7); - let data = noise(w * h * comps, bits as u32, (pred as u64) * 31 + comps as u64); - let enc = encode(&data, w, h, comps, bits, pred, 0); - let f = decode(&enc, usize::MAX).unwrap(); - assert_eq!((f.width, f.height, f.components, f.precision, f.predictor), (w, h, comps, bits, pred)); - assert_eq!(f.data, data, "pred {pred} comps {comps} bits {bits}"); - } - } - } -} - -#[test] -fn roundtrip_extremes_and_restarts() { - // alternating 0 / 65535 forces SSSS = 16 differences - let data: Vec = (0..64).map(|i| if i % 2 == 0 { 0 } else { 65535 }).collect(); - for pred in 1..=7 { - let enc = encode(&data, 8, 8, 1, 16, pred, 0); - assert_eq!(decode(&enc, usize::MAX).unwrap().data, data); - } - let data = noise(20 * 9 * 2, 12, 5); - for rst in [1usize, 7, 20, 40] { - let enc = encode(&data, 20, 9, 2, 12, 6, rst); - assert_eq!(decode(&enc, usize::MAX).unwrap().data, data, "restart {rst}"); - } -} - -#[test] -fn constant_image_single_symbol_table() { - let data = vec![1234u16; 16 * 4]; - let enc = encode(&data, 16, 4, 1, 14, 1, 0); - assert_eq!(decode(&enc, usize::MAX).unwrap().data, data); -} - -#[test] -fn rejects_bad_streams() { - assert!(decode(&[], 100).is_err()); - assert!(decode(&[0xff, 0xd8, 0xff, 0xd9], 100).is_err()); - let data = noise(64, 12, 1); - let enc = encode(&data, 8, 8, 1, 12, 1, 0); - assert!(matches!(decode(&enc, 10), Err(RawError::Limit(_)))); - for n in 0..enc.len() { - let _ = decode(&enc[..n], usize::MAX); - } - let mut bad = enc.clone(); - for i in (20..bad.len()).step_by(3) { - bad[i] ^= 0x5a; - } - let _ = decode(&bad, usize::MAX); -} - -// --- selection value 8 (Hasselblad 3FR / FFF) --- - -/// SOI, SOF3 (16 bits, `height` x `width`, one component), a DHT and an SOS with selection value 8, then -/// `entropy` and EOI. -fn hasselblad_stream(width: u16, height: u16, counts: &[u8; 16], values: &[u8], entropy: &[u8]) -> Vec { - let mut out = vec![0xff, 0xd8, 0xff, 0xc3, 0, 11, 16]; - out.extend_from_slice(&height.to_be_bytes()); - out.extend_from_slice(&width.to_be_bytes()); - out.extend_from_slice(&[1, 0, 0x11, 0]); - out.extend_from_slice(&[0xff, 0xc4]); - out.extend_from_slice(&((2 + 17 + values.len()) as u16).to_be_bytes()); - out.push(0); - out.extend_from_slice(counts); - out.extend_from_slice(values); - out.extend_from_slice(&[0xff, 0xda, 0, 8, 1, 0, 0, 8, 0, 0]); - out.extend_from_slice(entropy); - out.extend_from_slice(&[0xff, 0xd9]); - out -} - -/// Codes: SSSS 0 = `00`, 1 = `01`, 2 = `100`, 15 = `101`, 16 = `110`. -const HAND_COUNTS: [u8; 16] = [0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; -const HAND_VALUES: [u8; 5] = [0, 1, 2, 15, 16]; - -/// A 4 x 2 frame written out bit by bit: -/// - row 0, pair 1: codes `110` `110` (SSSS 16 twice), then 16 bits each (`FFFF`, `7FFF`) that do not count: -/// both samples are 32768 - 32768 = 0; -/// - row 0, pair 2: codes `01` `100`, bits `1` (+1) and `01` (-2): 0 + 1 = 1 and 0 - 2 = 65534 (modulo 2^16); -/// - row 1, pair 1: codes `00` `01`, bit `0` (-1): both predictors start again at 32768, so 32768 and 32767; -/// - row 1, pair 2: codes `100` `00`, bits `11` (+3): 32771 and 32767. -/// -/// 58 bits, padded with zeros to two 32-bit words `DBFFFDFF` `FD9450C0`, stored little-endian. The `FF FD` -/// they start with would be a marker to a T.81 reader: this coding has no byte stuffing. -const HAND_WORDS: [u8; 8] = [0xff, 0xfd, 0xff, 0xdb, 0xc0, 0x50, 0x94, 0xfd]; -const HAND_SAMPLES: [u16; 8] = [0, 0, 1, 65534, 32768, 32767, 32771, 32767]; - -#[test] -fn selection_value_8_known_answer() { - let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS); - assert_eq!(frame_info(&enc).unwrap(), (4, 2, 1, 16)); - let f = decode(&enc, 8).unwrap(); - assert_eq!((f.width, f.height, f.components, f.predictor), (4, 2, 1, 8)); - assert_eq!(f.data, HAND_SAMPLES); - assert_eq!(decode_hasselblad(&enc, 8).unwrap().data, HAND_SAMPLES); - assert!(matches!(decode(&enc, 7), Err(RawError::Limit(_)))); -} - -/// The same bits in plain byte order (not 32-bit little-endian words) are a different stream. -#[test] -fn selection_value_8_reads_little_endian_words() { - let mut plain = HAND_WORDS; - plain[..4].reverse(); - plain[4..].reverse(); - let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &plain); - assert_ne!(decode(&enc, 8).map(|f| f.data).ok(), Some(HAND_SAMPLES.to_vec())); -} - -#[test] -fn selection_value_8_rejects_bad_streams() { - // one word is not enough for the second row - let short = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS[..4]); - assert!(decode(&short, 8).is_err()); - // a category above 16 - let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &[0, 1, 2, 15, 17], &HAND_WORDS); - assert!(decode(&enc, 8).is_err()); - // layouts never seen with selection value 8 are not guessed at - let mut odd = hasselblad_stream(3, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS); - assert!(matches!(frame_info(&odd), Err(RawError::Unsupported(_)))); - assert!(matches!(decode(&odd, 8), Err(RawError::Unsupported(_)))); - odd = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS); - odd[6] = 14; // precision - assert!(matches!(decode(&odd, 8), Err(RawError::Unsupported(_)))); - // selection values above 8 stay unknown - let mut nine = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS); - let sos = nine.windows(2).position(|w| w == [0xff, 0xda]).unwrap(); - nine[sos + 7] = 9; - assert!(matches!(decode(&nine, 8), Err(RawError::Unsupported(w)) if w.contains("selection value 9"))); - // every prefix fails cleanly - let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS); - for n in 0..enc.len() { - let _ = decode(&enc[..n], 8); - } -} - -/// Test-only writer of the selection-value-8 coding (the inverse of the rule in [`decode_hasselblad`]), with -/// a 5-bit code for every category. Category-16 differences carry `FFFF` as their ignored bits. -pub(crate) fn encode_hasselblad(data: &[u16], width: usize, height: usize) -> Vec { - assert!(width.is_multiple_of(2) && data.len() == width * height); - let mut bits: Vec = vec![]; - let put = |bits: &mut Vec, v: u32, n: u32| { - for i in (0..n).rev() { - bits.push((v >> i) & 1 == 1); - } - }; - for row in data.chunks_exact(width) { - let mut last = [32768i32, 32768]; - for pair in row.as_chunks::<2>().0 { - let mut d = [0i32; 2]; - for k in 0..2 { - let mut v = (pair[k] as i32 - last[k]) & 0xffff; - if v >= 32768 { - v -= 65536; - } - d[k] = v; - last[k] = pair[k] as i32; - } - let s = [ssss_of(d[0]), ssss_of(d[1])]; - put(&mut bits, s[0] as u32, 5); - put(&mut bits, s[1] as u32, 5); - for k in 0..2 { - match s[k] { - 0 => {} - 16 => put(&mut bits, 0xffff, 16), - n => { - let v = if d[k] < 0 { d[k] - 1 } else { d[k] }; - put(&mut bits, v as u32 & ((1 << n) - 1), n as u32); - } - } - } - } - } - let mut entropy = vec![]; - for word in bits.chunks(32) { - let w = word.iter().enumerate().fold(0u32, |a, (i, &b)| a | ((b as u32) << (31 - i))); - entropy.extend_from_slice(&w.to_le_bytes()); - } - let mut counts = [0u8; 16]; - counts[4] = 17; - let values: Vec = (0..=16).collect(); - hasselblad_stream(width as u16, height as u16, &counts, &values, &entropy) -} - -#[test] -fn selection_value_8_round_trips_through_the_test_writer() { - // extremes force SSSS 16 and wrap-around; noise exercises every other category - let mut data = noise(10 * 7, 16, 9); - data[0] = 0; - data[1] = 65535; - data[2] = 65535; - data[3] = 0; - let enc = encode_hasselblad(&data, 10, 7); - assert_eq!(decode(&enc, 70).unwrap().data, data); -} - -#[test] -fn code_lengths_are_limited_to_16() { - // Fibonacci-like frequencies produce very long codes before adjustment - let mut f = [0u32; 17]; - let (mut a, mut b) = (1u32, 1u32); - for x in f.iter_mut() { - *x = a; - let c = a.saturating_add(b); - a = b; - b = c; - } - let (counts, values) = code_lengths(&f); - assert_eq!(counts.iter().map(|&c| c as usize).sum::(), 17); - assert_eq!(values.len(), 17); - assert!(Huffman::new(&counts, &values).is_ok()); -} diff --git a/crates/raw/src/ljpeg_fixtures.rs b/crates/raw/src/ljpeg_fixtures.rs new file mode 100644 index 0000000000..b639b2fa4b --- /dev/null +++ b/crates/raw/src/ljpeg_fixtures.rs @@ -0,0 +1,70 @@ +//! Test fixtures: hand-built lossless JPEG streams (the subsampled YCbCr coding Sony uses) for the ARW tests. + +/// Independent 4×4, 16-bit Sony 4:2:0 stream. Hand-specified differences in MCU order. +pub(crate) fn fixture_420() -> Vec { + fixture_subsampled(4, 4, 0x22, &[-31768, 1, 1000, 1, -16384, -16284, 1, 1, 1, 1, 1, 2, 100, 1, 1000, 1, 100, 100, 1, 1, 1, 1, 1, 2]) +} + +/// A 16-bit three-component frame of `width × height` pixels with the given luma `sampling` (`0x21` / `0x22`) +/// and one shared 5-bit Huffman table, whose differences are written as given (MCU order). +pub(crate) fn fixture_subsampled(width: u8, height: u8, sampling: u8, differences: &[i32]) -> Vec { + let mut out = vec![0xff, 0xd8, 0xff, 0xc3, 0, 17, 16, 0, height, 0, width, 3, 1, sampling, 0, 2, 0x11, 0, 3, 0x11, 0]; + out.extend_from_slice(&[0xff, 0xc4, 0, 36, 0]); + let mut counts = [0; 16]; + counts[4] = 17; + out.extend_from_slice(&counts); + out.extend(0..=16); + out.extend_from_slice(&[0xff, 0xda, 0, 12, 3, 1, 0, 2, 0, 3, 0, 1, 0, 0]); + let mut bw = BitWriter { out, acc: 0, n: 0 }; + for &d in differences { + let s = ssss_of(d); + bw.put(s as u32, 5); + if s > 0 && s < 16 { + let v = if d < 0 { d - 1 } else { d }; + bw.put(v as u32 & ((1 << s) - 1), s as u32); + } + } + bw.flush(); + bw.out.extend_from_slice(&[0xff, 0xd9]); + bw.out +} + +struct BitWriter { + out: Vec, + acc: u64, + n: u32, +} + +impl BitWriter { + fn put(&mut self, v: u32, bits: u32) { + if bits == 0 { + return; + } + self.acc = (self.acc << bits) | (v as u64 & ((1u64 << bits) - 1)); + self.n += bits; + while self.n >= 8 { + let b = (self.acc >> (self.n - 8)) as u8; + self.out.push(b); + if b == 0xff { + self.out.push(0); + } + self.n -= 8; + } + } + fn flush(&mut self) { + if self.n > 0 { + let pad = 8 - self.n; + self.put((1 << pad) - 1, pad); + } + } +} + +fn ssss_of(diff: i32) -> u8 { + if diff == 0 { + 0 + } else if diff == 32768 || diff == -32768 { + 16 + } else { + 32 - (diff.unsigned_abs()).leading_zeros() as u8 + } +} diff --git a/crates/raw/src/llvc.rs b/crates/raw/src/llvc.rs index 17408c7605..a8d5ca7b11 100644 --- a/crates/raw/src/llvc.rs +++ b/crates/raw/src/llvc.rs @@ -3,7 +3,7 @@ //! Clean-room: written from SMPTE RDD 34:2015 §6.3 (Figures 6.5-6.8) and checked against its worked //! example (Figure 6.9) and Phase 0 oracle vectors. No other raw decoder's source was consulted. -use crate::vendor::pef::Bits; +use crate::vendor::huffman::Bits; use crate::{RawError, Result}; /// Largest coefficient bit depth (DPT) a stream may select; keeps `Bits::get` in range. @@ -328,7 +328,7 @@ pub(crate) fn reconstruct3(b: &Bands3, phases: [u8; 3]) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::vendor::pef::Bits; + use crate::vendor::huffman::Bits; fn bits_of(s: &str) -> Vec { let mut out = vec![0u8; s.len().div_ceil(8)]; diff --git a/crates/raw/src/opcodes.rs b/crates/raw/src/opcodes.rs index 2f5d51fae0..7cca133d6c 100644 --- a/crates/raw/src/opcodes.rs +++ b/crates/raw/src/opcodes.rs @@ -1,6 +1,6 @@ //! DNG opcode lists (`OpcodeList1/2/3`, DNG 1.7 chapter 7). Opcode lists are always big-endian. //! -//! Parsed: every opcode (unknown ones are kept as [`Opcode::Unknown`]). Applied: `WarpRectilinear`, +//! Parsed (by `craft-raw`): every opcode (unknown ones are kept as [`Opcode::Unknown`]). Applied: `WarpRectilinear`, //! `WarpRectilinear2` (opcode 14, DNG 1.6; see [`Opcode::WarpRectilinear2`]), `FixVignetteRadial`, //! `FixBadPixelsConstant`, `FixBadPixelsList`, `MapTable`, `MapPolynomial`, `GainMap`, `DeltaPerRow/Column`, //! `ScalePerRow/Column`. `TrimBounds` and `WarpFisheye` are recorded but not applied. @@ -12,511 +12,13 @@ //! Value convention: list 1 runs on raw sample values (16-bit scale), lists 2 and 3 on values normalised to //! [0, 1]; table/polynomial/delta opcodes are defined on the normalised range and are rescaled accordingly. +pub use craft_raw::opcodes::{Area, Opcode, OpcodeLists, WR2_LEN, applied_ops, parse_list, wr2_factor, write_list}; + use crate::{Cfa, Rgb32f}; -use serde::{Deserialize, Serialize}; -/// Rectangular area + plane selection + pitch shared by the "area" opcodes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Area { - pub top: u32, - pub left: u32, - pub bottom: u32, - pub right: u32, - pub plane: u32, - pub planes: u32, - pub row_pitch: u32, - pub col_pitch: u32, -} - -/// Values per coefficient set of `WarpRectilinear2`: 15 radial (`kr0..kr14`), 2 tangential (`kt0`, `kt1`), -/// `min_valid_radius`, `max_valid_radius`. -pub const WR2_LEN: usize = 19; -/// Most coefficient sets (planes) a `WarpRectilinear2` may carry. -const WR2_MAX_PLANES: usize = 4; -/// Largest magnitude accepted for a `WarpRectilinear2` coefficient (a real lens fit is far below this; it keeps the -/// polynomial finite for any radius up to 1). -const WR2_MAX_COEF: f64 = 1e9; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub enum Opcode { - /// Per-plane radial (kr0..kr3) + tangential (kt0, kt1) coefficients and the relative optical centre. - WarpRectilinear { - planes: Vec<[f64; 6]>, - center: [f64; 2], - }, - WarpFisheye { - planes: Vec<[f64; 4]>, - center: [f64; 2], - }, - /// DNG 1.6 `WarpRectilinear2` (opcode 14; DNG specification 1.6.0.0, chapter 7, "WarpRectilinear2"). Per plane - /// `[kr0 .. kr14, kt0, kt1, min_valid_radius, max_valid_radius]` ([`WR2_LEN`] values, see [`wr2_factor`]), - /// the relative optical centre, and `reciprocalRadial`. `optional` is opcode flag bit 0, which turns on the skip - /// rule for the next warp opcode. - WarpRectilinear2 { - planes: Vec<[f64; WR2_LEN]>, - center: [f64; 2], - reciprocal: bool, - optional: bool, - }, - FixVignetteRadial { - k: [f64; 5], - center: [f64; 2], - }, - FixBadPixelsConstant { - constant: u32, - bayer_phase: u32, - }, - FixBadPixelsList { - bayer_phase: u32, - points: Vec<(u32, u32)>, - rects: Vec<[u32; 4]>, - }, - TrimBounds { - top: u32, - left: u32, - bottom: u32, - right: u32, - }, - MapTable { - area: Area, - table: Vec, - }, - MapPolynomial { - area: Area, - coefficients: Vec, - }, - GainMap { - area: Area, - points_v: u32, - points_h: u32, - spacing: [f64; 2], - origin: [f64; 2], - map_planes: u32, - gains: Vec, - }, - DeltaPerRow { - area: Area, - deltas: Vec, - }, - DeltaPerColumn { - area: Area, - deltas: Vec, - }, - ScalePerRow { - area: Area, - scales: Vec, - }, - ScalePerColumn { - area: Area, - scales: Vec, - }, - Unknown { - id: u32, - flags: u32, - params: Vec, - }, -} - -impl Opcode { - /// Whether [`apply_list`] / [`apply_list3`] implement this opcode. - pub fn is_applied(&self) -> bool { - !matches!(self, Opcode::Unknown { .. } | Opcode::TrimBounds { .. } | Opcode::WarpFisheye { .. }) - } - - /// Whether this is a lens correction (`WarpRectilinear`, `WarpRectilinear2`, `FixVignetteRadial`): from a DNG, or - /// the equivalent of a camera's own correction recorded in its raw (Panasonic RW2). Developers that apply these - /// through the "profile corrections" of the develop settings remove them before demosaicing. - pub fn is_lens_correction(&self) -> bool { - matches!(self, Opcode::WarpRectilinear { .. } | Opcode::WarpRectilinear2 { .. } | Opcode::FixVignetteRadial { .. }) - } - - /// This lens correction re-expressed for the part `crop` of the `width × height` image it was written for: applied - /// to the cropped image it gives the crop of the corrected whole. The centre moves into the crop and the - /// coefficients are rescaled for the crop's farthest corner, the radius every coordinate is normalised by. Centres - /// use the warps' convention (0 and 1 at the first and last pixel), also for `FixVignetteRadial`, as the develop - /// pipeline reads them. `None` for other opcodes, an image or crop under 2 × 2, or a crop outside the image. - pub fn cropped(&self, width: usize, height: usize, crop: crate::Rect) -> Option { - let fits = crop.x.checked_add(crop.width).is_some_and(|r| r <= width) && crop.y.checked_add(crop.height).is_some_and(|b| b <= height); - if width < 2 || height < 2 || crop.width < 2 || crop.height < 2 || !fits { - return None; - } - let (aw, ah) = (width as f64 - 1.0, height as f64 - 1.0); - let (cw, ch) = (crop.width as f64 - 1.0, crop.height as f64 - 1.0); - // the centre in the crop, and the ratio of the crop's normalising radius to the image's - let reframe = |c: [f64; 2]| -> Option<([f64; 2], f64)> { - let (px, py) = (c[0] * aw, c[1] * ah); - let (qx, qy) = (px - crop.x as f64, py - crop.y as f64); - let s = max_radius(qx, qy, cw, ch) / max_radius(px, py, aw, ah); - (s.is_finite() && s > 0.0 && qx.is_finite() && qy.is_finite()).then_some(([qx / cw, qy / ch], s)) - }; - match self { - // source radius r·(kr0 + kr1 r² + kr2 r⁴ + kr3 r⁶) and tangential terms quadratic in r: with r = r'·s, - // kr_i scales by s^2i and kt by s - Opcode::WarpRectilinear { planes, center } => { - let (center, s) = reframe(*center)?; - let planes = planes - .iter() - .map(|k| { - let mut k = *k; - for (i, v) in k[..4].iter_mut().enumerate() { - *v *= s.powi(2 * i as i32); - } - k[4] *= s; - k[5] *= s; - k - }) - .collect(); - Some(Opcode::WarpRectilinear { planes, center }) - } - // radial factor Σ kr_i r^i between the valid radii: kr_i scales by s^i, the radii by 1/s - Opcode::WarpRectilinear2 { planes, center, reciprocal, optional } => { - let (center, s) = reframe(*center)?; - let planes = planes - .iter() - .map(|k| { - let mut k = *k; - for (i, v) in k[..15].iter_mut().enumerate() { - *v *= s.powi(i as i32); - } - k[15] *= s; - k[16] *= s; - k[17] /= s; - k[18] /= s; - k - }) - .collect(); - Some(Opcode::WarpRectilinear2 { planes, center, reciprocal: *reciprocal, optional: *optional }) - } - // gain 1 + Σ k_i r^(2i+2) - Opcode::FixVignetteRadial { k, center } => { - let (center, s) = reframe(*center)?; - let mut k = *k; - for (i, v) in k.iter_mut().enumerate() { - *v *= s.powi(2 * i as i32 + 2); - } - Some(Opcode::FixVignetteRadial { k, center }) - } - _ => None, - } - } -} - -/// The opcodes of a list that a reader applies, in order: all of them, minus the DNG 1.6 skip rule (specification -/// 1.6.0.0, chapter 7) — a `WarpRectilinear` or `WarpFisheye` immediately after a `WarpRectilinear2` that is marked -/// optional is not applied. A `WarpRectilinear2` that could not be parsed ([`Opcode::Unknown`]) triggers no skip. -pub fn applied_ops(list: &[Opcode]) -> impl Iterator { - let mut skip = false; - list.iter().filter(move |op| { - let skipped = skip && matches!(op, Opcode::WarpRectilinear { .. } | Opcode::WarpFisheye { .. }); - skip = matches!(op, Opcode::WarpRectilinear2 { optional: true, .. }); - !skipped - }) -} - -/// `WarpRectilinear2` radial factor `r_real / r_ideal` for one coefficient set `k` at ideal radius `r` -/// (specification 1.6.0.0, "WarpRectilinear2"): `f(r) = Σ kr_p · r^p` (p = 0..14) evaluated at `r` clamped to -/// `[min_valid_radius, max_valid_radius]`, so `r_real = r · f` — or `r / f` when `reciprocalRadial` is non-zero. -/// `None` when the factor is not finite (a degenerate set, or `f = 0` with `reciprocalRadial`). -pub fn wr2_factor(k: &[f64; WR2_LEN], reciprocal: bool, r: f64) -> Option { - let rc = r.clamp(k[17].min(k[18]), k[17].max(k[18])); - let f = k[..15].iter().rev().fold(0.0, |acc, &c| acc * rc + c); - let f = if reciprocal { 1.0 / f } else { f }; - f.is_finite().then_some(f) -} - -/// The three opcode lists of a DNG raw IFD. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct OpcodeLists { - pub list1: Vec, - pub list2: Vec, - pub list3: Vec, -} - -struct Rd<'a> { - d: &'a [u8], - p: usize, -} - -impl Rd<'_> { - fn u32(&mut self) -> Option { - let v = u32::from_be_bytes(self.d.get(self.p..self.p + 4)?.try_into().ok()?); - self.p += 4; - Some(v) - } - fn u16(&mut self) -> Option { - let v = u16::from_be_bytes(self.d.get(self.p..self.p + 2)?.try_into().ok()?); - self.p += 2; - Some(v) - } - fn f64(&mut self) -> Option { - let v = f64::from_be_bytes(self.d.get(self.p..self.p + 8)?.try_into().ok()?); - self.p += 8; - Some(v) - } - fn finite_f64(&mut self) -> Option { - self.f64().filter(|v| v.is_finite()) - } - fn f32(&mut self) -> Option { - let v = f32::from_be_bytes(self.d.get(self.p..self.p + 4)?.try_into().ok()?); - self.p += 4; - Some(v) - } - fn area(&mut self) -> Option { - Some(Area { - top: self.u32()?, - left: self.u32()?, - bottom: self.u32()?, - right: self.u32()?, - plane: self.u32()?, - planes: self.u32()?, - row_pitch: self.u32()?.max(1), - col_pitch: self.u32()?.max(1), - }) - } - fn remaining(&self) -> usize { - self.d.len().saturating_sub(self.p) - } -} - -fn parse_one(id: u32, flags: u32, params: &[u8]) -> Option { - let mut reader = Rd { d: params, p: 0 }; - let parsed = match id { - 1 | 2 | 3 | 14 => parse_warp(id, flags, &mut reader)?, - 4 => Opcode::FixBadPixelsConstant { constant: reader.u32()?, bayer_phase: reader.u32()? }, - 5 => parse_bad_pixel_list(&mut reader)?, - 6 => Opcode::TrimBounds { top: reader.u32()?, left: reader.u32()?, bottom: reader.u32()?, right: reader.u32()? }, - 7..=13 => parse_area_opcode(id, &mut reader)?, - _ => Opcode::Unknown { id, flags, params: params.to_vec() }, - }; - Some(parsed) -} - -fn parse_warp(id: u32, flags: u32, reader: &mut Rd<'_>) -> Option { - match id { - 1 => { - let planes = parse_planes(reader, 4, |r| { - Some([r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?]) - })?; - Some(Opcode::WarpRectilinear { planes, center: [reader.finite_f64()?, reader.finite_f64()?] }) - } - 2 => { - let planes = parse_planes(reader, 4, |r| Some([r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?]))?; - Some(Opcode::WarpFisheye { planes, center: [reader.finite_f64()?, reader.finite_f64()?] }) - } - 3 => Some(Opcode::FixVignetteRadial { - k: [reader.finite_f64()?, reader.finite_f64()?, reader.finite_f64()?, reader.finite_f64()?, reader.finite_f64()?], - center: [reader.finite_f64()?, reader.finite_f64()?], - }), - 14 => parse_warp_rectilinear2(flags, reader), - _ => None, - } -} - -fn parse_planes(reader: &mut Rd<'_>, max: usize, mut parse: impl FnMut(&mut Rd<'_>) -> Option<[f64; N]>) -> Option> { - let count = reader.u32()? as usize; - if count == 0 || count > max { - return None; - } - (0..count).map(|_| parse(reader)).collect() -} - -fn parse_warp_rectilinear2(flags: u32, reader: &mut Rd<'_>) -> Option { - let count = reader.u32()? as usize; - // N sets of 19 doubles, then the centre (2 doubles) and reciprocalRadial (LONG); nothing else. - if count == 0 || count > WR2_MAX_PLANES || reader.remaining() != count * WR2_LEN * 8 + 16 + 4 { - return None; - } - let mut planes = Vec::with_capacity(count); - for _ in 0..count { - let mut coefficients = [0.0; WR2_LEN]; - for value in &mut coefficients { - *value = reader.finite_f64().filter(|value| value.abs() <= WR2_MAX_COEF)?; - } - if !(coefficients[17] >= 0.0 && coefficients[17] < coefficients[18] && coefficients[18] <= 1.0) { - return None; - } - planes.push(coefficients); - } - let center = [reader.finite_f64().filter(|value| value.abs() <= 4.0)?, reader.finite_f64().filter(|value| value.abs() <= 4.0)?]; - Some(Opcode::WarpRectilinear2 { planes, center, reciprocal: reader.u32()? != 0, optional: flags & 1 != 0 }) -} - -fn parse_bad_pixel_list(reader: &mut Rd<'_>) -> Option { - let bayer_phase = reader.u32()?; - let (point_count, rect_count) = (reader.u32()? as usize, reader.u32()? as usize); - if point_count.saturating_mul(8).saturating_add(rect_count.saturating_mul(16)) > reader.remaining() { - return None; - } - let points = (0..point_count).map(|_| Some((reader.u32()?, reader.u32()?))).collect::>()?; - let rects = (0..rect_count).map(|_| Some([reader.u32()?, reader.u32()?, reader.u32()?, reader.u32()?])).collect::>()?; - Some(Opcode::FixBadPixelsList { bayer_phase, points, rects }) -} - -fn parse_area_opcode(id: u32, reader: &mut Rd<'_>) -> Option { - let area = reader.area()?; - match id { - 7 => { - let count = reader.u32()? as usize; - if count == 0 || count > 65536 || count * 2 > reader.remaining() { - return None; - } - Some(Opcode::MapTable { area, table: (0..count).map(|_| reader.u16()).collect::>()? }) - } - 8 => { - let degree = reader.u32()? as usize; - if degree > 8 { - return None; - } - Some(Opcode::MapPolynomial { area, coefficients: (0..=degree).map(|_| reader.finite_f64()).collect::>()? }) - } - 9 => parse_gain_map(area, reader), - 10..=13 => parse_delta_scale(id, area, reader), - _ => None, - } -} - -fn parse_gain_map(area: Area, reader: &mut Rd<'_>) -> Option { - let (points_v, points_h) = (reader.u32()?, reader.u32()?); - let spacing = [reader.finite_f64()?, reader.finite_f64()?]; - let origin = [reader.finite_f64()?, reader.finite_f64()?]; - let map_planes = reader.u32()?; - let count = (points_v as usize).checked_mul(points_h as usize)?.checked_mul(map_planes as usize)?; - if count == 0 || count > reader.remaining() / 4 { - return None; - } - let gains = (0..count).map(|_| reader.f32()).collect::>()?; - Some(Opcode::GainMap { area, points_v, points_h, spacing, origin, map_planes, gains }) -} - -fn parse_delta_scale(id: u32, area: Area, reader: &mut Rd<'_>) -> Option { - let count = reader.u32()? as usize; - if count > reader.remaining() / 4 { - return None; - } - let values: Vec = (0..count).map(|_| reader.f32()).collect::>()?; - Some(match id { - 10 => Opcode::DeltaPerRow { area, deltas: values }, - 11 => Opcode::DeltaPerColumn { area, deltas: values }, - 12 => Opcode::ScalePerRow { area, scales: values }, - _ => Opcode::ScalePerColumn { area, scales: values }, - }) -} - -fn put_area(o: &mut Vec, a: &Area) { - for v in [a.top, a.left, a.bottom, a.right, a.plane, a.planes, a.row_pitch, a.col_pitch] { - o.extend_from_slice(&v.to_be_bytes()); - } -} - -fn params(op: &Opcode) -> (u32, u32, Vec) { - let mut o = Vec::new(); - let f64s = |o: &mut Vec, v: &[f64]| v.iter().for_each(|x| o.extend_from_slice(&x.to_be_bytes())); - let u32s = |o: &mut Vec, v: &[u32]| v.iter().for_each(|x| o.extend_from_slice(&x.to_be_bytes())); - let f32s = |o: &mut Vec, v: &[f32]| v.iter().for_each(|x| o.extend_from_slice(&x.to_be_bytes())); - let id = match op { - Opcode::WarpRectilinear { planes, center } => { - u32s(&mut o, &[planes.len() as u32]); - planes.iter().for_each(|p| f64s(&mut o, p)); - f64s(&mut o, center); - 1 - } - Opcode::WarpFisheye { planes, center } => { - u32s(&mut o, &[planes.len() as u32]); - planes.iter().for_each(|p| f64s(&mut o, p)); - f64s(&mut o, center); - 2 - } - Opcode::WarpRectilinear2 { planes, center, reciprocal, optional } => { - u32s(&mut o, &[planes.len() as u32]); - planes.iter().for_each(|p| f64s(&mut o, p)); - f64s(&mut o, center); - u32s(&mut o, &[*reciprocal as u32]); - return (14, *optional as u32, o); - } - Opcode::FixVignetteRadial { k, center } => { - f64s(&mut o, k); - f64s(&mut o, center); - 3 - } - Opcode::FixBadPixelsConstant { constant, bayer_phase } => { - u32s(&mut o, &[*constant, *bayer_phase]); - 4 - } - Opcode::FixBadPixelsList { bayer_phase, points, rects } => { - u32s(&mut o, &[*bayer_phase, points.len() as u32, rects.len() as u32]); - points.iter().for_each(|&(r, c)| u32s(&mut o, &[r, c])); - rects.iter().for_each(|r| u32s(&mut o, r)); - 5 - } - Opcode::TrimBounds { top, left, bottom, right } => { - u32s(&mut o, &[*top, *left, *bottom, *right]); - 6 - } - Opcode::MapTable { area, table } => { - put_area(&mut o, area); - u32s(&mut o, &[table.len() as u32]); - table.iter().for_each(|v| o.extend_from_slice(&v.to_be_bytes())); - 7 - } - Opcode::MapPolynomial { area, coefficients } => { - put_area(&mut o, area); - u32s(&mut o, &[coefficients.len().saturating_sub(1) as u32]); - f64s(&mut o, coefficients); - 8 - } - Opcode::GainMap { area, points_v, points_h, spacing, origin, map_planes, gains } => { - put_area(&mut o, area); - u32s(&mut o, &[*points_v, *points_h]); - f64s(&mut o, spacing); - f64s(&mut o, origin); - u32s(&mut o, &[*map_planes]); - f32s(&mut o, gains); - 9 - } - Opcode::DeltaPerRow { area, deltas: v } - | Opcode::DeltaPerColumn { area, deltas: v } - | Opcode::ScalePerRow { area, scales: v } - | Opcode::ScalePerColumn { area, scales: v } => { - put_area(&mut o, area); - u32s(&mut o, &[v.len() as u32]); - f32s(&mut o, v); - match op { - Opcode::DeltaPerRow { .. } => 10, - Opcode::DeltaPerColumn { .. } => 11, - Opcode::ScalePerRow { .. } => 12, - _ => 13, - } - } - Opcode::Unknown { id, flags, params } => return (*id, *flags, params.clone()), - }; - (id, 0, o) -} - -/// Serialise an opcode list (inverse of [`parse_list`]). -pub fn write_list(list: &[Opcode]) -> Vec { - let mut out = (list.len() as u32).to_be_bytes().to_vec(); - for op in list { - let (id, flags, p) = params(op); - for v in [id, if id == 14 { 0x0106_0000 } else { 0x0103_0000 }, flags, p.len() as u32] { - out.extend_from_slice(&v.to_be_bytes()); - } - out.extend_from_slice(&p); - } - out -} - -/// Parse an opcode list blob. Malformed opcodes become [`Opcode::Unknown`]; a truncated list stops early. -pub fn parse_list(d: &[u8]) -> Vec { - let mut r = Rd { d, p: 0 }; - let Some(count) = r.u32() else { return vec![] }; - let mut out = Vec::new(); - for _ in 0..count.min(4096) { - let (Some(id), Some(_ver), Some(flags), Some(size)) = (r.u32(), r.u32(), r.u32(), r.u32()) else { break }; - let Some(params) = d.get(r.p..r.p.saturating_add(size as usize)) else { break }; - r.p += size as usize; - out.push(parse_one(id, flags, params).unwrap_or(Opcode::Unknown { id, flags, params: params.to_vec() })); - } - out +/// Whether [`apply_list`] / [`apply_list3`] implement `op`. +pub fn is_applied(op: &Opcode) -> bool { + !matches!(op, Opcode::Unknown { .. } | Opcode::TrimBounds { .. } | Opcode::WarpFisheye { .. }) } fn area_iter(a: &Area, w: usize, h: usize, cpp: usize) -> impl Iterator + '_ { diff --git a/crates/raw/src/opcodes/tests.rs b/crates/raw/src/opcodes/tests.rs index 48840ff23a..50cc9bb5fd 100644 --- a/crates/raw/src/opcodes/tests.rs +++ b/crates/raw/src/opcodes/tests.rs @@ -87,7 +87,7 @@ fn parse_and_apply_area_ops() { let list = parse_list(&blob); assert_eq!(list.len(), 4); assert!(matches!(list[3], Opcode::Unknown { id: 99, .. })); - assert!(list[..3].iter().all(|o| o.is_applied())); + assert!(list[..3].iter().all(|o| is_applied(o))); let mut buf = vec![0.25f32; w * h]; apply_list(&list, &mut buf, w, h, 1, None, 1.0); // gain map: horizontal ramp 1 → 2 across relative x 0..1 (x / w) @@ -264,7 +264,7 @@ fn warp_rectilinear2_parses_the_spec_layout() { list, vec![Opcode::WarpRectilinear2 { planes: vec![k, wr2_set(&[(0, 1.0)])], center: [0.5, 0.25], reciprocal: true, optional: false }] ); - assert!(list[0].is_applied() && list[0].is_lens_correction()); + assert!(is_applied(&list[0]) && list[0].is_lens_correction()); // written back as opcode 14, version 1.6.0.0, optional flag kept let again = vec![Opcode::WarpRectilinear2 { planes: vec![k], center: [0.5, 0.5], reciprocal: false, optional: true }]; let bytes = write_list(&again); diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index cc4535af2b..834694a17b 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -328,9 +328,9 @@ fn preview_covering(bytes: &[u8], min_edge: Option) -> Option> { .or(largest) .map(|s| if is_jxl(s) { s.to_vec() } else { trim_eoi(s).to_vec() }); // a TIFF raw whose preview no tag points to: one we can't decode (Leaf MOS), or Epson ERF (in its maker note) - best.or_else(|| format.filter(|f| !f.is_supported() || *f == crate::RawFormat::Erf).and_then(|_| scan_for_jpeg(bytes))) + best.or_else(|| format.filter(|f| !crate::is_supported(*f) || *f == crate::RawFormat::Erf).and_then(|_| scan_for_jpeg(bytes))) // Hasselblad 3FR / FFF carry no JPEG, only uncompressed RGB images: one wrapped as a baseline TIFF - .or_else(|| (format == Some(crate::RawFormat::CfaTiff)).then(|| crate::vendor::hasselblad::rgb_preview(&tiff, bytes)).flatten()) + .or_else(|| (format == Some(crate::RawFormat::CfaTiff)).then(|| craft_raw::embedded_preview(bytes)).flatten()) } /// Drops candidate ranges that repeat an earlier one, that are not a displayable JPEG or JPEG XL, and valid ones diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index 924c4b4213..056b45070e 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -577,7 +577,7 @@ fn scanned_containers_give_the_largest_colour_jpeg() { f.extend_from_slice(&[0u8; 7]); } // CRW and MRW decode; their previews are still found by the scan, the others stay preview-only containers - assert!(crate::probe(&f).is_some_and(|p| !p.is_supported() || p == crate::RawFormat::Crw || p == crate::RawFormat::Mrw), "{head:?}"); + assert!(crate::probe(&f).is_some_and(|p| !crate::is_supported(p) || p == crate::RawFormat::Crw || p == crate::RawFormat::Mrw), "{head:?}"); assert_eq!(embedded_preview(&f).as_deref(), Some(&big[..]), "{head:?}"); for n in (0..f.len()).step_by(11) { let _ = embedded_preview(&f[..n]); diff --git a/crates/raw/src/profile.rs b/crates/raw/src/profile.rs index 7ca6b0e386..532dcf9aae 100644 --- a/crates/raw/src/profile.rs +++ b/crates/raw/src/profile.rs @@ -22,46 +22,27 @@ //! Values above 1.0 (highlight headroom) keep their headroom: the table's value scale only ever //! lowers them, so a lookup can't clip what the scene-referred pipeline still needs. -use crate::gaintable::GainTableMap; +pub use craft_raw::profile::{HsvTable, ProfileLook, ToneCurve}; use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear}; use lightcraft_color::{D50, D65, Mat3, PROPHOTO, REC2020, bradford}; -use serde::{Deserialize, Serialize}; -/// Upper bound on table entries (Adobe profiles use ≤ 90 × 30 × 16; guards header-driven sizes). -const MAX_ENTRIES: usize = 1 << 20; -/// A DNG hue/saturation/value mapping table (`ProfileHueSatMapData*` / `ProfileLookTableData`). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct HsvTable { - pub hue_divisions: usize, - pub sat_divisions: usize, - pub val_divisions: usize, - /// `(hue shift °, saturation scale, value scale)`, value-major, hue-middle, saturation-minor. - pub data: Vec<[f32; 3]>, - /// The value axis is indexed through the sRGB encoding curve (`…Encoding` = 1). - pub srgb_value: bool, +/// Applying a hue/saturation/value table (the table, and reading it from its tags, is `craft-raw`'s). +pub trait HsvTableApply: Sized { + /// The entry-wise blend `g · a + (1 − g) · b` of two tables of the same shape (`None` otherwise). + fn blend(a: &Self, b: &Self, g: f64) -> Option; + /// Tri-linear lookup at hue `h` (degrees), saturation `s` and value `v` (table coordinates). + fn lookup(&self, h: f32, s: f32, v: f32) -> [f32; 3]; + /// Apply the table to one linear ProPhoto RGB colour. + fn apply(&self, rgb: [f32; 3]) -> [f32; 3]; + /// [`Self::apply`] to `N` colours at once (`rgb[channel][lane]`), bit for bit. + fn apply_lanes(&self, rgb: [[f32; N]; 3]) -> [[f32; N]; 3]; } -impl HsvTable { - /// A table from its `…Dims` (hue, saturation, value divisions), data floats and encoding. - /// `None` when the dimensions are out of range, the data length doesn't match or a value is - /// not finite. - pub fn from_tags(dims: &[u64], data: &[f64], encoding: u64) -> Option { - let [h, s, v] = <[u64; 3]>::try_from(dims).ok()?; - let (h, s, v) = (usize::try_from(h).ok()?, usize::try_from(s).ok()?, usize::try_from(v).ok()?); - if h < 1 || s < 2 || v < 1 || h > 4096 || s > 4096 || v > 4096 { - return None; - } - let n = h.checked_mul(s)?.checked_mul(v)?; - if n > MAX_ENTRIES || data.len() != n * 3 || data.iter().any(|x| !x.is_finite()) { - return None; - } - let data = data.as_chunks::<3>().0.iter().map(|c| [c[0] as f32, (c[1] as f32).max(0.0), (c[2] as f32).max(0.0)]).collect(); - Some(HsvTable { hue_divisions: h, sat_divisions: s, val_divisions: v, data, srgb_value: encoding == 1 && v > 1 }) - } +impl HsvTableApply for HsvTable { /// The entry-wise blend `g · a + (1 − g) · b` of two tables of the same shape (`None` otherwise). - pub fn blend(a: &HsvTable, b: &HsvTable, g: f64) -> Option { + fn blend(a: &HsvTable, b: &HsvTable, g: f64) -> Option { if (a.hue_divisions, a.sat_divisions, a.val_divisions) != (b.hue_divisions, b.sat_divisions, b.val_divisions) { return None; } @@ -70,12 +51,9 @@ impl HsvTable { Some(HsvTable { data, ..a.clone() }) } - fn entry(&self, v: usize, h: usize, s: usize) -> [f32; 3] { - self.data.get((v * self.hue_divisions + h) * self.sat_divisions + s).copied().unwrap_or([0.0, 1.0, 1.0]) - } /// Tri-linear lookup at hue `h` (degrees), saturation `s` and value `v` (table coordinates). - pub fn lookup(&self, h: f32, s: f32, v: f32) -> [f32; 3] { + fn lookup(&self, h: f32, s: f32, v: f32) -> [f32; 3] { let hf = (wrap(h, 360.0) / 360.0 * self.hue_divisions as f32).clamp(0.0, self.hue_divisions as f32); let h0 = (hf as usize).min(self.hue_divisions - 1); let h1 = (h0 + 1) % self.hue_divisions; @@ -90,15 +68,15 @@ impl HsvTable { let (v0, v1, tv) = if self.val_divisions > 1 { axis(v, self.val_divisions) } else { (0, 0, 0.0) }; let lerp = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) }; let plane = |vi: usize| { - let lo = lerp(self.entry(vi, h0, s0), self.entry(vi, h0, s1), ts); - let hi = lerp(self.entry(vi, h1, s0), self.entry(vi, h1, s1), ts); + let lo = lerp(entry(self, vi, h0, s0), entry(self, vi, h0, s1), ts); + let hi = lerp(entry(self, vi, h1, s0), entry(self, vi, h1, s1), ts); lerp(lo, hi, th) }; if v0 == v1 { plane(v0) } else { lerp(plane(v0), plane(v1), tv) } } /// Apply the table to one linear ProPhoto RGB colour. - pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] { + fn apply(&self, rgb: [f32; 3]) -> [f32; 3] { let max = rgb[0].max(rgb[1]).max(rgb[2]); if max.is_nan() || max <= 0.0 || !max.is_finite() { return rgb; @@ -127,9 +105,9 @@ impl HsvTable { /// [`Self::apply`] to `N` colours at once (`rgb[channel][lane]`), bit for bit: the same operations, with the /// branches on the data (largest channel, hue sector, wrap-around) turned into selects so the compiler /// vectorises them. The table reads, `powf` and the rare `rem_euclid` run lane by lane. - pub fn apply_lanes(&self, rgb: [[f32; N]; 3]) -> [[f32; N]; 3] { + fn apply_lanes(&self, rgb: [[f32; N]; 3]) -> [[f32; N]; 3] { let [r, g, b] = rgb; - if !self.fits_lanes() { + if !fits_lanes(self) { let mut out = rgb; for l in 0..N { [out[0][l], out[1][l], out[2][l]] = self.apply([r[l], g[l], b[l]]); @@ -172,7 +150,7 @@ impl HsvTable { } } } - let [shift, ss, vs] = self.lookup_lanes(&hue, &sat, &v_index, active); + let [shift, ss, vs] = lookup_lanes(self, &hue, &sat, &v_index, active); let (mut s2, mut v2, mut curve) = ([0.0f32; N], [0.0f32; N], [false; N]); for l in 0..N { s2[l] = limited_select(sat[l], ss[l]); @@ -229,71 +207,77 @@ impl HsvTable { out } - /// Whether [`Self::lookup_lanes`] can do this table's index arithmetic in `f32`: every index below 2²³. - fn fits_lanes(&self) -> bool { - let entries = self.hue_divisions.checked_mul(self.sat_divisions).and_then(|n| n.checked_mul(self.val_divisions.max(1))); - self.hue_divisions >= 1 && self.sat_divisions >= 1 && entries.is_some_and(|n| n <= 1 << 23) - } - /// [`Self::lookup`] at `N` points (`(shift, saturation scale, value scale)[lane]`), bit for bit for the lanes - /// `wanted`, on a table that [`Self::fits_lanes`]. The indices are computed as `f32` (exact integers below 2²³: - /// `x as usize` is a saturating conversion that doesn't vectorise). - fn lookup_lanes(&self, h: &[f32; N], s: &[f32; N], v: &[f32; N], wanted: [bool; N]) -> [[f32; N]; 3] { - const EXACT: f32 = 8_388_608.0; // 2²³: ulp 1 from here - // `x as usize` for `0 ≤ x < 2²³`: rounded to an integer, minus 1 if it rounded up; NaN is 0 - let floor = |x: f32| { - let nearest = (x + EXACT) - EXACT; - let floor = if nearest > x { nearest - 1.0 } else { nearest }; - if x.is_nan() { 0.0 } else { floor } - }; - let (hn, sn, vn) = (self.hue_divisions as f32, self.sat_divisions as f32, self.val_divisions as f32); - let axis = |x: f32, n: f32| { - let f = x.clamp(0.0, 1.0) * (n - 1.0); - let i0 = floor(f).min((n - 2.0).max(0.0)); - let i1 = (i0 + 1.0).min(n - 1.0); - (i0, i1, (f - i0).clamp(0.0, 1.0)) - }; - let h = wrap_lanes(*h, 360.0, wanted); - // the corners' indices (v, h, s), s fastest, and the weights between them - let (mut at, mut t) = ([[0u32; N]; 8], [[0.0f32; N]; 3]); - for l in 0..N { - let hf = (h[l] / 360.0 * hn).clamp(0.0, hn); - let h0 = floor(hf).min(hn - 1.0); - // (h0 + 1) % hn - let h1 = if h0 + 1.0 == hn { 0.0 } else { h0 + 1.0 }; - let (s0, s1, ts) = axis(s[l], sn); - let (v0, v1, tv) = axis(v[l], vn); - let (v0, v1, tv) = if self.val_divisions > 1 { (v0, v1, tv) } else { (0.0, 0.0, 0.0) }; - for (k, (vi, hi)) in [(v0, h0), (v0, h1), (v1, h0), (v1, h1)].into_iter().enumerate() { - let row = (vi * hn + hi) * sn; - // an exact integer below 2²³ plus 2²³ has it as its mantissa - at[2 * k][l] = (row + s0 + EXACT).to_bits().wrapping_sub(EXACT.to_bits()); - at[2 * k + 1][l] = (row + s1 + EXACT).to_bits().wrapping_sub(EXACT.to_bits()); - } - [t[0][l], t[1][l], t[2][l]] = [(hf - h0).clamp(0.0, 1.0), ts, tv]; +} + +fn entry(table: &HsvTable, v: usize, h: usize, s: usize) -> [f32; 3] { + table.data.get((v * table.hue_divisions + h) * table.sat_divisions + s).copied().unwrap_or([0.0, 1.0, 1.0]) +} + +/// Whether [`lookup_lanes`] can do this table's index arithmetic in `f32`: every index below 2²³. +fn fits_lanes(table: &HsvTable) -> bool { + let entries = table.hue_divisions.checked_mul(table.sat_divisions).and_then(|n| n.checked_mul(table.val_divisions.max(1))); + table.hue_divisions >= 1 && table.sat_divisions >= 1 && entries.is_some_and(|n| n <= 1 << 23) +} + +/// [`HsvTableApply::lookup`] at `N` points (`(shift, saturation scale, value scale)[lane]`), bit for bit for the lanes +/// `wanted`, on a table that [`fits_lanes`]. The indices are computed as `f32` (exact integers below 2²³: +/// `x as usize` is a saturating conversion that doesn't vectorise). +fn lookup_lanes(table: &HsvTable, h: &[f32; N], s: &[f32; N], v: &[f32; N], wanted: [bool; N]) -> [[f32; N]; 3] { + const EXACT: f32 = 8_388_608.0; // 2²³: ulp 1 from here + // `x as usize` for `0 ≤ x < 2²³`: rounded to an integer, minus 1 if it rounded up; NaN is 0 + let floor = |x: f32| { + let nearest = (x + EXACT) - EXACT; + let floor = if nearest > x { nearest - 1.0 } else { nearest }; + if x.is_nan() { 0.0 } else { floor } + }; + let (hn, sn, vn) = (table.hue_divisions as f32, table.sat_divisions as f32, table.val_divisions as f32); + let axis = |x: f32, n: f32| { + let f = x.clamp(0.0, 1.0) * (n - 1.0); + let i0 = floor(f).min((n - 2.0).max(0.0)); + let i1 = (i0 + 1.0).min(n - 1.0); + (i0, i1, (f - i0).clamp(0.0, 1.0)) + }; + let h = wrap_lanes(*h, 360.0, wanted); + // the corners' indices (v, h, s), s fastest, and the weights between them + let (mut at, mut t) = ([[0u32; N]; 8], [[0.0f32; N]; 3]); + for l in 0..N { + let hf = (h[l] / 360.0 * hn).clamp(0.0, hn); + let h0 = floor(hf).min(hn - 1.0); + // (h0 + 1) % hn + let h1 = if h0 + 1.0 == hn { 0.0 } else { h0 + 1.0 }; + let (s0, s1, ts) = axis(s[l], sn); + let (v0, v1, tv) = axis(v[l], vn); + let (v0, v1, tv) = if table.val_divisions > 1 { (v0, v1, tv) } else { (0.0, 0.0, 0.0) }; + for (k, (vi, hi)) in [(v0, h0), (v0, h1), (v1, h0), (v1, h1)].into_iter().enumerate() { + let row = (vi * hn + hi) * sn; + // an exact integer below 2²³ plus 2²³ has it as its mantissa + at[2 * k][l] = (row + s0 + EXACT).to_bits().wrapping_sub(EXACT.to_bits()); + at[2 * k + 1][l] = (row + s1 + EXACT).to_bits().wrapping_sub(EXACT.to_bits()); } - let mut corner = [[[0.0f32; N]; 3]; 8]; - for l in 0..N { - for (corner, at) in corner.iter_mut().zip(&at) { - [corner[0][l], corner[1][l], corner[2][l]] = self.data.get(at[l] as usize).copied().unwrap_or([0.0, 1.0, 1.0]); - } + [t[0][l], t[1][l], t[2][l]] = [(hf - h0).clamp(0.0, 1.0), ts, tv]; + } + let mut corner = [[[0.0f32; N]; 3]; 8]; + for l in 0..N { + for (corner, at) in corner.iter_mut().zip(&at) { + [corner[0][l], corner[1][l], corner[2][l]] = table.data.get(at[l] as usize).copied().unwrap_or([0.0, 1.0, 1.0]); } - let lerp = |a: &[f32; N], b: &[f32; N], t: &[f32; N]| { - let mut out = [0.0f32; N]; - for l in 0..N { - out[l] = a[l] + (b[l] - a[l]) * t[l]; - } - out - }; - let [th, ts, tv] = &t; - let mut out = [[0.0f32; N]; 3]; - for (c, out) in out.iter_mut().enumerate() { - let plane = |k: usize| lerp(&lerp(&corner[k][c], &corner[k + 1][c], ts), &lerp(&corner[k + 2][c], &corner[k + 3][c], ts), th); - // `lookup`'s `v0 == v1` for every lane: `axis` gives `v1 = v0 + 1` whenever there are two values or more - *out = if self.val_divisions > 1 { lerp(&plane(0), &plane(4), tv) } else { plane(0) }; + } + let lerp = |a: &[f32; N], b: &[f32; N], t: &[f32; N]| { + let mut out = [0.0f32; N]; + for l in 0..N { + out[l] = a[l] + (b[l] - a[l]) * t[l]; } out + }; + let [th, ts, tv] = &t; + let mut out = [[0.0f32; N]; 3]; + for (c, out) in out.iter_mut().enumerate() { + let plane = |k: usize| lerp(&lerp(&corner[k][c], &corner[k + 1][c], ts), &lerp(&corner[k + 2][c], &corner[k + 3][c], ts), th); + // `lookup`'s `v0 == v1` for every lane: `axis` gives `v1 = v0 + 1` whenever there are two values or more + *out = if table.val_divisions > 1 { lerp(&plane(0), &plane(4), tv) } else { plane(0) }; } + out } /// `x · k` clipped to 1, for `x ≤ 1`; above 1, only scale factors below 1 apply (continuous at 1). @@ -378,26 +362,17 @@ fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { } } -/// A DNG tone curve (`ProfileToneCurve`): linear-gamma (input, output) pairs, increasing input. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ToneCurve { - pub points: Vec<[f32; 2]>, + +/// Evaluating a profile tone curve. +pub trait ToneCurveEval { + /// The curve at `x` (0..=1): monotone cubic (Fritsch–Carlson) through the samples. + fn eval(&self, x: f32) -> f32; } -impl ToneCurve { - /// From the tag's flat float pairs. `None` unless there are 2..=65536 finite pairs within - /// 0..=1 with strictly increasing inputs. - pub fn from_tag(v: &[f64]) -> Option { - if !v.len().is_multiple_of(2) || v.len() < 4 || v.len() > 131_072 { - return None; - } - let points: Vec<[f32; 2]> = v.as_chunks::<2>().0.iter().map(|p| [p[0] as f32, p[1] as f32]).collect(); - let ok = points.iter().all(|p| p.iter().all(|x| x.is_finite() && (0.0..=1.0).contains(x))) && points.windows(2).all(|w| w[1][0] > w[0][0]); - ok.then_some(ToneCurve { points }) - } +impl ToneCurveEval for ToneCurve { /// The curve at `x` (0..=1): monotone cubic (Fritsch–Carlson) through the samples. - pub fn eval(&self, x: f32) -> f32 { + fn eval(&self, x: f32) -> f32 { let p = &self.points; let n = p.len(); let x = x.clamp(p[0][0], p[n - 1][0]); @@ -425,27 +400,17 @@ impl ToneCurve { } } -/// The DNG profile look tags of a file (all optional). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ProfileLook { - /// `ProfileHueSatMapData1/2` (same shape, `ProfileHueSatMapDims`). - pub hue_sat_map: [Option; 2], - /// `ProfileLookTableData`. - pub look_table: Option, - /// `ProfileToneCurve`. - pub tone_curve: Option, - /// `ProfileGainTableMap2`, else `ProfileGainTableMap`. - #[serde(default)] - pub gain_table_map: Option, + +/// The hue/saturation map of a profile look for a white balance. +pub trait ProfileLookHueSat { + /// The hue/saturation map for calibration-1 weight `g` (one table: used for any white). + fn hue_sat_for(&self, g: f64) -> Option; } -impl ProfileLook { - pub fn is_empty(&self) -> bool { - self.hue_sat_map.iter().all(Option::is_none) && self.look_table.is_none() && self.tone_curve.is_none() && self.gain_table_map.is_none() - } +impl ProfileLookHueSat for ProfileLook { /// The hue/saturation map for calibration-1 weight `g` (one table: used for any white). - pub fn hue_sat_for(&self, g: f64) -> Option { + fn hue_sat_for(&self, g: f64) -> Option { match &self.hue_sat_map { [Some(a), Some(b)] => HsvTable::blend(a, b, g).or_else(|| Some(a.clone())), [Some(a), None] | [None, Some(a)] => Some(a.clone()), diff --git a/crates/raw/src/saturation.rs b/crates/raw/src/saturation.rs index 40daa37de8..f0b575bb8d 100644 --- a/crates/raw/src/saturation.rs +++ b/crates/raw/src/saturation.rs @@ -64,7 +64,7 @@ impl RawImage { let black = self.black.mean(); // a hostile file can state any levels: NaN, negative or inverted ones are left alone let levels_ok = black.is_finite() && white.is_finite() && black >= 0.0 && white > black && white <= 65535.0; - if self.cpp != 1 || !cfa.valid() || self.width.checked_mul(self.height) != Some(d.len()) || !levels_ok { + if self.cpp != 1 || !crate::cfa_valid(cfa) || self.width.checked_mul(self.height) != Some(d.len()) || !levels_ok { return none; } let a = self.active_area; @@ -143,7 +143,7 @@ impl RawImage { let (old, black) = (self.white_at(0), self.black.mean()); let ceiling = ((1u32 << self.bits) - 1) as f32; if self.cpp != 1 - || !cfa.valid() + || !crate::cfa_valid(cfa) || self.width.checked_mul(self.height) != Some(data.len()) || !black.is_finite() || !old.is_finite() diff --git a/crates/raw/src/semantic.rs b/crates/raw/src/semantic.rs deleted file mode 100644 index fba28596e1..0000000000 --- a/crates/raw/src/semantic.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! DNG semantic masks (DNG 1.6+, chapter "Semantic Masks"): single-channel segmentation mattes -//! stored in their own IFDs (NewSubFileType 10004.H, PhotometricInterpretation 52527) with a -//! `SemanticName`, an optional `SemanticInstanceID` and an optional `MaskSubArea`. iPhone ProRAW -//! stores e.g. a sky matte this way. -//! -//! [`semantic_masks`] reads them separately from [`crate::decode`] (only callers that use them -//! pay for them); malformed or unsupported mask IFDs are skipped. - -use crate::Rect; -use crate::tiffraw::{Packing, read_image}; -use crate::{RawData, Result}; -use craft_tiff::Tiff; -use craft_tiff::tags::{self as t, photometric}; -use lightcraft_raster::Image; - -/// At most this many mask IFDs are read from one file. -pub const MAX_MASKS: usize = 16; -/// Masks with more samples than this are skipped (a mask is a low-resolution matte; this is -/// 8192 × 4096). -pub const MAX_MASK_SAMPLES: usize = 1 << 25; - -/// Where a cropped mask sits in the uncropped mask (DNG `MaskSubArea`). The uncropped mask -/// (`full_width × full_height`) spans the main image's active area. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct MaskSubArea { - pub top: u32, - pub left: u32, - pub full_width: u32, - pub full_height: u32, -} - -/// One semantic mask: `width × height` values, 0 = not part of the attribute, 65535 = fully part. -#[derive(Clone, Debug, PartialEq)] -pub struct SemanticMask { - /// `SemanticName`, e.g. `urn:com:apple:photo:2020:aux:semanticskymatte`. - pub name: String, - pub instance_id: Option, - pub width: usize, - pub height: usize, - /// `None`: the mask covers the whole active area. - pub sub_area: Option, - pub data: Vec, -} - -/// The semantic masks of a DNG, in file order (none for other files). Only the first -/// [`MAX_MASKS`] mask IFDs are looked at, malformed ones included, so a file full of mask IFDs -/// costs at most that many decodes. -pub fn semantic_masks(bytes: &[u8]) -> Vec { - let Ok(tiff) = Tiff::parse(bytes) else { return Vec::new() }; - tiff.all_ifds() - .into_iter() - .filter(|i| i.u16(t::PHOTOMETRIC) == Some(photometric::MASK) || i.u32(t::NEW_SUBFILE_TYPE) == Some(t::SUBFILE_SEMANTIC_MASK)) - .take(MAX_MASKS) - .filter_map(|ifd| read_mask(bytes, &tiff, ifd).ok().flatten()) - .collect() -} - -fn read_mask(bytes: &[u8], tiff: &Tiff, ifd: &craft_tiff::Ifd) -> Result> { - let Some(name) = ifd.string(t::SEMANTIC_NAME).filter(|n| !n.is_empty()) else { return Ok(None) }; - let info = ifd.image()?; - let (w, h) = (info.width as usize, info.height as usize); - if info.samples_per_pixel != 1 || w.checked_mul(h).is_none_or(|n| n > MAX_MASK_SAMPLES) { - return Ok(None); - } - let bits = info.bits() as u32; - let data: Vec = match read_image(bytes, &info, tiff.order, Packing::Msb)? { - RawData::U16(v) if (1..=16).contains(&bits) => { - let max = ((1u32 << bits) - 1) as f32; - if bits == 16 { v } else { v.into_iter().map(|s| (s as f32 / max * 65535.0).round().min(65535.0) as u16).collect() } - } - RawData::F32(v) => v.into_iter().map(|s| if s.is_finite() { (s.clamp(0.0, 1.0) * 65535.0).round() as u16 } else { 0 }).collect(), - RawData::U16(_) => return Ok(None), - }; - if data.len() != w * h { - return Ok(None); - } - // the tag is ignored when the stored mask does not fit inside the uncropped one - let sub_area = match ifd.u64s(t::MASK_SUB_AREA).as_deref() { - Some(&[top, left, fw, fh]) => { - let fits = fw > 0 && fh > 0 && left.saturating_add(w as u64) <= fw && top.saturating_add(h as u64) <= fh && fw.max(fh) <= u32::MAX as u64; - fits.then_some(MaskSubArea { top: top as u32, left: left as u32, full_width: fw as u32, full_height: fh as u32 }) - } - _ => None, - }; - Ok(Some(SemanticMask { name, instance_id: ifd.string(t::SEMANTIC_INSTANCE_ID).filter(|s| !s.is_empty()), width: w, height: h, sub_area, data })) -} - -impl SemanticMask { - /// The mask value (0..1) at a continuous position of the uncropped mask (pixel centres at - /// +0.5); 0 outside the stored (cropped) mask. - pub fn value_at(&self, x: f64, y: f64) -> f32 { - let (left, top) = self.sub_area.map_or((0.0, 0.0), |a| (a.left as f64, a.top as f64)); - let (x, y) = (x - left, y - top); - if self.width == 0 || self.height == 0 || !(x >= 0.0 && y >= 0.0 && x <= self.width as f64 && y <= self.height as f64) { - return 0.0; - } - let (fx, fy) = ((x - 0.5).max(0.0), (y - 0.5).max(0.0)); - let (x0, y0) = (fx.floor() as usize, fy.floor() as usize); - let (tx, ty) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32); - let at = |x: usize, y: usize| { - let (x, y) = (x.min(self.width - 1), y.min(self.height - 1)); - self.data.get(y * self.width + x).copied().unwrap_or(0) as f32 / 65535.0 - }; - let top = at(x0, y0) + (at(x0 + 1, y0) - at(x0, y0)) * tx; - let bottom = at(x0, y0 + 1) + (at(x0 + 1, y0 + 1) - at(x0, y0 + 1)) * tx; - top + (bottom - top) * ty - } - - /// The mask over the developed image ([`crate::RawImage::develop`]: the default `crop` of the - /// `active_area`, before orientation), at the mask's own resolution, as 0..255 alpha. `None` - /// for an empty crop. - pub fn developed(&self, active_area: Rect, crop: Rect) -> Option> { - let c = crop.clipped(active_area.width, active_area.height); - if c.width == 0 || c.height == 0 || self.width == 0 || self.height == 0 { - return None; - } - let (fw, fh) = self.sub_area.map_or((self.width, self.height), |a| (a.full_width as usize, a.full_height as usize)); - // uncropped-mask px per active-area px - let (sx, sy) = (fw as f64 / active_area.width as f64, fh as f64 / active_area.height as f64); - let ow = ((c.width as f64 * sx).round() as usize).clamp(1, self.width.max(fw)); - let oh = ((c.height as f64 * sy).round() as usize).clamp(1, self.height.max(fh)); - if ow.checked_mul(oh).is_none_or(|n| n > MAX_MASK_SAMPLES) { - return None; - } - let (kx, ky) = (c.width as f64 / ow as f64, c.height as f64 / oh as f64); - let mut out = Image::new(ow, oh); - lightcraft_raster::par_rows(&mut out.data, ow, |y, row| { - let ay = c.y as f64 + (y as f64 + 0.5) * ky; - for (x, v) in row.iter_mut().enumerate() { - let ax = c.x as f64 + (x as f64 + 0.5) * kx; - *v = (self.value_at(ax * sx, ay * sy) * 255.0).round() as u8; - } - }); - Some(out) - } -} diff --git a/crates/raw/src/sparse.rs b/crates/raw/src/sparse.rs index dd81263e58..cb958f21f9 100644 --- a/crates/raw/src/sparse.rs +++ b/crates/raw/src/sparse.rs @@ -296,7 +296,7 @@ fn tiff_plan(bytes: &[u8], loaded: &Ranges, preview: bool) -> HeaderPlan { Some(RawFormat::Nef | RawFormat::Nrw | RawFormat::Orf | RawFormat::Pef | RawFormat::Erf | RawFormat::Mef) => { HeaderPlan::Whole("its header probe reads samples") } - Some(f) if f.is_supported() => HeaderPlan::Ready, + Some(f) if crate::is_supported(f) => HeaderPlan::Ready, _ => HeaderPlan::Whole("not a supported raw"), }) } diff --git a/crates/raw/src/tests.rs b/crates/raw/src/tests.rs index 0cff6f2006..a65927312f 100644 --- a/crates/raw/src/tests.rs +++ b/crates/raw/src/tests.rs @@ -10,7 +10,7 @@ fn cfa_helpers() { assert_eq!(c.shifted(1, 1).name(), "BGGR"); assert!(Cfa::bayer("RGGX").is_none()); for name in ["RGGB", "BGGR", "GRBG", "GBRG"] { - assert_eq!(Cfa::bayer_static(name).name(), name); + assert_eq!(crate::bayer(name).name(), name); } let x = Cfa::xtrans(); assert!(!x.is_bayer()); @@ -259,9 +259,9 @@ fn private_containers_are_recognised_by_their_magic() { assert_eq!(probe(b"\0MRM\0\x01\0\0"), Some(RawFormat::Mrw)); assert_eq!(probe(b"FOVb\x02\0\x02\0"), Some(RawFormat::X3f)); for f in [RawFormat::Crw, RawFormat::Mrw] { - assert!(f.is_supported()); + assert!(crate::is_supported(f)); } - assert!(!RawFormat::X3f.is_supported()); + assert!(!crate::is_supported(RawFormat::X3f)); // a CRW signature with no heap behind it is corrupt, not a panic assert!(matches!(decode(b"II\x1a\0\0\0HEAPCCDR\0\0"), Err(RawError::Corrupt(_)))); assert!(matches!(decode(b"FOVb\x02\0\x02\0"), Err(RawError::Unsupported(w)) if w.contains("X3f"))); @@ -546,7 +546,7 @@ fn lossless_jpeg_cfa_tiff_decodes() { /// same layout decodes: the file is read like the uncompressed one. #[test] fn selection_value_8_cfa_tiff_decodes() { - let strip = ljpeg::tests::encode_hasselblad(&cfa_samples(), 8, 6); + let strip = crate::ljpeg_fixtures::encode_hasselblad(&cfa_samples(), 8, 6); let bytes = plain_cfa_tiff(7, strip, None); assert_eq!(probe(&bytes), Some(RawFormat::CfaTiff)); let r = decode(&bytes).unwrap(); @@ -569,7 +569,7 @@ fn cfa_tiff_with_an_unknown_predictor_stays_undecodable() { assert!(matches!(ljpeg::decode(&strip, 1 << 20), Err(RawError::Unsupported(w)) if w.contains("selection value 9"))); let bytes = plain_cfa_tiff(7, strip, None); assert_eq!(probe(&bytes), Some(RawFormat::OtherTiff)); - assert!(!RawFormat::OtherTiff.is_supported()); + assert!(!crate::is_supported(RawFormat::OtherTiff)); let Err(RawError::Unsupported(why)) = decode(&bytes) else { panic!("expected Unsupported") }; assert!(why.contains("lossless JPEG") && why.contains("selection value 9"), "{why}"); } diff --git a/crates/raw/src/tiffraw.rs b/crates/raw/src/tiffraw.rs index c396651ae5..794116e411 100644 --- a/crates/raw/src/tiffraw.rs +++ b/crates/raw/src/tiffraw.rs @@ -315,16 +315,11 @@ fn chunk_dims(info: &ImageInfo, c: &Chunk) -> (usize, usize, usize, usize) { (cw, ch, vw, vh) } -#[cfg(feature = "jxl")] -use crate::jxl::{check as jxl_chunk_check, decode as jxl_chunk}; - -#[cfg(not(feature = "jxl"))] #[allow(clippy::too_many_arguments)] fn jxl_chunk(_: &[u8], _: usize, _: usize, _: usize, _: usize, _: usize, _: u32, _: bool) -> Result { - Err(RawError::Unsupported("JPEG XL DNG (built without the `jxl` feature)".into())) + Err(RawError::Unsupported("JPEG XL outside a DNG".into())) } -#[cfg(not(feature = "jxl"))] #[allow(clippy::too_many_arguments)] fn jxl_chunk_check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result<()> { jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ()) diff --git a/crates/raw/src/vendor.rs b/crates/raw/src/vendor.rs index dea94043e5..d85bce85c1 100644 --- a/crates/raw/src/vendor.rs +++ b/crates/raw/src/vendor.rs @@ -1,4 +1,5 @@ -//! Vendor raw formats (TIFF-based) and helpers shared by them. +//! The vendor raw formats still decoded here (CR3, ARW, RAF, RW2, ORF; the others are `craft-raw`'s) and helpers +//! shared by them. pub mod arw; pub mod arw6; @@ -7,27 +8,16 @@ mod arw6_curve; pub(crate) mod arw6_testenc; mod arw_lens; pub(crate) mod arw_lens_rm6; -pub mod cr2; pub mod cr3; -pub mod crw; pub mod crx; pub(crate) mod crx_wavelet; -pub mod erf; -pub(crate) mod hasselblad; -pub mod kodak; -pub mod mef; -pub mod mrw; -pub mod nef; -mod nef_lens; -pub mod nefc; +pub(crate) mod huffman; pub mod orf; -pub mod pef; pub mod raf; mod raf_lens; mod rafc; pub mod rw2; mod sr2; -pub mod srw; use crate::{BlackLevel, Cfa, Rect}; use craft_tiff::Tiff; @@ -48,7 +38,7 @@ pub(crate) fn cfa_from_exif(tiff: &Tiff) -> Option { [1, 2, 0, 1] => "GBRG", _ => return None, }; - (two(c0, c1) && two(r0, r1)).then(|| Cfa::bayer_static(name)) + (two(c0, c1) && two(r0, r1)).then(|| crate::bayer(name)) } /// Black level per 2×2 CFA position (anchored at the active area origin) from masked sensor columns `cols` over diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index 950e3bec47..dbe413392f 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -715,7 +715,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, - _ => Cfa::bayer_static("RGGB"), + _ => crate::bayer("RGGB"), }; let default_black = if scale_bits >= 14 { 512.0 } else { 128.0 }; // the decrypted SR2SubIFD, read once and only when a plain black level or white balance is missing @@ -849,7 +849,7 @@ mod tests { raw.set(TONE_CURVE, Value::Short(vec![0; 4])); raw.set(BLACK_LEVEL, Value::Short(vec![512; 4])); raw.set(WB_RGGB, Value::Short(vec![2048, 1024, 1024, 2048])); - raw.set_image(ImageData::Tiles { tile_width: 4, tile_height: 4, tiles: vec![ljpeg::tests::fixture_420()] }); + raw.set_image(ImageData::Tiles { tile_width: 4, tile_height: 4, tiles: vec![crate::ljpeg_fixtures::fixture_420()] }); let file = TiffWriter::default().write(&[raw]).unwrap(); let header = decode(&file, Mode::Header).unwrap(); let full = decode(&file, Mode::Full).unwrap(); diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rs index b8ee711732..1cd5c71c8d 100644 --- a/crates/raw/src/vendor/arw6.rs +++ b/crates/raw/src/vendor/arw6.rs @@ -7,7 +7,7 @@ use crate::llvc::{Bands3, Plane, band_rows, dequant, reconstruct3, vld_decode_line}; use crate::vendor::arw6_curve::curve; -use crate::vendor::pef::Bits; +use crate::vendor::huffman::Bits; use crate::{RawError, Result}; use rayon::prelude::*; use std::ops::Range; @@ -542,7 +542,7 @@ pub(crate) fn decode(strip: &[u8], width: usize, height: usize, mode: crate::Mod mod tests { use super::*; use crate::vendor::arw6_testenc::*; - use crate::vendor::pef::Bits; + use crate::vendor::huffman::Bits; use craft_tiff::Tiff; use craft_tiff::image::chunk_bytes; use craft_tiff::tags as t; diff --git a/crates/raw/src/vendor/arw_lens.rs b/crates/raw/src/vendor/arw_lens.rs index 94f1b67883..778289d303 100644 --- a/crates/raw/src/vendor/arw_lens.rs +++ b/crates/raw/src/vendor/arw_lens.rs @@ -1324,7 +1324,7 @@ mod tests { for (tag, value) in plain(&TELE, 17) { raw.set(tag, value); } - raw.set_image(ImageData::Tiles { tile_width: 4, tile_height: 4, tiles: vec![crate::ljpeg::tests::fixture_420()] }); + raw.set_image(ImageData::Tiles { tile_width: 4, tile_height: 4, tiles: vec![crate::ljpeg_fixtures::fixture_420()] }); let img = decode(&TiffWriter::new(order, false).write(&[raw]).unwrap()); let s = sony(&img); assert!(s.geometry.linear_ycbcr && s.geometry.native_3_2); diff --git a/crates/raw/src/vendor/cr2.rs b/crates/raw/src/vendor/cr2.rs deleted file mode 100644 index 83367e2324..0000000000 --- a/crates/raw/src/vendor/cr2.rs +++ /dev/null @@ -1,638 +0,0 @@ -//! Canon CR2. -//! -//! Source: Laurent Clévy, "Understanding what is stored in a Canon RAW .CR2 file" (prose sections on the file -//! structure, IFD#3, the `0xc640` slice layout and the maker-note `SensorInfo` table), plus the ExifTool Canon -//! tag-name documentation for maker-note tag meanings. Only the structural description was used. -//! -//! - The raw data is IFD#3's single strip: a lossless-JPEG frame (usually 2 or 4 components). -//! - The decoded sample stream fills vertical slices left to right: `cr2_slice = [n, w, last]` means `n` slices of -//! width `w` then one of width `last`; each slice is filled top to bottom, row by row. -//! - Colour filter layout: IFD#3 tag `0xc5e0` (`CR2CFAPattern` in the ExifTool EXIF tag-name docs): 1 = RGGB, -//! 2 = BGGR, 3 = GBRG, 4 = GRBG, anchored at the top-left of the full decoded sensor (masked borders included). -//! It differs by model (e.g. 3 on the 50D/60D/7D/550D/5D Mark II, 1 on the 40D/5D Mark III/6D/5DS R), so it is -//! read per file (no model table); files without the tag fall back to RGGB (issue #85). The parity of the -//! `SensorInfo` borders does *not* predict it (RGGB files come with both even and odd top borders). -//! - `SensorInfo` (maker note `0x00e0`): sensor width/height and the left/top/right/bottom borders of the image -//! area. Light already reaches some columns left of that border (EOS 6D: masked columns 0–70, border 84; 10–36 -//! such columns on every corpus body), so the masked columns that give the black level are measured from the -//! data ([`masked_columns`]) rather than taken as the whole border. -//! - `ColorBalance` (maker note `0x4001`): as-shot `RGGB` levels at a model-dependent offset; we probe the known -//! offsets and accept the first plausible quadruple. The array is 16-bit words; some models store it as UNDEFINED -//! bytes (ColorData versions -3 and -4), which are paired up in the maker note's byte order first. -//! - The same array lists the levels of the camera's white-balance presets, each with the colour temperature Canon -//! gives it ([`kelvin_presets_from_color_data`]): a Kelvin scale for a body without colour matrices. -//! - sRAW / mRAW (raw IFD tag `0xc6c5` = 4) hold subsampled YCbCr instead of a mosaic: see [`sraw`]. - -mod sraw; - -use super::{active_rows, black_from_columns, white_from_data}; -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; -use craft_tiff::image::chunk_bytes; -use craft_tiff::{ByteOrder, Ifd, Tiff, Value, makernote, tags as t}; -use lightcraft_geom::Orientation; -use std::ops::Range; - -const CR2_SLICE: u16 = 0xc640; -const SRAW_TYPE: u16 = 0xc6c5; -/// `SRAW_TYPE` value of the YCbCr frames of sRAW / mRAW (IFD2's preview image carries 3). -const SRAW_YCC: u32 = 4; -const CR2_CFA_PATTERN: u16 = 0xc5e0; -const SENSOR_INFO: u16 = 0x00e0; -const COLOR_BALANCE: u16 = 0x4001; -/// ShotInfo, whose value 7 is the white-balance setting. -const SHOT_INFO: u16 = 0x0004; -/// WBInfo, the PowerShot G9's preset levels (it writes no `ColorData`). -const WB_INFO: u16 = 0x0029; - -fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> { - tiff.ifds.get(3).or_else(|| tiff.ifds.iter().rev().find(|i| i.contains(CR2_SLICE))) -} - -/// Bayer layout from the raw IFD's `CR2CFAPattern` (`0xc5e0`) value; `None` for missing/unknown values. -fn cfa_from_tag(v: Option) -> Option { - let name = match v? { - 1 => "RGGB", - 2 => "BGGR", - 3 => "GBRG", - 4 => "GRBG", - _ => return None, - }; - Some(Cfa::bayer_static(name)) -} - -/// The 16-bit words of a maker-note array. Canon writes `ColorData` as SHORT in most models, but as UNDEFINED -/// bytes (count = byte length, e.g. 5120) in the PowerShot / EOS M models with ColorData versions -3 and -4; -/// those bytes are the same 16-bit words in the maker note's byte order, so they are paired up, not read one by -/// one. Other types are returned value by value. -fn words(v: &Value, order: ByteOrder) -> Vec { - match v { - Value::Byte(b) | Value::Undefined(b) => b.as_chunks::<2>().0.iter().map(|c| u64::from(order.u16(*c))).collect(), - _ => v.to_u64_vec(), - } -} - -/// WB multipliers (R, G, B; G = 1) from one set of levels, when they are plausible. -fn wb_from_levels(r: f32, g1: f32, g2: f32, b: f32) -> Option<[f32; 3]> { - if g1 < 256.0 || g2 < 256.0 || r < 64.0 || b < 64.0 || g1 > 16384.0 || (g1 - g2).abs() > 0.05 * g1 { - return None; - } - let g = (g1 + g2) / 2.0; - let (mr, mb) = (r / g, b / g); - ((0.25..6.0).contains(&mr) && (0.25..6.0).contains(&mb)).then_some([mr, 1.0, mb]) -} - -/// As-shot WB multipliers (R, G, B; G = 1) from the ColorBalance array. -fn wb_from_color_balance(v: &[u64]) -> Option<[f32; 3]> { - for off in [63usize, 25, 24, 34, 71, 85, 105, 69, 77] { - let q = v.get(off..off + 4)?; - if let Some(wb) = wb_from_levels(q[0] as f32, q[1] as f32, q[2] as f32, q[3] as f32) { - return Some(wb); - } - } - None -} - -/// Where the planckian white-balance presets sit in `ColorData`, by `ColorDataVersion` (word 0, signed): the word -/// index of each preset's `R G G B` levels and of its colour temperature. Daylight, Shade, Cloudy, Tungsten and -/// Flash, in that order. Fluorescent is left out (a green light off the locus) and so is the Kelvin row (it holds the -/// dial's last setting, and on some bodies a temperature that doesn't match its own levels: 6036 K with the camera at -/// 5500 K on the PowerShot G1 X Mark III, Daylight's levels at 5213 K on the EOS 2000D). Positions from the ExifTool -/// Canon tag-name documentation's `ColorData5` / `ColorData8` tables, confirmed with ExifTool run as a black-box tool -/// on files of each version: -4 on a PowerShot G1 X Mark III (`ColorData5`: 8-word records, the second record after -/// Daylight a repeat of it), 13, 14 and 15 on the CC0 corpus samples of the EOS 5D Mark IV, 2000D and 6D Mark II -/// (`ColorData8`: 5-word records). Other versions give no presets. -fn preset_rows(version: i16) -> Option<[(usize, usize); 5]> { - match version { - -4 => Some([(95, 102), (111, 118), (119, 126), (127, 134), (151, 158)]), - 13..=15 => Some([(133, 137), (138, 142), (143, 147), (148, 152), (163, 167)]), - _ => None, - } -} - -/// The camera's planckian white-balance presets from the `ColorData` words ([`preset_rows`]) as a Kelvin curve; -/// `None` for an unknown version, a short array or presets that don't make a curve. -fn kelvin_presets_from_color_data(v: &[u64]) -> Option { - let version = *v.first()? as u16 as i16; - let rows = preset_rows(version)?; - let mut points = Vec::with_capacity(rows.len()); - for (at, temp_at) in rows { - let q = v.get(at..at + 4)?; - let temp = *v.get(temp_at)? as f32; - if let Some(wb) = wb_from_levels(q[0] as f32, q[1] as f32, q[2] as f32, q[3] as f32) - && (1000.0..=20000.0).contains(&temp) - { - points.push((temp, wb)); - } - } - crate::kelvin_presets::KelvinPresets::from_unordered(points) -} - -/// As-shot WB multipliers of a body without `ColorData` (the PowerShot G9): the WBInfo row of the preset that -/// ShotInfo's white-balance value names. WBInfo is int32 values in the maker note's byte order, four per preset in -/// G R B G order, at the rows the ExifTool Canon tag-name documentation gives (2 Auto, 10 Daylight, 18 Cloudy, -/// 26 Tungsten, 34 Fluorescent, 50 Flash, 58 Underwater, 66 Custom 1, 74 Custom 2); other settings (14, Daylight -/// Fluorescent, has no documented row) give none. Measured on the CC0 file IMG_1188.CR2 (Custom 1, row 66: -/// 848 1747 1676 848), whose camera JPEG's neutral areas imply the same gains within 0.1 %. -fn wb_from_wb_info(m: &makernote::MakerNote) -> Option<[f32; 3]> { - let row = match m.ifd.u64s(SHOT_INFO)?.get(7)? { - 0 => 2, - 1 => 10, - 2 => 18, - 3 => 26, - 4 => 34, - 5 => 50, - 15 => 66, - 16 => 74, - 17 => 58, - _ => return None, - }; - let b = m.ifd.bytes(WB_INFO)?; - let level = |i: usize| Some(m.order.u32(b.get(4 * (row + i)..4 * (row + i + 1))?.try_into().ok()?) as i32 as f32); - wb_from_levels(level(1)?, level(0)?, level(3)?, level(2)?) -} - -/// The optically black columns left of the image area: from column 2 up to two columns before the first column -/// whose mean (over the image rows) rises above the leftmost columns' level by more than 1/256 of the remaining -/// range (at least 16), else up to two columns before the image area. Empty when the border is too narrow. -fn masked_columns(data: &[u16], width: usize, active: Rect, white: f32) -> Range { - let limit = active.x.saturating_sub(2).min(width); - if limit < 4 || active.height == 0 { - return 0..0; - } - let step = (active.height / 256).max(1); - let column_mean = |x: usize| { - let (mut sum, mut n) = (0.0, 0usize); - for y in (active.y..active.y.saturating_add(active.height)).step_by(step) { - if let Some(&v) = y.checked_mul(width).and_then(|i| data.get(i.checked_add(x)?)) { - sum += f64::from(v); - n += 1; - } - } - (n > 0).then(|| sum / n as f64) - }; - let means: Vec = (2..limit).map_while(column_mean).collect(); - let mut first: Vec = means.iter().take(8).copied().collect(); - first.sort_by(f64::total_cmp); - let Some(&level) = first.get(first.len() / 2) else { return 0..0 }; - let tolerance = ((f64::from(white) - level) / 256.0).max(16.0); - let end = match means.iter().position(|&m| m > level + tolerance) { - // `means[k]` is column `2 + k`: stop two columns before it - Some(k) => k, - None => 2 + means.len(), - }; - 2..end.max(2) -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let tiff = Tiff::parse(bytes)?; - let ifd0 = &tiff.ifds[0]; - let raw = raw_ifd(&tiff).ok_or_else(|| RawError::Corrupt("CR2 without raw IFD".into()))?; - match raw.u32(SRAW_TYPE) { - Some(SRAW_YCC) => return sraw::decode(bytes, &tiff, raw, mode), - Some(v) if v != 1 => return Err(RawError::Unsupported(format!("Canon raw type {v}"))), - _ => {} - } - let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(craft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?; - let len = raw.u64(t::STRIP_BYTE_COUNTS).unwrap_or(bytes.len() as u64 - off.min(bytes.len() as u64)); - let chunk = craft_tiff::image::Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len }; - let src = chunk_bytes(bytes, &chunk).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; - let (fw, fh, nc, prec) = ljpeg::frame_info(src)?; - let frame = match mode { - Mode::Full => { - let total = (fw as u64) - .checked_mul(fh as u64) - .and_then(|v| v.checked_mul(nc as u64)) - .filter(|t| *t > 0 && *t <= crate::MAX_SAMPLES as u64) - .ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?; - Some(ljpeg::decode(src, total as usize)?) - } - Mode::Header => None, - }; - let total = match &frame { - Some(f) => f.data.len(), - None => { - let total = fw - .checked_mul(fh) - .and_then(|v| v.checked_mul(nc)) - .filter(|t| *t > 0) - .ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?; - if total > crate::MAX_SAMPLES { - return Err(RawError::Limit("lossless JPEG frame larger than expected")); - } - total - } - }; - let slices = raw.u64s(CR2_SLICE).filter(|s| s.len() == 3 && s[1] > 0 && s[2] > 0); - let widths: Vec = match &slices { - Some(s) => { - let n = s[0].min(64) as usize; - let mut v = vec![s[1] as usize; n]; - v.push(s[2] as usize); - v - } - None => { - let w = (fw as u64).checked_mul(nc as u64).ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?; - vec![w as usize] - } - }; - let width: usize = widths.iter().sum(); - if width == 0 || total % width != 0 { - return Err(RawError::Corrupt(format!("CR2 slices ({width}) do not divide the frame ({total} samples)"))); - } - let height = total / width; - let mut data = Vec::new(); - if let Some(frame) = &frame { - data = vec![0u16; total]; - let mut i = 0; - let mut x0 = 0; - for &sw in &widths { - for y in 0..height { - data[y * width + x0..y * width + x0 + sw].copy_from_slice(&frame.data[i..i + sw]); - i += sw; - } - x0 += sw; - } - } - drop(frame); - - // maker note: sensor borders and white balance - let make = ifd0.string(t::MAKE).unwrap_or_default(); - let mn = - tiff.exif().and_then(|e| e.get(t::MAKER_NOTE)).and_then(|e| makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)); - let mut active = Rect::new(0, 0, width, height); - if let Some(si) = mn.as_ref().and_then(|m| m.ifd.u64s(SENSOR_INFO)).filter(|v| v.len() >= 9) { - let (l, tp, r, b) = (si[5] as usize, si[6] as usize, si[7] as usize, si[8] as usize); - if r > l && b > tp && r < width && b < height { - active = Rect::new(l, tp, r - l + 1, b - tp + 1); - } - } - let color_data = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order))); - let kelvin_presets = color_data.as_deref().and_then(kelvin_presets_from_color_data); - let wb = color_data.as_deref().and_then(wb_from_color_balance).or_else(|| wb_from_wb_info(mn.as_ref()?)); - let cfa = cfa_from_tag(raw.u64(CR2_CFA_PATTERN)).unwrap_or_else(|| Cfa::bayer_static("RGGB")); - let white = white_from_data(&active_rows(&data, width, active), prec as u32); - let black = match masked_columns(&data, width, active, white) { - cols if cols.len() >= 2 => black_from_columns(&data, width, cols, active.y..active.y + active.height, active), - _ => BlackLevel::uniform(0.0), - }; - let mut metadata = lightcraft_meta::from_tiff(&tiff); - metadata.width = Some(active.width as u32); - metadata.height = Some(active.height as u32); - let img = RawImage { - format: RawFormat::Cr2, - width, - height, - cpp: 1, - data: RawData::U16(data), - cfa: Some(cfa), - bits: prec as u32, - black, - white: vec![white], - active_area: active, - crop: Rect::new(0, 0, active.width, active.height), - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: ColorData { kelvin_presets, ..Default::default() }, - wb_multipliers: wb, - linearized: false, - pixel_aspect: 1.0, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; - - /// Build a synthetic CR2: IFD0..IFD2 placeholders + IFD3 holding a sliced 2-component LJ92 frame. - pub(crate) fn synthetic_cr2(w: usize, h: usize, slices: Option<[u16; 3]>) -> (Vec, Vec) { - synthetic_cr2_note(w, h, slices, None) - } - - /// Like [`synthetic_cr2`], with `note` as the Exif maker note (bytes as stored). - fn synthetic_cr2_note(w: usize, h: usize, slices: Option<[u16; 3]>, note: Option>) -> (Vec, Vec) { - let img: Vec = (0..w * h).map(|i| 1024 + ((i * 7919) % 12000) as u16).collect(); - (synthetic_cr2_of(&img, w, h, slices, note), img) - } - - /// A synthetic CR2 whose sensor samples are `img` (`w`×`h`, 14-bit), with `note` as the Exif maker note. - fn synthetic_cr2_of(img: &[u16], w: usize, h: usize, slices: Option<[u16; 3]>, note: Option>) -> Vec { - let widths: Vec = match slices { - Some([n, sw, last]) => { - let mut v = vec![sw as usize; n as usize]; - v.push(last as usize); - v - } - None => vec![w], - }; - let mut stream = Vec::with_capacity(w * h); - let mut x0 = 0; - for &sw in &widths { - for y in 0..h { - stream.extend_from_slice(&img[y * w + x0..y * w + x0 + sw]); - } - x0 += sw; - } - let enc = crate::ljpeg::encode(&stream, w / 2, h, 2, 14, 1, 0); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("Canon".into())); - ifd0.set(t::MODEL, Value::Ascii("Canon EOS Test".into())); - ifd0.set(t::ORIENTATION, Value::Short(vec![8])); - // maker note: SensorInfo + ColorBalance, plain IFD with offsets relative to the TIFF header - let mut exif = IfdBuilder::new(); - exif.set(t::ISO_SPEED, Value::Short(vec![400])); - if let Some(n) = note { - exif.set(t::MAKER_NOTE, Value::Undefined(n)); - } - ifd0.set_child(t::EXIF_IFD, exif); - let mut ifd3 = IfdBuilder::new(); - ifd3.set(t::COMPRESSION, Value::Short(vec![6])); - ifd3.set(CR2_CFA_PATTERN, Value::Long(vec![3])); - if let Some(s) = slices { - ifd3.set(CR2_SLICE, Value::Short(s.to_vec())); - } - ifd3.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![enc] }); - // (real files also carry a "CR\x02\0" signature at offset 8; probe recognises the structure without it) - TiffWriter::new(ByteOrder::Little, false) - .write(&[ifd0, IfdBuilder::new().with(1, Value::Short(vec![0])), IfdBuilder::new().with(1, Value::Short(vec![0])), ifd3]) - .unwrap() - } - - #[test] - fn synthetic_roundtrip() { - for slices in [None, Some([2u16, 24, 16]), Some([1, 40, 24])] { - let (bytes, img) = synthetic_cr2(64, 10, slices); - assert_eq!(crate::probe(&bytes), Some(RawFormat::Cr2)); - let r = crate::decode(&bytes).unwrap(); - assert_eq!((r.width, r.height), (64, 10)); - assert_eq!(crate::probe_info(&bytes).unwrap(), r.info()); - assert_eq!(r.data, RawData::U16(img)); - assert_eq!(r.orientation, Orientation::Rotate270); - assert_eq!(r.cfa.as_ref().map(Cfa::name).as_deref(), Some("GBRG"), "CR2CFAPattern 3"); - assert_eq!(r.metadata.iso, Some(400)); - assert!(r.develop(crate::Method::Ahd).is_ok()); - } - } - - #[test] - fn cfa_pattern_tag() { - let name = |v| cfa_from_tag(v).map(|c| c.name()); - assert_eq!(name(Some(1)).as_deref(), Some("RGGB")); - assert_eq!(name(Some(2)).as_deref(), Some("BGGR")); - assert_eq!(name(Some(3)).as_deref(), Some("GBRG")); - assert_eq!(name(Some(4)).as_deref(), Some("GRBG")); - assert_eq!(name(Some(0)), None); - assert_eq!(name(Some(7)), None); - assert_eq!(name(None), None); - } - - #[test] - fn wb_probe() { - let mut v = vec![0u64; 120]; - v[63..67].copy_from_slice(&[2000, 1024, 1026, 1500]); - let wb = wb_from_color_balance(&v).unwrap(); - assert!((wb[0] - 2000.0 / 1025.0).abs() < 1e-4 && (wb[2] - 1500.0 / 1025.0).abs() < 1e-4); - assert!(wb_from_color_balance(&[0; 10]).is_none()); - } - - #[test] - fn wb_from_undefined_bytes() { - // hand-coded: ColorData of an S110-like file, UNDEFINED bytes, little-endian words; word 71.. = 1988 745 745 1641 - let mut b = vec![0u8; 2 * 120]; - b[0..2].copy_from_slice(&[0xfd, 0xff]); // version -3 - b[142..150].copy_from_slice(&[0xc4, 0x07, 0xe9, 0x02, 0xe9, 0x02, 0x69, 0x06]); - let le = words(&Value::Undefined(b.clone()), ByteOrder::Little); - assert_eq!(&le[71..75], &[1988, 745, 745, 1641]); - let wb = wb_from_color_balance(&le).unwrap(); - assert!((wb[0] - 1988.0 / 745.0).abs() < 1e-5 && wb[1] == 1.0 && (wb[2] - 1641.0 / 745.0).abs() < 1e-5); - // read as single bytes (the old behaviour) nothing is plausible - assert!(wb_from_color_balance(&b.iter().map(|&x| u64::from(x)).collect::>()).is_none()); - // big-endian note: same words, bytes swapped - let mut be = b.clone(); - be.as_chunks_mut::<2>().0.iter_mut().for_each(|c| c.swap(0, 1)); - assert_eq!(words(&Value::Undefined(be), ByteOrder::Big), le); - // SHORT values pass through, an odd trailing byte is ignored - assert_eq!(words(&Value::Short(vec![1, 2, 3]), ByteOrder::Little), vec![1, 2, 3]); - assert_eq!(words(&Value::Undefined(vec![1, 0, 2]), ByteOrder::Little), vec![1]); - } - - /// Light reaches columns left of the `SensorInfo` border (as on the EOS 6D): the black level comes from the - /// masked columns only, not from the image columns between them and the border. - #[test] - fn black_from_masked_columns_only() { - let (w, h, border, light) = (40, 12, 20, 14); - let data: Vec = (0..w * h).map(|i| if i % w < light { 2048 + (i % 2) as u16 } else { 6000 }).collect(); - let active = Rect::new(border, 2, w - border, h - 2); - let cols = masked_columns(&data, w, active, 15000.0); - assert_eq!(cols, 2..light - 2); - let black = black_from_columns(&data, w, cols, 2..h, active); - assert!(black.values.iter().all(|v| (2048.0..=2049.0).contains(v)), "{:?}", black.values); - // the whole border masked: every column but the two next to the image - let dark: Vec = (0..w * h).map(|i| if i % w < border { 2048 } else { 6000 }).collect(); - assert_eq!(masked_columns(&dark, w, active, 15000.0), 2..border - 2); - // too narrow a border, or no samples (headers-only decode): none - assert!(masked_columns(&dark, w, Rect::new(5, 0, 30, h), 15000.0).is_empty()); - assert!(masked_columns(&[], w, active, 15000.0).is_empty()); - } - - /// A maker note holding only `tag` as `ty` (3 = SHORT, 7 = UNDEFINED) with `data`, a plain IFD whose value - /// offset is relative to the TIFF header (patched by [`patch_note`] once the note's position is known). - fn note_with(tag: u16, ty: u16, data: &[u8]) -> Vec { - let count = if ty == 3 { data.len() / 2 } else { data.len() } as u32; - let mut note = Vec::new(); - note.extend_from_slice(&1u16.to_le_bytes()); - note.extend_from_slice(&tag.to_le_bytes()); - note.extend_from_slice(&ty.to_le_bytes()); - note.extend_from_slice(&count.to_le_bytes()); - note.extend_from_slice(&0u32.to_le_bytes()); // value offset, patched below - note.extend_from_slice(&0u32.to_le_bytes()); // next IFD - note.extend_from_slice(data); - note - } - - fn patch_note(bytes: &mut [u8]) { - let tiff = Tiff::parse(bytes).unwrap(); - let e = tiff.exif().unwrap().get(t::MAKER_NOTE).unwrap(); - let off = e.offset as usize; - bytes[off + 10..off + 14].copy_from_slice(&(e.offset as u32 + 18).to_le_bytes()); - } - - fn decode_with_color_data(ty: u16, data: &[u8]) -> RawImage { - let (mut bytes, _) = synthetic_cr2_note(64, 10, None, Some(note_with(COLOR_BALANCE, ty, data))); - patch_note(&mut bytes); - crate::decode(&bytes).unwrap() - } - - /// A maker note of `entries` (tag, TIFF type, value bytes), each value stored after the IFD, decoded; the value - /// offsets (relative to the TIFF header) are patched once the note's position is known. - fn decode_with_note(entries: &[(u16, u16, Vec)]) -> RawImage { - let ifd_len = 2 + 12 * entries.len() + 4; - let (mut note, mut data, mut at) = (Vec::new(), Vec::new(), Vec::new()); - note.extend_from_slice(&(entries.len() as u16).to_le_bytes()); - for (tag, ty, value) in entries { - let count = if *ty == 3 { value.len() / 2 } else { value.len() } as u32; - note.extend_from_slice(&tag.to_le_bytes()); - note.extend_from_slice(&ty.to_le_bytes()); - note.extend_from_slice(&count.to_le_bytes()); - at.push((note.len(), ifd_len + data.len())); - note.extend_from_slice(&0u32.to_le_bytes()); - data.extend_from_slice(value); - } - note.extend_from_slice(&0u32.to_le_bytes()); - note.extend_from_slice(&data); - let (mut bytes, _) = synthetic_cr2_note(64, 10, None, Some(note)); - let tiff = Tiff::parse(&bytes).unwrap(); - let off = tiff.exif().unwrap().get(t::MAKER_NOTE).unwrap().offset as usize; - for (field, value) in at { - bytes[off + field..off + field + 4].copy_from_slice(&((off + value) as u32).to_le_bytes()); - } - crate::decode(&bytes).unwrap() - } - - /// Issue #1273: the PowerShot G9 has no `ColorData`; its preset levels are WBInfo (`0x0029`: BYTE, int32 values, - /// four per preset in G R B G order), and ShotInfo (`0x0004`) value 7 says which preset was used (15 = Custom 1, - /// row 66: 848 1747 1676 848 on the CC0 file IMG_1188.CR2). - #[test] - fn white_balance_from_wb_info_when_there_is_no_color_data() { - let shot_info = |wb: u16| { - let mut v = [0u16; 34]; - v[7] = wb; - v.iter().flat_map(|x| x.to_le_bytes()).collect::>() - }; - let mut rows = vec![0i32; 512]; - rows[2..6].copy_from_slice(&[850, 1805, 1684, 850]); - rows[66..70].copy_from_slice(&[848, 1747, 1676, 848]); - rows[74..78].copy_from_slice(&[820, 1901, 4000, 820]); - rows[18..22].copy_from_slice(&[850, 1805, 6000, 850]); - let wb_info: Vec = rows.iter().flat_map(|x| x.to_le_bytes()).collect(); - let wb = |si: u16| decode_with_note(&[(0x0004, 3, shot_info(si)), (0x0029, 1, wb_info.clone())]).wb_multipliers; - assert_eq!(wb(15), Some([1747.0 / 848.0, 1.0, 1676.0 / 848.0])); - assert_eq!(wb(0), Some([1805.0 / 850.0, 1.0, 1684.0 / 850.0])); - // each preset its own row (Custom 2: row 74); an empty row (Daylight here), an implausible one (Cloudy: - // B 7.1) or a value without a documented row (14) gives none - assert_eq!(wb(16), Some([1901.0 / 820.0, 1.0, 4000.0 / 820.0])); - assert_eq!(wb(1), None); - assert_eq!(wb(2), None); - assert_eq!(wb(14), None); - // without ShotInfo, or with WBInfo too short for the row - assert_eq!(decode_with_note(&[(0x0029, 1, wb_info.clone())]).wb_multipliers, None); - assert_eq!(decode_with_note(&[(0x0004, 3, shot_info(15)), (0x0029, 1, wb_info[..4 * 68].to_vec())]).wb_multipliers, None); - // ColorData, when it gives levels, wins - let mut color_data = vec![0u8; 2 * 120]; - color_data[0..2].copy_from_slice(&[0xfd, 0xff]); - color_data[142..150].copy_from_slice(&[0xc4, 0x07, 0xe9, 0x02, 0xe9, 0x02, 0x69, 0x06]); - let both = decode_with_note(&[(0x0004, 3, shot_info(15)), (0x0029, 1, wb_info.clone()), (COLOR_BALANCE, 7, color_data)]); - assert_eq!(both.wb_multipliers, Some([1988.0 / 745.0, 1.0, 1641.0 / 745.0])); - } - - /// `ColorData` stored as UNDEFINED bytes (versions -3 / -4: PowerShot, EOS M) gives the as-shot WB from word 71, - /// exactly as the same words stored as SHORT do. - #[test] - fn color_data_stored_as_bytes() { - let mut bytes = vec![0u8; 2 * 120]; - bytes[0..2].copy_from_slice(&[0xfd, 0xff]); // version -3 - bytes[142..150].copy_from_slice(&[0xc4, 0x07, 0xe9, 0x02, 0xe9, 0x02, 0x69, 0x06]); // 1988 745 745 1641 - for ty in [7, 3] { - let wb = decode_with_color_data(ty, &bytes).wb_multipliers.unwrap_or_else(|| panic!("type {ty}: no WB")); - assert!((wb[0] - 1988.0 / 745.0).abs() < 1e-5 && wb[1] == 1.0 && (wb[2] - 1641.0 / 745.0).abs() < 1e-5, "type {ty}: {wb:?}"); - } - } - - /// `ColorData` words of `version` with the planckian presets (R, B over G = 1024, Kelvin) at its - /// [`preset_rows`], a Fluorescent-like green row between them, and the as-shot levels at word 71 / 63. - fn color_data_with_presets(version: i16, presets: &[(u16, u16, u16)]) -> Vec { - let mut v = vec![0u64; 400]; - v[0] = u64::from(version as u16); - for ((at, temp_at), &(r, b, k)) in preset_rows(version).unwrap().into_iter().zip(presets) { - v[at..at + 4].copy_from_slice(&[r.into(), 1024, 1024, b.into()]); - v[temp_at] = k.into(); - } - v - } - - /// Issue #157 of a downstream fork: the PowerShot G1 X Mark III (`ColorData` -4) gets a Kelvin curve from its - /// Daylight, Shade, Cloudy, Tungsten and Flash presets (levels and temperatures as its files carry them), which - /// puts a preset's own levels at the preset's temperature; the EOS bodies of versions 13–15 likewise. - #[test] - fn kelvin_presets_from_color_data_presets() { - let g1x3 = [(1418, 1357, 5651), (1653, 1171, 7505), (1533, 1259, 6594), (963, 2016, 3174), (1807, 1080, 8529)]; - let v = color_data_with_presets(-4, &g1x3); - let p = kelvin_presets_from_color_data(&v).unwrap(); - for (r, b, k) in g1x3 { - let (t, tint) = p.temp_tint([r as f32 / 1024.0, 1.0, b as f32 / 1024.0]).unwrap(); - assert!((t - k as f64).abs() < 1.0 && tint.abs() < 0.1, "{k}: {t} {tint}"); - } - // levels between Tungsten and Daylight: a temperature between them - let (t, _) = p.temp_tint([1264.0 / 1024.0, 1.0, 1537.0 / 1024.0]).unwrap(); - assert!((3174.0..5651.0).contains(&t), "{t}"); - let eos = [(2013, 1479, 5200), (2300, 1280, 7000), (2153, 1374, 6000), (1442, 2089, 3200), (2203, 1371, 6156)]; - for version in [13, 14, 15] { - assert!(kelvin_presets_from_color_data(&color_data_with_presets(version, &eos)).is_some(), "{version}"); - } - // a preset that would turn the curve back (Flash cooler than Shade's levels say) is dropped, not fatal - let mut odd = g1x3; - odd[4] = (1500, 1300, 9000); - assert!(kelvin_presets_from_color_data(&color_data_with_presets(-4, &odd)).is_some()); - } - - /// Unknown versions, short or garbled arrays give no presets and never panic. - #[test] - fn kelvin_presets_from_hostile_color_data() { - let g1x3 = [(1418, 1357, 5651), (1653, 1171, 7505), (1533, 1259, 6594), (963, 2016, 3174), (1807, 1080, 8529)]; - let good = color_data_with_presets(-4, &g1x3); - let mut other = good.clone(); - other[0] = u64::from(-3i16 as u16); - assert!(kelvin_presets_from_color_data(&other).is_none(), "unverified version"); - assert!(kelvin_presets_from_color_data(&[]).is_none()); - for len in [1, 96, 120, 157, 158] { - assert!(kelvin_presets_from_color_data(&good[..len]).is_none(), "{len}"); - } - let mut zeros = good.clone(); - for at in [102, 118, 126] { - zeros[at] = 0; - } - assert!(kelvin_presets_from_color_data(&zeros).is_none(), "two points left"); - let mut seed = 0x2545_f491_4f6c_dd1du64; - for _ in 0..2000 { - let v: Vec = (0..200) - .map(|i| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - if i == 0 { [0xfffc, 13, 14, 15][(seed % 4) as usize] } else { seed % 70000 } - }) - .collect(); - let _ = kelvin_presets_from_color_data(&v); - } - // through a whole decode, ColorData as UNDEFINED bytes - let bytes: Vec = good.iter().flat_map(|&w| (w as u16).to_le_bytes()).collect(); - assert!(decode_with_color_data(7, &bytes).color.kelvin_presets.is_some()); - assert!(decode_with_color_data(7, &bytes[..200]).color.kelvin_presets.is_none()); - } - - /// Masked rows above the image full of samples at 16383 (EOS 50D, issue #1272): the white level is the image's - /// own saturation plateau, not the edge of that strip, so clipped highlights still reach 1.0. - #[test] - fn white_from_active_area_only() { - let (w, h, top, left) = (64, 40, 4, 8); - let img: Vec = (0..w * h) - .map(|i| match (i % w, i / w) { - (_, y) if y < top => 16383, - (x, _) if x < left => 1024, - _ if i % 7 == 0 => 13433, - _ => 1024 + ((i * 7919) % 11000) as u16, - }) - .collect(); - // SensorInfo: width, height, three unused words, then the inclusive left/top/right/bottom borders - let si: Vec = [w, h, 0, 0, 0, left, top, w - 1, h - 1].iter().flat_map(|&v| (v as u16).to_le_bytes()).collect(); - let mut bytes = synthetic_cr2_of(&img, w, h, None, Some(note_with(SENSOR_INFO, 3, &si))); - patch_note(&mut bytes); - let r = crate::decode(&bytes).unwrap(); - assert_eq!(r.active_area, Rect::new(left, top, w - left, h - top)); - assert!((13300.0..=13433.0).contains(&r.white[0]), "{:?}", r.white); - } -} diff --git a/crates/raw/src/vendor/cr2/sraw.rs b/crates/raw/src/vendor/cr2/sraw.rs deleted file mode 100644 index 742ce3a58a..0000000000 --- a/crates/raw/src/vendor/cr2/sraw.rs +++ /dev/null @@ -1,580 +0,0 @@ -//! Canon sRAW / mRAW: reduced-resolution YCbCr "raw" frames in CR2 (raw IFD tag `0xc6c5` = 4). -//! -//! What the files contain (measured on the 31 CC0 sRAW / mRAW samples of 16 models, see the evidence below): -//! -//! - The raw strip is one lossless-JPEG frame with three components. Luma is sampled 2×1 (sRAW, 4:2:2, `0x21`) or -//! 2×2 (mRAW, 4:2:0, `0x22`), both chroma components 1×1; precision 15, predictor 1, no restart markers. -//! The frame's width and height are only a factorisation of the sample count: they are not the image size. -//! - The decoded sample stream (MCU after MCU: `Y Y Cb Cr` or `Y Y Y Y Cb Cr`) is cut into vertical slices exactly -//! like the CFA data (`cr2_slice = [n, w, last]`, widths counted in samples). A slice row is a whole number of -//! MCUs, so the image is `Σw / MCU-size × 2` pixels wide, and one slice row is one pixel row (4:2:2) or two (4:2:0). -//! - Prediction: each component is a one-dimensional chain in decoding order (so the second luma row of a 4:2:0 MCU -//! continues from the end of the first), and the first sample of every frame row starts from the first sample of -//! the previous one ([`ljpeg::Prediction::Sequential`]). The Sony prediction (geometric) gives vertical stripes on -//! these files. -//! - The samples are linear. Luma is the BT.601 luma (0.299, 0.587, 0.114; also the TIFF 6.0 default -//! `YCbCrCoefficients`) of white-balanced camera RGB, about 7/8 of the black-subtracted sensor counts; chroma is -//! centred on 16384. White balance is baked in (neutral surfaces have neutral chroma); which of the maker note's -//! white-balance sets was used is not always the as-shot one, so it is not undone. -//! - Chroma is stored as a scaled colour difference, `R − Y = a·(Cr − 16384)` and `B − Y = b·(Cb − 16384)`, with -//! `G` from the luma equation. `a` and `b` are about 1.0 on bodies from 2012 on, but about 5.7 and 7.4 (the TIFF -//! 6.0 YCbCr ratio 1.402 : 1.772, scaled by about 4.1) on the 2008–2010 bodies (5D Mark II, 50D, 7D, 60D, 1D Mark IV). -//! Rather than keying a table on the model, the gains are measured per file against the 16-bit RGB image the -//! camera stores in IFD2 for these files (see [`chroma_gains`]). -//! -//! Only these files were used as evidence: the sRAW samples themselves, the same cameras' CFA files of the same -//! scenes (raw counts against the decoded samples), and the IFD2 image. The ExifTool tag documentation was used for -//! tag names. - -use super::{COLOR_BALANCE, CR2_SLICE, SENSOR_INFO, words}; -use crate::{BlackLevel, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; -use craft_tiff::image::{Chunk, chunk_bytes}; -use craft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t}; -use lightcraft_geom::Orientation; -use rayon::prelude::*; - -/// Chroma samples are centred on this value. -const CHROMA_CENTRE: f64 = 16384.0; -/// BT.601 luma weights, the TIFF 6.0 default `YCbCrCoefficients`. -const KR: f64 = 0.299; -const KG: f64 = 0.587; -const KB: f64 = 0.114; -/// Decoded luma relative to black-subtracted sensor counts (white-balanced): 0.877, 0.877, 0.896, 0.880, 0.871, 0.851 -/// and 0.846 on the 7D Mark II, 5DS R, 6D Mark II, 5DS, 5D Mark II, 1D X Mark II and 50D (CFA and sRAW files of the -/// same scene), so 7/8. It sets the white level, so that a file renders about as bright as the CFA file of the same -/// scene. -const LUMA_GAIN: f32 = 0.875; -/// Full scale of a 14-bit sensor, the white level of a CFA CR2 without a saturation plateau. -const SENSOR_FULL: f32 = 16383.0; -/// Mid-tone limit (IFD2 units) of the pixels used for the chroma fit: above about a quarter of full scale the -/// camera's own RGB image rolls off. -const FIT_LIMIT: f64 = 4096.0; - -/// How the decoded frame maps to the image. -#[derive(Debug, PartialEq)] -pub(super) struct Layout { - pub width: usize, - pub height: usize, - /// Vertical subsampling of the chroma planes: 1 (4:2:2, sRAW) or 2 (4:2:0, mRAW). - pub vertical: usize, - /// Slice widths in samples. - widths: Vec, - /// Slice height in MCU rows. - rows: usize, - /// Samples per MCU. - mcu: usize, - /// Frame size from the SOF3 header. - frame_width: usize, - frame_height: usize, -} - -impl Layout { - /// The layout of a `frame_width × frame_height` frame with `vertical` chroma subsampling and `cr2_slice` tag - /// values `slices` (`[n, w, last]`). - pub(super) fn new(frame_width: usize, frame_height: usize, vertical: usize, slices: &[u64]) -> Result { - let &[n, w, last] = slices else { return Err(RawError::Corrupt("sRAW without slice layout".into())) }; - if n > 64 || w == 0 || last == 0 { - return Err(RawError::Corrupt("sRAW slice layout".into())); - } - let mcu = 2 * vertical + 2; - let mut widths = vec![w as usize; n as usize]; - widths.push(last as usize); - if widths.iter().any(|w| w % mcu != 0) { - return Err(RawError::Corrupt("sRAW slice is not a whole number of MCUs".into())); - } - let samples = - frame_width.checked_mul(frame_height).and_then(|p| p.checked_add(p / vertical)).ok_or(RawError::Limit("sRAW frame too large"))?; - let row = widths.iter().try_fold(0usize, |a, &w| a.checked_add(w)).ok_or(RawError::Limit("sRAW slice widths"))?; - if samples == 0 || row == 0 || samples % row != 0 { - return Err(RawError::Corrupt(format!("sRAW slices ({row} samples per row) do not divide the frame ({samples} samples)"))); - } - let rows = samples / row; - let (width, height) = (row / mcu * 2, rows * vertical); - if width.checked_mul(height).and_then(|p| p.checked_mul(3)).is_none_or(|s| s > crate::MAX_SAMPLES) { - return Err(RawError::Limit("sRAW image too large")); - } - Ok(Layout { width, height, vertical, widths, rows, mcu, frame_width, frame_height }) - } -} - -/// Planar YCbCr at image geometry: luma `width × height`, chroma `width/2 × height/vertical`. -struct Planes { - width: usize, - height: usize, - vertical: usize, - y: Vec, - cb: Vec, - cr: Vec, -} - -impl Planes { - fn chroma_width(&self) -> usize { - self.width / 2 - } - - /// Re-chop the decoded MCU stream into image planes. - fn arrange(frame: &ljpeg::FrameSubsampled, layout: &Layout) -> Planes { - let (w, h, v, m) = (layout.width, layout.height, layout.vertical, layout.mcu); - let cw = w / 2; - let mut p = Planes { width: w, height: h, vertical: v, y: vec![0; w * h], cb: vec![0; cw * (h / v)], cr: vec![0; cw * (h / v)] }; - let mcus_per_frame_row = layout.frame_width / 2; - let mut x0 = 0; - for &sw in &layout.widths { - let per_row = sw / m; - let first = layout.rows * (x0 / m); - for r in 0..layout.rows { - for k in 0..per_row { - let q = first + r * per_row + k; - let (qy, qx) = (q / mcus_per_frame_row, q % mcus_per_frame_row); - let px = (x0 / m + k) * 2; - for dy in 0..v { - let src = (qy * v + dy) * layout.frame_width + qx * 2; - let dst = (r * v + dy) * w + px; - p.y[dst..dst + 2].copy_from_slice(&frame.planes[0][src..src + 2]); - } - p.cb[r * cw + px / 2] = frame.planes[1][qy * mcus_per_frame_row + qx]; - p.cr[r * cw + px / 2] = frame.planes[2][qy * mcus_per_frame_row + qx]; - } - } - x0 += sw; - } - p - } - - /// Mean luma / Cb / Cr over the pixel window `[x0, x1) × [y0, y1)` (non-empty, inside the image). - fn window_mean(&self, x0: usize, x1: usize, y0: usize, y1: usize) -> (f64, f64, f64) { - let (mut sy, mut ny) = (0f64, 0f64); - for y in y0..y1 { - let row = &self.y[y * self.width + x0..y * self.width + x1]; - sy += row.iter().map(|&v| f64::from(v)).sum::(); - ny += row.len() as f64; - } - let (cx0, cx1) = (x0 / 2, x1.div_ceil(2).max(x0 / 2 + 1)); - let (cy0, cy1) = (y0 / self.vertical, y1.div_ceil(self.vertical).max(y0 / self.vertical + 1)); - let (mut sb, mut sr, mut nc) = (0f64, 0f64, 0f64); - for y in cy0..cy1.min(self.height / self.vertical) { - for x in cx0..cx1.min(self.chroma_width()) { - sb += f64::from(self.cb[y * self.chroma_width() + x]); - sr += f64::from(self.cr[y * self.chroma_width() + x]); - nc += 1.0; - } - } - let nc = nc.max(1.0); - (sy / ny.max(1.0), sb / nc - CHROMA_CENTRE, sr / nc - CHROMA_CENTRE) - } - - /// Linear RGB (`width × height × 3`): `R = Y + a·Cr`, `B = Y + b·Cb`, `G` from the luma equation. - fn to_rgb(&self, a: f64, b: f64) -> Vec { - let (gr, gb) = ((KR / KG * a) as f32, (KB / KG * b) as f32); - let (a, b) = (a as f32, b as f32); - let cw = self.chroma_width(); - let centre = CHROMA_CENTRE as f32; - let mut out = vec![0u16; self.width * self.height * 3]; - out.par_chunks_mut(self.width * 3).enumerate().for_each(|(y, row)| { - let luma = &self.y[y * self.width..(y + 1) * self.width]; - let chroma = (y / self.vertical) * cw; - for (x, px) in row.as_chunks_mut::<3>().0.iter_mut().enumerate() { - let (cb, cr) = (f32::from(self.cb[chroma + x / 2]) - centre, f32::from(self.cr[chroma + x / 2]) - centre); - let l = f32::from(luma[x]); - px[0] = (l + a * cr).round().clamp(0.0, 65535.0) as u16; - px[1] = (l - gr * cr - gb * cb).round().clamp(0.0, 65535.0) as u16; - px[2] = (l + b * cb).round().clamp(0.0, 65535.0) as u16; - } - }); - out - } -} - -/// The 16-bit RGB image in IFD2 (`SRawType` 3): the camera's own rendering of the same frame at a fraction of the -/// size, white-balanced and linear below about a quarter of full scale. -struct Preview { - width: usize, - height: usize, - rgb: Vec, -} - -fn read_preview(bytes: &[u8], tiff: &Tiff) -> Option { - let info = tiff.ifds.get(2)?.image().ok()?; - let (w, h) = (info.width as usize, info.height as usize); - if info.samples_per_pixel != 3 || info.bits_per_sample != [16, 16, 16] || info.compression != 1 || info.planar != 1 || info.sample_format != 1 { - return None; - } - let n = w.checked_mul(h)?.checked_mul(3)?; - if n == 0 || n > 1 << 24 { - return None; - } - let mut raw: Vec = Vec::with_capacity(n * 2); - for c in info.chunks(bytes.len() as u64) { - raw.extend_from_slice(chunk_bytes(bytes, &c)?); - if raw.len() >= n * 2 { - break; - } - } - if raw.len() < n * 2 { - return None; - } - let order: ByteOrder = tiff.order; - let rgb = raw.as_chunks::<2>().0.iter().take(n).map(|&c| order.u16(c)).collect(); - Some(Preview { width: w, height: h, rgb }) -} - -#[derive(Default)] -struct Regression { - n: f64, - sx: f64, - st: f64, - sxx: f64, - sxt: f64, - stt: f64, -} - -impl Regression { - fn add(&mut self, x: f64, t: f64) { - self.n += 1.0; - self.sx += x; - self.st += t; - self.sxx += x * x; - self.sxt += x * t; - self.stt += t * t; - } - - /// Least-squares slope of `t` on `x` (with intercept) and its residual sum of squares. - fn slope(&self) -> Option<(f64, f64)> { - let var = self.n * self.sxx - self.sx * self.sx; - if self.n < 500.0 || var <= 1e-9 * self.n * self.n { - return None; - } - let slope = (self.n * self.sxt - self.sx * self.st) / var; - let icpt = (self.st - slope * self.sx) / self.n; - let rss = - self.stt - 2.0 * slope * self.sxt - 2.0 * icpt * self.st + slope * slope * self.sxx + 2.0 * slope * icpt * self.sx + self.n * icpt * icpt; - Some((slope, rss.max(0.0))) - } -} - -/// How the IFD2 image sits on the full-size planes: its pixel `(i, j)` covers the window starting at -/// `(x0 + i·sx, y0 + j·sy)` and `sx × sy` pixels large. -struct Grid { - x0: f64, - y0: f64, - sx: f64, - sy: f64, -} - -/// The chroma gains `(a, b)` of this file (`R − Y = a·Cr`, `B − Y = b·Cb`), by least squares of the IFD2 image -/// against the planes averaged to its size. Where IFD2 sits on the frame depends on the model (the whole frame, -/// the sensor's active area, or a whole or half-integer reduction of the frame that overhangs it by a few pixels), -/// so these are tried and the best fit is kept. `None` when the file has no usable IFD2 or the fit is not well -/// conditioned. -fn chroma_gains(planes: &Planes, preview: &Preview, active: Rect) -> Option<(f64, f64)> { - let (pw, ph) = (preview.width as f64, preview.height as f64); - let (w, h) = (planes.width as f64, planes.height as f64); - let grids = [ - Grid { x0: 0.0, y0: 0.0, sx: w / pw, sy: h / ph }, - Grid { x0: active.x as f64, y0: active.y as f64, sx: active.width as f64 / pw, sy: active.height as f64 / ph }, - Grid { x0: 0.0, y0: 0.0, sx: (2.0 * w / pw).round() / 2.0, sy: (2.0 * h / ph).round() / 2.0 }, - ]; - let mut best: Option<(f64, f64, f64)> = None; - for g in &grids { - if !(g.sx >= 1.0 && g.sy >= 1.0) { - continue; - } - let (mut fr, mut fb) = (Regression::default(), Regression::default()); - for j in 0..preview.height { - let y0 = (g.y0 + j as f64 * g.sy) as usize; - let y1 = ((g.y0 + (j + 1) as f64 * g.sy) as usize).min(planes.height); - for i in 0..preview.width { - let p = &preview.rgb[(j * preview.width + i) * 3..][..3]; - let [r, gr, b] = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]; - if r.max(gr).max(b) >= FIT_LIMIT || r.min(gr).min(b) <= 0.0 { - continue; - } - let x0 = (g.x0 + i as f64 * g.sx) as usize; - let x1 = ((g.x0 + (i + 1) as f64 * g.sx) as usize).min(planes.width); - if x1 <= x0 || y1 <= y0 { - continue; - } - let (y, cb, cr) = planes.window_mean(x0, x1, y0, y1); - if y < 150.0 { - continue; - } - fr.add(cr, r - y); - fb.add(cb, b - y); - } - } - if let (Some((a, ra)), Some((b, rb))) = (fr.slope(), fb.slope()) { - let cost = (ra + rb) / (fr.n + fb.n); - if a.is_finite() && b.is_finite() && best.is_none_or(|(_, _, c)| cost < c) { - best = Some((a, b, cost)); - } - } - } - best.map(|(a, b, _)| (a, b)).filter(|(a, b)| (0.25..=16.0).contains(a) && (0.25..=16.0).contains(b)) -} - -/// Word index of `AverageBlackLevel` (four equal-ish values) in the maker note's `ColorData` by `ColorDataVersion` -/// (word 0), located by searching the CC0 samples for the values ExifTool reports. -fn average_black_at(version: i16) -> Option { - Some(match version { - 6 | 7 | 9 => 231, - 10 | 11 => 276, - 12 | 13 | 15 => 326, - _ => return None, - }) -} - -/// The sensor's black level in raw counts from `ColorData` (`None` for versions whose position is not known, and -/// when the four values are not plausible and near-equal). -fn colour_data_black(words: &[u64]) -> Option { - let version = words.first().map(|&v| v as u16 as i16)?; - let q = words.get(average_black_at(version)?..)?.get(..4)?; - let (lo, hi) = (q.iter().min()?, q.iter().max()?); - ((256..=4096).contains(lo) && hi - lo <= 8).then(|| q.iter().sum::() as f32 / 4.0) -} - -/// Decode a Canon sRAW / mRAW CR2 into linear white-balanced camera RGB (`cpp` 3). -pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode) -> Result { - let ifd0 = &tiff.ifds[0]; - let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(craft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?; - let len = raw.u64(t::STRIP_BYTE_COUNTS).unwrap_or(bytes.len() as u64 - off.min(bytes.len() as u64)); - let chunk = Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len }; - let src = chunk_bytes(bytes, &chunk).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?; - let (fw, fh, vertical) = ljpeg::frame_info_subsampled(src)?; - let slices = raw.u64s(CR2_SLICE).unwrap_or_default(); - let layout = Layout::new(fw, fh, vertical, &slices)?; - - let make = ifd0.string(t::MAKE).unwrap_or_default(); - let mn = - tiff.exif().and_then(|e| e.get(t::MAKER_NOTE)).and_then(|e| makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)); - let (w, h) = (layout.width, layout.height); - let mut active = Rect::new(0, 0, w, h); - if let Some(si) = mn.as_ref().and_then(|m| m.ifd.u64s(SENSOR_INFO)).filter(|v| v.len() >= 9) { - let (l, tp, r, b) = (si[5] as usize, si[6] as usize, si[7] as usize, si[8] as usize); - if r > l && b > tp && r < w && b < h { - active = Rect::new(l, tp, r - l + 1, b - tp + 1); - } - } - let colour_data = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order))); - let black_counts = colour_data.as_deref().and_then(colour_data_black); - // 1.0 = a CFA CR2 of the same body at full 14-bit scale; see LUMA_GAIN - let white = LUMA_GAIN * (SENSOR_FULL - black_counts.unwrap_or(0.0)); - - let data = match mode { - Mode::Header => Vec::new(), - Mode::Full => { - let samples = fw * fh + fw * fh / vertical; - let frame = ljpeg::decode_subsampled(src, samples.min(crate::MAX_SAMPLES), ljpeg::Prediction::Sequential)?; - let planes = Planes::arrange(&frame, &layout); - drop(frame); - let (a, b) = read_preview(bytes, tiff).and_then(|p| chroma_gains(&planes, &p, active)).unwrap_or((1.0, 1.0)); - planes.to_rgb(a, b) - } - }; - - let mut metadata = lightcraft_meta::from_tiff(tiff); - metadata.width = Some(active.width as u32); - metadata.height = Some(active.height as u32); - let img = RawImage { - format: RawFormat::Cr2, - width: w, - height: h, - cpp: 3, - data: RawData::U16(data), - cfa: None, - bits: 14, - black: BlackLevel::uniform(0.0), - white: vec![white], - active_area: active, - crop: Rect::new(0, 0, active.width, active.height), - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: ColorData::default(), - // the camera's white balance is already applied, as in Sony's linear YCbCr - wb_multipliers: Some([1.0; 3]), - linearized: false, - pixel_aspect: 1.0, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -#[cfg(test)] -mod tests { - use super::*; - use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; - - const SRAW_TYPE_TAG: u16 = 0xc6c5; - - /// The 4:2:2 stream of `ljpeg`'s hand-coded fixture (4 × 2 frame, two MCUs per frame row) decodes to luma - /// 1000 1001 / 1002 1003 / 1100 1101 / 1102 1103 in MCU order, Cb 16384 16385 16484 16485, Cr 16484 16486 - /// 16584 16586. - fn stream_422() -> Vec { - ljpeg::tests::fixture_subsampled(4, 2, 0x21, &[-31768, 1, -16384, -16284, 1, 1, 1, 2, 100, 1, 100, 100, 1, 1, 1, 2]) - } - - /// A CR2 whose raw IFD holds `stream` cut into the slices `slices` (IFD2 = a 2 × 2 16-bit RGB image when - /// `preview` is given). - fn sraw_file(stream: Vec, slices: [u16; 3], sraw_type: u32, preview: Option<[u16; 12]>) -> Vec { - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("Canon".into())); - ifd0.set(t::MODEL, Value::Ascii("Canon EOS Test".into())); - let mut ifd2 = IfdBuilder::new(); - if let Some(p) = preview { - ifd2.set(t::COMPRESSION, Value::Short(vec![1])); - ifd2.set(t::PHOTOMETRIC, Value::Short(vec![2])); - ifd2.set(t::IMAGE_WIDTH, Value::Long(vec![2])); - ifd2.set(t::IMAGE_LENGTH, Value::Long(vec![2])); - ifd2.set(t::BITS_PER_SAMPLE, Value::Short(vec![16, 16, 16])); - ifd2.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![3])); - ifd2.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![p.iter().flat_map(|v| v.to_le_bytes()).collect()] }); - } else { - ifd2.set(1, Value::Short(vec![0])); - } - let mut ifd3 = IfdBuilder::new(); - ifd3.set(t::COMPRESSION, Value::Short(vec![6])); - ifd3.set(SRAW_TYPE_TAG, Value::Long(vec![sraw_type])); - ifd3.set(CR2_SLICE, Value::Short(slices.to_vec())); - ifd3.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![stream] }); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0, IfdBuilder::new().with(1, Value::Short(vec![0])), ifd2, ifd3]).unwrap() - } - - #[test] - fn slices_are_cut_back_into_image_columns_and_converted() { - // slices [1, 4, 4]: two slices of one MCU per row; slice 0 holds MCUs 0 and 1 (image rows 0 and 1), slice 1 - // holds MCUs 2 and 3, so the image is 4 × 2 with luma 1000 1001 1100 1101 / 1002 1003 1102 1103. - let bytes = sraw_file(stream_422(), [1, 4, 4], 4, None); - let img = crate::decode(&bytes).unwrap(); - assert_eq!((img.width, img.height, img.cpp), (4, 2, 3)); - assert!(img.cfa.is_none()); - assert_eq!(img.wb_multipliers, Some([1.0; 3])); - let RawData::U16(px) = &img.data else { panic!("integer data") }; - // no IFD2: chroma gains 1; R = Y + Cr', B = Y + Cb', G from the BT.601 luma - let expect = |y: f64, cb: f64, cr: f64| { - let (r, b) = (y + cr, y + cb); - [r, (y - KR * r - KB * b) / KG, b].map(|v| v.round() as i32) - }; - let cases = [ - ((0, 0), expect(1000.0, 0.0, 100.0)), - ((1, 0), expect(1001.0, 0.0, 100.0)), - ((2, 0), expect(1100.0, 100.0, 200.0)), - ((3, 0), expect(1101.0, 100.0, 200.0)), - ((0, 1), expect(1002.0, 1.0, 102.0)), - ((3, 1), expect(1103.0, 101.0, 202.0)), - ]; - for ((x, y), want) in cases { - let got: Vec = px[(y * 4 + x) * 3..][..3].iter().map(|&v| i32::from(v)).collect(); - assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1), "({x},{y}): {got:?} vs {want:?}"); - } - // header-only decoding reports the same image - assert_eq!(crate::probe_info(&bytes).unwrap(), img.info()); - assert!(img.develop(crate::Method::Bilinear).is_ok()); - } - - #[test] - fn a_preview_too_small_to_fit_leaves_the_gains_at_one() { - // IFD2 of 2 × 2 pixels cannot support a fit (it needs hundreds of samples): the file still decodes - let with = crate::decode(&sraw_file(stream_422(), [1, 4, 4], 4, Some([900; 12]))).unwrap(); - let without = crate::decode(&sraw_file(stream_422(), [1, 4, 4], 4, None)).unwrap(); - assert_eq!(with.data, without.data); - } - - #[test] - fn only_ycbcr_frames_take_this_path() { - // other raw types (3 is the preview image's) stay unsupported, as before - for kind in [0, 2, 3, 5] { - let bytes = sraw_file(stream_422(), [1, 4, 4], kind, None); - assert!(matches!(crate::decode(&bytes), Err(RawError::Unsupported(_))), "type {kind}"); - } - } - - #[test] - fn slice_layouts_must_fit_the_frame() { - let ok = Layout::new(4, 2, 1, &[1, 4, 4]).unwrap(); - assert_eq!((ok.width, ok.height), (4, 2)); - // 4:2:0: six samples per MCU, one slice row is two image rows - let l = Layout::new(8, 4, 2, &[1, 12, 12]).unwrap(); - assert_eq!((l.width, l.height), (8, 4)); - assert!(Layout::new(4, 2, 1, &[1, 3, 5]).is_err()); // not whole MCUs - assert!(Layout::new(4, 2, 1, &[1, 4, 8]).is_err()); // rows do not divide the frame - assert!(Layout::new(4, 2, 1, &[1, 0, 4]).is_err()); - assert!(Layout::new(4, 2, 1, &[4, 4]).is_err()); // not three values - assert!(Layout::new(4, 2, 1, &[65, 4, 4]).is_err()); - // slice widths whose sum overflows (or wraps to zero) are rejected, not divided by - assert!(Layout::new(4, 2, 1, &[3, 1 << 62, 1 << 62]).is_err()); - assert!(Layout::new(4, 2, 1, &[1, u64::MAX - 3, 4]).is_err()); - let bytes = sraw_file(stream_422(), [1, 4, 8], 4, None); - assert!(crate::decode(&bytes).is_err()); - } - - /// Textured luma and smooth chroma on `w × h` planes. - fn test_planes(w: usize, h: usize, vertical: usize) -> Planes { - let y: Vec = (0..w * h).map(|i| (600 + ((i % w) * 13 + (i / w) * 29) % 1500) as u16).collect(); - let cw = w / 2; - let ch = h / vertical; - let cb = (0..cw * ch).map(|i| (16384 + (i % cw) as i32 * 7 - (i / cw) as i32 * 3 - 150) as u16).collect(); - let cr = (0..cw * ch).map(|i| (16384 + (i / cw) as i32 * 5 + (i % cw) as i32 * 2 - 120) as u16).collect(); - Planes { width: w, height: h, vertical, y, cb, cr } - } - - /// An IFD2 image of `pw × ph` pixels at `scale` per pixel, built the way the files relate it to the planes. - fn preview_of(p: &Planes, pw: usize, ph: usize, scale: usize, a: f64, b: f64, pedestal: f64) -> Preview { - let mut rgb = Vec::new(); - for j in 0..ph { - for i in 0..pw { - let (y, cb, cr) = p.window_mean(i * scale, (i + 1) * scale, j * scale, (j + 1) * scale); - let (r, bl) = (y + a * cr, y + b * cb); - let g = (y - KR * r - KB * bl) / KG; - rgb.extend([r, g, bl].map(|v| (v + pedestal).round().clamp(0.0, 65535.0) as u16)); - } - } - Preview { width: pw, height: ph, rgb } - } - - #[test] - fn chroma_gains_are_measured_against_the_preview() { - for vertical in [1, 2] { - for (a, b) in [(1.0, 1.0), (5.7, 7.4), (1.13, 1.12)] { - let planes = test_planes(160, 96, vertical); - // IFD2 is a plain 1/4 reduction, optionally with a black pedestal (some bodies add one) - for pedestal in [0.0, 520.0] { - let preview = preview_of(&planes, 40, 24, 4, a, b, pedestal); - let (ga, gb) = - chroma_gains(&planes, &preview, Rect::new(0, 0, 160, 96)).unwrap_or_else(|| panic!("no fit for {a}, {b}, {vertical}")); - assert!((ga / a - 1.0).abs() < 0.02 && (gb / b - 1.0).abs() < 0.02, "vertical {vertical}: ({a}, {b}) measured as ({ga}, {gb})"); - } - } - } - // the preview overhangs the frame by a few pixels: the whole-frame scale (4.1) is wrong, 4 is right - let planes = test_planes(164, 96, 1); - let mut preview = preview_of(&planes, 40, 24, 4, 5.7, 7.4, 0.0); - let (ga, gb) = chroma_gains(&planes, &preview, Rect::new(0, 0, 164, 96)).unwrap(); - assert!((ga / 5.7 - 1.0).abs() < 0.02 && (gb / 7.4 - 1.0).abs() < 0.02, "({ga}, {gb})"); - // a preview of something else gives no usable fit rather than a wild gain - preview.rgb.iter_mut().enumerate().for_each(|(i, v)| *v = (1000 + (i * 7919) % 3000) as u16); - assert!( - chroma_gains(&planes, &preview, Rect::new(0, 0, 164, 96)).is_none_or(|(a, b)| (0.25..=16.0).contains(&a) && (0.25..=16.0).contains(&b)) - ); - } - - #[test] - fn colour_data_black_by_version() { - let mut w = vec![0u64; 400]; - w[0] = 7; - w[231..235].copy_from_slice(&[2048, 2047, 2048, 2048]); - assert_eq!(colour_data_black(&w), Some(2047.75)); - w[0] = 12; - assert_eq!(colour_data_black(&w), None); // the black level of another version lives elsewhere - w[326..330].copy_from_slice(&[512, 512, 511, 512]); - assert_eq!(colour_data_black(&w), Some(511.75)); - w[326..330].copy_from_slice(&[512, 512, 100, 512]); // implausible - assert_eq!(colour_data_black(&w), None); - w[0] = 3; - assert_eq!(colour_data_black(&w), None); // no position known: black 0 - w[0] = 65533; // -3 - assert_eq!(colour_data_black(&w), None); - assert_eq!(colour_data_black(&[]), None); - assert_eq!(colour_data_black(&[7, 1, 2]), None); - } -} diff --git a/crates/raw/src/vendor/cr3.rs b/crates/raw/src/vendor/cr3.rs index 8a0a54c8c6..084135a65a 100644 --- a/crates/raw/src/vendor/cr3.rs +++ b/crates/raw/src/vendor/cr3.rs @@ -54,7 +54,7 @@ fn cfa(pattern: u8) -> Option { 3 => "BGGR", _ => return None, }; - Some(Cfa::bayer_static(name)) + Some(crate::bayer(name)) } /// Inclusive offsets, clipped to the sample dimensions (some Canon crop-mode files record right diff --git a/crates/raw/src/vendor/crw.rs b/crates/raw/src/vendor/crw.rs deleted file mode 100644 index d48e1f229b..0000000000 --- a/crates/raw/src/vendor/crw.rs +++ /dev/null @@ -1,255 +0,0 @@ -//! Canon CRW (CIFF heap) raw decoding through the shared `craft-crw` crate (craft-libs, -//! `crates/crw`): the bodies before the CR2 era (EOS D30/D60/10D/300D, PowerShot G-series). -//! -//! The decoder, its frozen code tables and its clean-room record live in -//! craft-libs (`crates/crw/clean-room/`: the frozen format `02-crw-format.md`, the verification -//! `03-verification.md`, 28 of 29 corpus files and 1,516 EOS D60 files sample-exact against a -//! black-box reference). This module maps its output onto [`RawImage`]: CFA phase, black and white -//! levels, active area, orientation, as-shot white balance and the make, model and capture-time -//! records (a CRW carries no Exif block, so this is where the catalog learns the camera). -//! -//! Known gaps (documented in the freeze): the PowerShot G5's entropy coding diverges from the -//! model and is refused (its embedded JPEG is shown instead); PowerShot bodies without CC0 samples -//! (G2/G3/Pro1/S-series) decode through the same model unverified. Colour matrices for these -//! bodies are LightCraft's own (`chart_table`, the EOS D60); the file carries none. - -use crate::{BlackLevel, Cfa, ColorData, Metadata, Mode, OpcodeLists, Orientation, RawData, RawError, RawFormat, RawImage, Rect, Result}; -use lightcraft_meta::DateTime; - -fn map_err(e: craft_crw::Error) -> RawError { - match e { - craft_crw::Error::NotCrw => RawError::NotRaw, - craft_crw::Error::Corrupt(why) => RawError::Corrupt(format!("CRW: {why}")), - craft_crw::Error::Unsupported(why) => RawError::Unsupported(format!("CRW: {why}")), - craft_crw::Error::LimitExceeded(what) => RawError::Limit(what), - } -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - // the crate's own cap (2²³ samples; the largest CRW frame is 7.4 million): its decode holds - // about three `u16` buffers of the declared size, so the raw crate's general `MAX_SAMPLES` - // (2³⁰) would let a malformed file ask for gigabytes. No sample may be filled after the - // entropy stream ends (the crate allows one 64-sample block by default): every corpus file - // ends exactly on its frame, so a shorter stream is a truncated file and is `Corrupt`. - let mut limits = craft_crw::Limits::default(); - limits.max_stream_end_fill = 0; - let full = mode == Mode::Full; - let (h, samples, black, white) = if full { - let img = craft_crw::decode(bytes, &limits).map_err(map_err)?; - let black = BlackLevel { repeat_rows: 2, repeat_cols: 2, values: img.black.values.to_vec(), delta_h: vec![], delta_v: vec![] }; - (img.header, img.samples, black, img.white) - } else { - let h = craft_crw::header(bytes, &limits).map_err(map_err)?; - let white = ((1u32 << h.bits.clamp(1, 16)) - 1) as f32; - (h, Vec::new(), BlackLevel::uniform(0.0), white) - }; - let active = Rect::new(h.active_area.x, h.active_area.y, h.active_area.width, h.active_area.height); - let orientation = Orientation::from_exif(h.exif_orientation as _); - let metadata = Metadata { - make: h.make, - model: h.model, - capture_time: h.capture_unix.and_then(datetime_from_unix), - width: Some(active.width as u32), - height: Some(active.height as u32), - orientation: Some(orientation), - ..Metadata::default() - }; - let img = RawImage { - format: RawFormat::Crw, - width: h.width, - height: h.height, - cpp: 1, - data: RawData::U16(samples), - cfa: Some(Cfa::bayer_static(h.cfa.name())), - bits: h.bits, - black, - white: vec![white], - active_area: active, - crop: Rect::new(0, 0, active.width, active.height), - orientation, - color: ColorData::default(), - wb_multipliers: h.wb_multipliers, - linearized: false, - pixel_aspect: 1.0, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -/// Civil date-time from the TimeStamp record's Unix seconds (the camera's local clock, no UTC -/// offset; inverse of [`DateTime::unix_seconds`]). Before 1970 or after 2200 is a garbage clock, -/// not a capture time. -fn datetime_from_unix(t: i64) -> Option { - use chrono::{Datelike, Timelike}; - let c = chrono::DateTime::from_timestamp(t, 0)?.naive_utc(); - let dt = DateTime { - year: u16::try_from(c.year()).ok()?, - month: u8::try_from(c.month()).ok()?, - day: u8::try_from(c.day()).ok()?, - hour: u8::try_from(c.hour()).ok()?, - minute: u8::try_from(c.minute()).ok()?, - second: u8::try_from(c.second()).ok()?, - millis: 0, - offset_minutes: None, - }; - ((1970..=2200).contains(&dt.year)).then_some(dt) -} - -#[cfg(test)] -mod tests { - use super::*; - - const W: usize = 48; - const H: usize = 20; - - /// A CIFF file with the records the decoder reads and a pseudo-random payload: enough for the - /// header path; the entropy data decodes or is refused, never panics. - fn synthetic_crw(model: &str) -> Vec { - synthetic_crw_sized(model, W, H) - } - - fn synthetic_crw_sized(model: &str, w: usize, h: usize) -> Vec { - let payload: Vec = (0..514 + 256).map(|i| (i * 41 % 253) as u8).collect(); - synthetic_crw_with_payload(model, w, h, payload) - } - - fn synthetic_crw_with_payload(model: &str, w: usize, h: usize, payload: Vec) -> Vec { - let le16 = |v: u16| v.to_le_bytes(); - let le32 = |v: u32| v.to_le_bytes(); - let heap = |records: &[(u16, Vec)]| -> Vec { - let mut b = Vec::new(); - let mut entries = Vec::new(); - for (tc, v) in records { - entries.push((*tc, v.len() as u32, b.len() as u32)); - b.extend_from_slice(v); - if b.len() % 2 == 1 { - b.push(0); - } - } - let tbl = b.len() as u32; - b.extend_from_slice(&le16(entries.len() as u16)); - for (tc, l, off) in entries { - b.extend_from_slice(&le16(tc)); - b.extend_from_slice(&le32(l)); - b.extend_from_slice(&le32(off)); - } - b.extend_from_slice(&le32(tbl)); - b - }; - let sensor: Vec = [34u16, w as u16, h as u16, 0, 0, 2, 2, w as u16 - 3, h as u16 - 3].iter().flat_map(|&v| le16(v)).collect(); - let dtable: Vec = [0u32, 0, 514, 0].iter().flat_map(|&v| le32(v)).collect(); - let image_info: Vec = [w as u32, h as u32, 0, 270, 12, 12, 0].iter().flat_map(|&v| le32(v)).collect(); - let mut color_balance: Vec = vec![66]; - color_balance.extend([2000u16, 800, 800, 960]); - color_balance.extend((0..7).flat_map(|_| [1500u16, 900, 900, 1500])); - let color_balance: Vec = color_balance.iter().flat_map(|&v| le16(v)).collect(); - let mut make_model = b"Canon\0".to_vec(); - make_model.extend_from_slice(model.as_bytes()); - make_model.push(0); - let props = heap(&[ - (0x1031, sensor), - (0x1835, dtable), - (0x080a, make_model), - (0x1810, image_info), - (0x180e, [1083410638u32, 0, 0].iter().flat_map(|&v| le32(v)).collect()), - (0x10a9, color_balance), - ]); - let root = heap(&[(0x2005, payload), (0x300a, props)]); - let mut f = b"II".to_vec(); - f.extend_from_slice(&le32(26)); - f.extend_from_slice(b"HEAPCCDR"); - f.extend_from_slice(&le32(0x0001_0002)); - f.extend_from_slice(&[0; 8]); - f.extend_from_slice(&root); - f - } - - #[test] - fn header_mode_maps_the_records_onto_raw_image() { - let f = synthetic_crw("Canon EOS D60"); - let img = decode(&f, Mode::Header).expect("header decodes"); - assert_eq!((img.format, img.width, img.height, img.bits, img.cpp), (RawFormat::Crw, W, H, 10, 1)); - assert_eq!(img.data.len(), 0); - assert_eq!(img.active_area, Rect::new(2, 2, W - 4, H - 4)); - assert_eq!(img.crop, Rect::new(0, 0, W - 4, H - 4)); - assert_eq!(img.cfa.as_ref().map(|c| c.name()).as_deref(), Some("RGGB")); - assert_eq!(img.orientation, Orientation::from_exif(8)); - assert_eq!(img.metadata.make.as_deref(), Some("Canon")); - assert_eq!(img.metadata.model.as_deref(), Some("Canon EOS D60")); - assert_eq!(img.metadata.orientation, Some(Orientation::from_exif(8))); - assert_eq!(img.metadata.capture_time.map(|t| t.unix_seconds()), Some(1083410638)); - let wb = img.wb_multipliers.expect("ColorBalance slot 0"); - assert!((wb[0] - 2.5).abs() < 1e-3 && wb[1] == 1.0 && (wb[2] - 1.2).abs() < 1e-3, "{wb:?}"); - assert_eq!(img.white, vec![1023.0]); - assert_eq!(img.black, BlackLevel::uniform(0.0)); - // the entropy data is pseudo-random: decodes or errors, never panics - let _ = decode(&f, Mode::Full); - let g1 = decode(&synthetic_crw("Canon PowerShot G1"), Mode::Header).expect("header decodes"); - assert_eq!(g1.cfa.as_ref().map(|c| c.name()).as_deref(), Some("GBRG")); - } - - #[test] - fn errors_map_onto_raw_error() { - assert!(matches!(decode(b"II*\0\x08\0\0\0", Mode::Full), Err(RawError::NotRaw))); - assert!(matches!(decode(b"II HEAPCCDR ", Mode::Full), Err(RawError::Corrupt(w)) if w.starts_with("CRW: "))); - let Err(RawError::Unsupported(why)) = decode(&synthetic_crw("Canon PowerShot G5"), Mode::Header) else { panic!("expected Unsupported") }; - assert!(why.contains("PowerShot G5"), "{why}"); - assert_eq!(map_err(craft_crw::Error::LimitExceeded("image too large")), RawError::Limit("image too large")); - } - - /// A file declaring more samples than any CRW camera has is refused before anything is - /// allocated: 4096 × 4096 (16.8 million) passed when the adapter raised the crate's cap of 2²³ - /// to the raw crate's 2³⁰. - #[test] - fn an_oversized_crw_is_refused_by_the_crates_own_limit() { - let f = synthetic_crw_sized("Canon EOS D60", 4096, 4096); - for mode in [Mode::Header, Mode::Full] { - assert_eq!(decode(&f, mode).err(), Some(RawError::Limit("image too large")), "{mode:?}"); - } - // the largest real frame (the 10D's 3152 × 2068) is within it - assert!(decode(&synthetic_crw_sized("Canon EOS D60", 3152, 2068), Mode::Header).is_ok()); - } - - /// A stream cut short is `Corrupt`, not a smeared image: the crate once filled every sample - /// after the entropy stream ended with its predictor value and returned success, so a CRW - /// truncated just past its header rendered and exported as a flat frame. - #[test] - fn a_truncated_entropy_stream_is_corrupt() { - // the 514-byte header and two bytes of entropy: almost all of the 960-sample frame unread - let f = synthetic_crw_with_payload("Canon EOS D60", W, H, vec![0; 516]); - let Err(RawError::Corrupt(why)) = decode(&f, Mode::Full) else { panic!("a truncated stream must be refused") }; - assert!(why.starts_with("CRW: ") && why.contains("before the frame does"), "{why}"); - // the header alone still reads, so the library can list the file and show its preview - assert!(decode(&f, Mode::Header).is_ok()); - } - - /// A stream that ends a few samples short is `Corrupt` too: the crate's default limit fills up - /// to one 64-sample block silently, and no real CRW fills any. - #[test] - fn a_stream_a_few_samples_short_is_corrupt() { - // an all-zero entropy stream of 842 bytes decodes the 960-sample frame exactly - let payload = |len: usize| vec![0u8; 514 + len]; - let whole = synthetic_crw_with_payload("Canon EOS D60", W, H, payload(842)); - assert!(decode(&whole, Mode::Full).is_ok()); - // six bytes fewer leave 10 samples unread, within the crate's default of 64 - let short = synthetic_crw_with_payload("Canon EOS D60", W, H, payload(836)); - let filled = craft_crw::decode(&short, &craft_crw::Limits::default()).map(|i| i.stream_end_fill); - assert_eq!(filled, Ok(10)); - let Err(RawError::Corrupt(why)) = decode(&short, Mode::Full) else { panic!("a stream 10 samples short must be refused") }; - assert!(why.contains("10 samples before the frame does"), "{why}"); - } - - #[test] - fn unix_datetime_inverse_matches_unix_seconds() { - for t in [0i64, 1, 86399, 86400, 951867295, 1083410638, 1600000000, 4102444799] { - let dt = datetime_from_unix(t).expect("in range"); - assert_eq!(dt.unix_seconds(), t, "{t}"); - } - // Before 1970 or after 2200 is a garbage clock, not a capture time. - assert!(datetime_from_unix(-1).is_none()); - assert!(datetime_from_unix(i64::MAX).is_none()); - } -} diff --git a/crates/raw/src/vendor/erf.rs b/crates/raw/src/vendor/erf.rs deleted file mode 100644 index 0a1316448b..0000000000 --- a/crates/raw/src/vendor/erf.rs +++ /dev/null @@ -1,234 +0,0 @@ -//! Epson ERF (R-D1, R-D1s, R-D1x): a big-endian TIFF whose `SubIFDs` child is a 12-bit CFA image in 16-byte blocks. -//! -//! Sources: TIFF 6.0 (container, `CFARepeatPatternDim` / `CFAPattern`) and our own black-box analysis of the three -//! CC0 ERF samples on raw.pixls.us (one per body); every number below was measured on them. -//! -//! - IFD0 is a 160 x 120 RGB thumbnail; its `SubIFDs` child is the raw: 3040 x 2024, 12 bits, `Compression` 32769, -//! photometric CFA, one strip of exactly `width * 8 / 5` bytes per row. Byte 15 of every 16 is zero in all rows: -//! a row is 16-byte blocks, each 15 bytes of ten 12-bit samples, most significant bits first (`b0 << 4 | b1 >> 4`, -//! `(b1 & 15) << 8 | b2`), then a pad byte. Read the other way (least significant first, as the Olympus blocks are) -//! the frame is noise: the mean step between same-colour neighbours is 150..199 codes against 11..18. -//! - `CFAPattern` `00 01 01 02`: RGGB. -//! - The maker note (`EPSON\0\x01\0`, then a big-endian IFD with offsets from the file start) holds four black levels -//! as `u32` in tag `0x0401` (61..65; in Bayer-cell order), above which the darkest 0.01% of samples sit; `0x020b` x -//! `0x020c` is the picture size, 3008 x 2000. Registered against the 640 x 424 preview JPEG (correlation of the -//! green channel over every even offset), that picture starts at column 20, row 12 in all three files. -//! - White: the saturation plateau (4095 on the clipped R-D1x frame), else 4095. -//! - No maker-note tag tracks the as-shot white balance across the three files, so it is measured from the -//! preview's neutral pixels ([`crate::wb_estimate`]); on the R-D1s sample (54,000 neutral preview pixels) that -//! gives red 2.68 and blue 1.31. -//! - The preview is the maker note's tag `0x0280`, a JPEG whose first byte is stored as `ee` (found by the -//! structural scan in `preview::scan_for_jpeg`). -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; -use craft_tiff::image::chunk_bytes; -use craft_tiff::{Ifd, Tiff, tags as t}; -use lightcraft_geom::Orientation; - -/// Epson's private compression code for the 16-byte block layout. -const BLOCKS16: u16 = 32769; -/// Maker-note tags. -const MN_BLACK: u16 = 0x0401; -const MN_WIDTH: u16 = 0x020b; -const MN_HEIGHT: u16 = 0x020c; -/// Where the picture starts in the sensor frame (measured, see the module notes). -const CROP_ORIGIN: (usize, usize) = (20, 12); - -/// The raw IFD of an Epson ERF: CFA, 12 bits, compression 32769, one strip of 16-byte blocks of ten samples. -pub(crate) fn raw_ifd(tiff: &Tiff, len: usize) -> Option<&Ifd> { - let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str())?; - if !make.to_ascii_uppercase().contains("EPSON") { - return None; - } - tiff.all_ifds().into_iter().find(|i| { - let Ok(info) = i.image() else { return false }; - let (w, h) = (info.width as u64, info.height as u64); - i.u16(t::PHOTOMETRIC) == Some(t::photometric::CFA) - && i.u16(t::COMPRESSION) == Some(BLOCKS16) - && i.u16(t::BITS_PER_SAMPLE) == Some(12) - && w > 0 - && w % 10 == 0 - && matches!(info.chunks(len as u64).as_slice(), [c] if Some(c.len) == (w * 8 / 5).checked_mul(h)) - }) -} - -/// The maker-note IFD (`EPSON\0\x01\0` then an IFD in the file's byte order, offsets from the file start). -fn maker_note(bytes: &[u8], tiff: &Tiff) -> Option { - let e = tiff.exif()?.get(t::MAKER_NOTE)?; - let start = usize::try_from(e.offset).ok()?; - if !bytes.get(start..)?.starts_with(b"EPSON\0") { - return None; - } - let opts = craft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() }; - craft_tiff::parse_ifd_at(bytes, e.offset.checked_add(8)?, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) -} - -/// Unpack a strip of 16-byte blocks (15 bytes of ten MSB-first 12-bit samples, one pad byte). -fn unpack(src: &[u8], out: &mut [u16]) { - let (blocks, _) = src.as_chunks::<16>(); - let (pixels, _) = out.as_chunks_mut::<10>(); - for (b, px) in blocks.iter().zip(pixels) { - crate::unpack::unpack_msb(&b[..15], 12, px); - } -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let tiff = Tiff::parse(bytes)?; - let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("Erf TIFF without IFDs".into()))?; - let raw = raw_ifd(&tiff, bytes.len()).ok_or_else(|| RawError::Unsupported("Erf raw image not found".into()))?; - let info = raw.image()?; - let (w, h) = (info.width as usize, info.height as usize); - let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { - (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, - _ => return Err(RawError::Unsupported("Erf raw without a 2x2 CFAPattern".into())), - }; - let mn = maker_note(bytes, &tiff); - let black = match mn.as_ref().and_then(|m| m.u64s(MN_BLACK)).as_deref() { - Some(v @ [_, _, _, _]) if v.iter().all(|&b| b < 4095) => { - BlackLevel { repeat_rows: 2, repeat_cols: 2, values: v.iter().map(|&b| b as f32).collect(), delta_h: vec![], delta_v: vec![] } - } - _ => BlackLevel::uniform(0.0), - }; - let size = mn.as_ref().and_then(|m| Some((m.u32(MN_WIDTH)? as usize, m.u32(MN_HEIGHT)? as usize))); - let crop = match size { - Some((cw, ch)) if cw > 0 && ch > 0 && CROP_ORIGIN.0 + cw <= w && CROP_ORIGIN.1 + ch <= h => Rect::new(CROP_ORIGIN.0, CROP_ORIGIN.1, cw, ch), - _ => Rect::new(0, 0, w, h), - }; - // the white balance is measured from the samples, so the header probe reads them too - // the strip length is the tag value, so a short file must fail before the sample buffer is sized from it - let chunks = info.chunks(bytes.len() as u64); - let src = chunks - .first() - .and_then(|c| chunk_bytes(bytes, c).filter(|s| s.len() as u64 == c.len)) - .ok_or_else(|| RawError::Corrupt("Erf strip outside file".into()))?; - let mut d = vec![0u16; n]; - unpack(src, &mut d); - let white = super::white_from_data(&d, 12); - let wb = crate::wb_estimate::as_shot(bytes, &crate::wb_estimate::Frame { data: &d, width: w, crop, cfa: &cfa, black: &black, white }); - let data = if mode == Mode::Full { RawData::U16(d) } else { RawData::U16(Vec::new()) }; - let mut metadata = lightcraft_meta::from_tiff(&tiff); - metadata.width = Some(crop.width as u32); - metadata.height = Some(crop.height as u32); - let img = RawImage { - format: RawFormat::Erf, - width: w, - height: h, - cpp: 1, - data, - cfa: Some(cfa), - bits: 12, - black, - white: vec![white], - active_area: Rect::new(0, 0, w, h), - crop, - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: ColorData::default(), - wb_multipliers: wb, - linearized: false, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - pixel_aspect: 1.0, - }; - img.validate_for(mode)?; - Ok(img) -} - -#[cfg(test)] -mod tests { - use super::*; - use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; - - /// Pack ten-sample groups into 16-byte blocks, MSB first, zero pad. - fn pack(px: &[u16]) -> Vec { - let mut out = Vec::new(); - for g in px.chunks(10) { - for p in g.chunks(2) { - let (a, b) = (p[0], p[1]); - out.extend_from_slice(&[(a >> 4) as u8, ((a & 15) << 4) as u8 | (b >> 8) as u8, b as u8]); - } - out.push(0); - } - out - } - - fn sample(w: u32, h: u32, px: &[u16]) -> Vec { - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); - raw.set(t::COMPRESSION, Value::Short(vec![BLOCKS16])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![pack(px)] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("SEIKO EPSON CORP.".into())); - ifd0.set(t::MODEL, Value::Ascii("R-D1".into())); - ifd0.set(t::ORIENTATION, Value::Short(vec![1])); - ifd0.add_sub_ifd(raw); - TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() - } - - #[test] - fn decodes_the_block_layout() { - let (w, h) = (20u32, 6u32); - let px: Vec = (0..w * h).map(|i| (i * 37 % 4096) as u16).collect(); - let f = sample(w, h, &px); - assert_eq!(crate::probe(&f), Some(RawFormat::Erf)); - let r = crate::decode(&f).unwrap(); - assert_eq!(r.data, RawData::U16(px)); - assert_eq!(r.cfa.as_ref().map(Cfa::name).as_deref(), Some("RGGB")); - assert!(r.wb_multipliers.is_some()); - assert_eq!(crate::probe_info(&f).unwrap(), r.info()); - } - - #[test] - fn malformed_files_never_panic() { - let px: Vec = (0..200).map(|i| (i * 13 % 4096) as u16).collect(); - let f = sample(20, 10, &px); - for n in (0..f.len()).step_by(3) { - let _ = crate::decode(&f[..n]); - } - for i in 0..f.len() { - for v in [0u8, 0xff] { - let mut g = f.clone(); - g[i] = v; - let _ = crate::decode(&g); - let _ = crate::probe_info(&g); - } - } - } - - /// Rewrite the raw IFD's height, rows per strip and strip length in place (the strip data stays as written). - fn declare(f: &mut [u8], rows: u32, strip_len: u32) { - let tiff = Tiff::parse(f).unwrap(); - let raw = &tiff.ifds[0].sub_ifds[0]; - let spots: Vec<_> = [(t::IMAGE_LENGTH, rows), (t::ROWS_PER_STRIP, rows), (t::STRIP_BYTE_COUNTS, strip_len)] - .into_iter() - .map(|(tag, v)| { - let e = raw.entries.iter().find(|e| e.tag == tag).unwrap(); - (e.offset as usize, matches!(e.value, Value::Short(_)), v) - }) - .collect(); - for (at, short, v) in spots { - if short { - f[at..at + 2].copy_from_slice(&u16::try_from(v).unwrap().to_be_bytes()); - } else { - f[at..at + 4].copy_from_slice(&v.to_be_bytes()); - } - } - } - - #[test] - fn a_strip_longer_than_the_file_is_an_error() { - // #2119: the declared strip length matched the size, so a few bytes of data were decoded as a full frame - let px: Vec = (0..40).map(|i| (i * 13 % 4096) as u16).collect(); - let mut f = sample(20, 2, &px); - declare(&mut f, 2000, 32 * 2000); - assert_eq!(crate::probe(&f), Some(RawFormat::Erf)); - assert!(matches!(crate::probe_info(&f), Err(RawError::Corrupt(_)))); - assert!(matches!(crate::decode(&f), Err(RawError::Corrupt(_)))); - } -} diff --git a/crates/raw/src/vendor/hasselblad.rs b/crates/raw/src/vendor/hasselblad.rs deleted file mode 100644 index 9ec21d85c9..0000000000 --- a/crates/raw/src/vendor/hasselblad.rs +++ /dev/null @@ -1,295 +0,0 @@ -//! Hasselblad 3FR and FFF raws ([`crate::RawFormat::CfaTiff`]). -//! -//! Sources: TIFF 6.0 (container), the DNG Specification (the tags these files borrow) and our own black-box -//! analysis of a CC0 H4D-40 FFF from raw.pixls.us (931, "Hasselblad - H4D-40 - 16bit (4:3).fff"); every number -//! below was measured on it. -//! -//! - Both are TIFFs without a DNG version tag that describe their raw image with DNG's tags: a full-resolution -//! CFA sub-IFD with `BlackLevel`, `WhiteLevel`, `DefaultCropOrigin` / `DefaultCropSize`, and `AsShotNeutral`. -//! [`crate::dng::decode_as`] reads all of that; this module adds what that reader does not know about. -//! - The raw image is uncompressed (X1D, X1D II, X2D, CFV 100C) or Hasselblad's lossless JPEG with predictor -//! selection value 8 ([`crate::ljpeg::decode_hasselblad`]); the H4D-40 FFF's 7410 x 5586 strip is the latter. -//! - No `CFAPattern`. The layout is RGGB from the sensor origin: averaged over the 6 x 6 sensor blocks behind each -//! pixel of the file's 1217 x 913 RGB IFD0 image (the default crop is exactly six times its size), the sites at -//! (0, 0) correlate 0.976 with its red and 0.726 with its blue, the sites at (1, 1) 0.896 with blue and 0.847 -//! with red, and the two green sites' diagonal differences are half those of the other pair. -//! - An FFF is a 3FR converted on the desktop. It has no colour matrix of its own: the camera's matrix stays in -//! the original 3FR header, which the FFF carries whole as a little-endian TIFF in the private IFD0 tag -//! `0xC51B` (4096 bytes in the sample: an IFD0 with Make, Model, `ColorMatrix1` and `AsShotNeutral`, a -//! `SubIFDs` pair for the raw and preview images, whose data offsets point into the old 3FR and are not read). -//! [`decode`] takes the matrices from there when the outer file has none. The white balance stays the outer -//! file's, which is the one the converter last saved. -//! - No JPEG preview. IFD0 is an uncompressed 8-bit RGB image (1217 x 913 in the H4D-40 FFF, IFD1 pointing at the -//! same strip; 218 x 218 in the CFV 3FR, under the file's own `Orientation`); the FFF also has a 16-bit RGB -//! copy in a `SubIFDs` child, with a `TransferFunction` whose meaning is not known, so it is not used. -//! [`rgb_preview`] hands the largest 8-bit one on as a small baseline TIFF. -use crate::dng; -use crate::{ColorData, Mode, RawFormat, RawImage, Result}; -use craft_tiff::image::{Layout, chunk_bytes}; -use craft_tiff::{ByteOrder, IfdBuilder, ImageData, ParseOptions, Tiff, TiffWriter, Value, tags as t}; - -/// Private IFD0 tag holding the original 3FR header (a complete TIFF) inside an FFF. -pub(crate) const ORIGINAL_HEADER: u16 = 0xc51b; - -/// Upper bound on the embedded header's size: the sample's is 4 KiB; a larger block is not a header. -const MAX_HEADER: usize = 1 << 20; - -/// Decode a 3FR / FFF (or another TIFF raw in the DNG layout, see [`dng::is_plain_cfa_tiff`]). -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let mut img = dng::decode_as(bytes, mode, RawFormat::CfaTiff)?; - if !crate::color::has_matrix(&img.color) - && let Some(header) = original_header_color(bytes) - { - adopt_matrices(&mut img.color, &header); - } - Ok(img) -} - -/// The colour tags of the original 3FR header an FFF embeds in [`ORIGINAL_HEADER`], when it has a colour matrix. -fn original_header_color(bytes: &[u8]) -> Option { - let outer = Tiff::parse(bytes).ok()?; - let block = outer.ifds.first()?.bytes(ORIGINAL_HEADER)?; - if block.len() > MAX_HEADER { - return None; - } - let opts = ParseOptions { max_ifds: 16, max_depth: 2, ..Default::default() }; - let header = Tiff::parse_with(block, &opts).ok()?; - let ifd0 = header.ifds.first()?; - let raw = dng::raw_ifd(&header).unwrap_or(ifd0); - let color = dng::color_data(ifd0, raw, header.order); - crate::color::has_matrix(&color).then_some(color) -} - -/// Upper bound on a preview's pixel bytes (8-bit RGB): 64 MP, far above the 1.1 MP of the largest one seen. -const MAX_PREVIEW_BYTES: usize = (64 << 20) * 3; - -/// The file's largest uncompressed 8-bit RGB image (chunky, in strips), as a little-endian baseline TIFF holding -/// just those pixels, which `lightcraft_codecs::decode` reads. No `Orientation` tag is written: the viewer -/// applies the raw file's, which is the one that stands over this image in IFD0. -pub(crate) fn rgb_preview(tiff: &Tiff, bytes: &[u8]) -> Option> { - let info = tiff - .all_ifds() - .into_iter() - .filter_map(|i| i.image().ok()) - .filter(|i| { - i.photometric == t::photometric::RGB - && i.compression == t::compression::NONE - && i.samples_per_pixel == 3 - && i.bits_per_sample.iter().all(|&b| b == 8) - && i.planar == 1 - && i.sample_format == 1 - && matches!(i.layout, Layout::Strips { .. }) - && i.width > 0 - && i.height > 0 - }) - .max_by_key(|i| u64::from(i.width) * u64::from(i.height))?; - let (w, h) = (info.width as usize, info.height as usize); - let size = w.checked_mul(h)?.checked_mul(3)?; - if size > MAX_PREVIEW_BYTES { - return None; - } - let mut pixels = Vec::with_capacity(size); - for chunk in info.chunks(bytes.len() as u64) { - pixels.extend_from_slice(chunk_bytes(bytes, &chunk)?); - if pixels.len() >= size { - break; - } - } - // a short last strip is a truncated file: no preview rather than a picture with a black band - if pixels.len() < size { - return None; - } - pixels.truncate(size); - let mut ifd = IfdBuilder::new(); - ifd.set(t::IMAGE_WIDTH, Value::Long(vec![info.width])); - ifd.set(t::IMAGE_LENGTH, Value::Long(vec![info.height])); - ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![8, 8, 8])); - ifd.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![3])); - ifd.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::RGB])); - ifd.set(t::COMPRESSION, Value::Short(vec![t::compression::NONE])); - ifd.set(t::PLANAR_CONFIGURATION, Value::Short(vec![1])); - ifd.set_image(ImageData::Strips { rows_per_strip: info.height, strips: vec![pixels] }); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).ok() -} - -/// Take the camera matrices (and the illuminants they belong to) of `from`; the rest of `color` stays. -fn adopt_matrices(color: &mut ColorData, from: &ColorData) { - color.illuminant = from.illuminant; - color.color_matrix = from.color_matrix; - color.forward_matrix = from.forward_matrix; - color.camera_calibration = from.camera_calibration; -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{RawData, RawError, decode as decode_file, probe, probe_info}; - use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t}; - - const MATRIX: [(i32, i32); 9] = - [(686, 1000), (-196, 1000), (-32, 1000), (-437, 1000), (1228, 1000), (235, 1000), (-165, 1000), (317, 1000), (675, 1000)]; - - fn rgb_ifd() -> IfdBuilder { - let mut ifd = IfdBuilder::new(); - ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![1])); - ifd.set(t::IMAGE_WIDTH, Value::Long(vec![4])); - ifd.set(t::IMAGE_LENGTH, Value::Long(vec![3])); - ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![8, 8, 8])); - ifd.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![3])); - ifd.set(t::PHOTOMETRIC, Value::Short(vec![2])); - ifd.set(t::COMPRESSION, Value::Short(vec![1])); - ifd.set_image(ImageData::Strips { rows_per_strip: 3, strips: vec![(0..36).collect()] }); - ifd - } - - /// The camera's 3FR header as an FFF embeds it: a little-endian TIFF whose IFD0 has the colour matrix. - fn original_header(matrix: bool) -> Vec { - let mut ifd0 = rgb_ifd(); - ifd0.set(t::MAKE, Value::Ascii("Hasselblad".into())); - ifd0.set(t::MODEL, Value::Ascii("Hasselblad H4D".into())); - if matrix { - ifd0.set(t::COLOR_MATRIX_1, Value::SRational(MATRIX.to_vec())); - } - ifd0.set(t::AS_SHOT_NEUTRAL, Value::Rational(vec![(43, 100), (1, 1), (79, 100)])); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() - } - - /// An FFF in miniature: big-endian, IFD0 an RGB image with `AsShotNeutral` and the embedded header `header`, - /// a 16-bit uncompressed CFA sub-IFD of 8 x 6 samples, no colour matrix of its own unless `own_matrix`. - fn fff(header: Option>, own_matrix: bool) -> Vec { - fff_with(header, own_matrix, vec![]) - } - - /// [`fff`] with more `SubIFDs` children of IFD0 (other preview images). - fn fff_with(header: Option>, own_matrix: bool, extra: Vec) -> Vec { - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![8])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![6])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![16])); - raw.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); - raw.set(t::COMPRESSION, Value::Short(vec![1])); - raw.set(t::BLACK_LEVEL, Value::Rational(vec![(256, 1)])); - raw.set(t::WHITE_LEVEL, Value::Short(vec![65535])); - raw.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![(0..96u8).collect()] }); - let mut ifd0 = rgb_ifd(); - ifd0.set(t::MAKE, Value::Ascii("Hasselblad".into())); - ifd0.set(t::MODEL, Value::Ascii("Hasselblad H4D-40".into())); - ifd0.set(t::AS_SHOT_NEUTRAL, Value::Rational(vec![(2, 5), (1, 1), (4, 5)])); - if own_matrix { - ifd0.set(t::COLOR_MATRIX_1, Value::SRational(vec![(1, 1), (0, 1), (0, 1), (0, 1), (1, 1), (0, 1), (0, 1), (0, 1), (1, 1)])); - } - if let Some(h) = header { - ifd0.set(ORIGINAL_HEADER, Value::Undefined(h)); - } - ifd0.add_sub_ifd(raw); - for e in extra { - ifd0.add_sub_ifd(e); - } - TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap() - } - - fn matrix_row0(c: &ColorData) -> Option<[f64; 3]> { - c.color_matrix[0].map(|m| m.0[0]) - } - - /// The FFF's own tags give the samples and white balance; the colour matrix comes from the 3FR header it - /// embeds, so the image is not developed with the "camera RGB ≈ sRGB" fallback. - #[test] - fn fff_takes_the_colour_matrix_from_the_embedded_3fr_header() { - let bytes = fff(Some(original_header(true)), false); - assert_eq!(probe(&bytes), Some(RawFormat::CfaTiff)); - let r = decode_file(&bytes).unwrap(); - assert_eq!(r.data, RawData::U16((0..48u16).map(|i| u16::from_be_bytes([2 * i as u8, 2 * i as u8 + 1])).collect())); - assert_eq!(r.cfa.as_ref().unwrap().name(), "RGGB"); - assert_eq!(matrix_row0(&r.color), Some([0.686, -0.196, -0.032])); - assert_eq!(r.color.as_shot_neutral, Some([0.4, 1.0, 0.8]), "the outer file's white balance"); - assert!(!crate::color::camera_transform_of(&r.color, lightcraft_color::D65).matrix_is_fallback); - // the import probe says the same - assert_eq!(matrix_row0(&probe_info(&bytes).unwrap().color), Some([0.686, -0.196, -0.032])); - } - - /// A matrix of the file's own wins; without one anywhere (no header, or a header without a matrix) the - /// file still decodes, with the fallback colour. - #[test] - fn own_matrix_wins_and_a_missing_one_is_not_an_error() { - let own = decode_file(&fff(Some(original_header(true)), true)).unwrap(); - assert_eq!(matrix_row0(&own.color), Some([1.0, 0.0, 0.0])); - for header in [None, Some(original_header(false)), Some(b"not a tiff".to_vec())] { - let r = decode_file(&fff(header, false)).unwrap(); - assert!(!crate::color::has_matrix(&r.color)); - } - } - - /// A truncated or damaged file never panics: an error, or a decode. - #[test] - fn damaged_files_do_not_panic() { - let bytes = fff(Some(original_header(true)), false); - for n in (0..bytes.len()).step_by(7) { - let _ = decode_file(&bytes[..n]); - let _ = probe_info(&bytes[..n]); - let _ = crate::embedded_preview(&bytes[..n]); - } - let mut header = original_header(true); - for i in (8..header.len()).step_by(3) { - header[i] ^= 0x5a; - match decode_file(&fff(Some(header.clone()), false)) { - Ok(_) | Err(RawError::Corrupt(_) | RawError::Tiff(_) | RawError::Unsupported(_) | RawError::Limit(_) | RawError::NotRaw) => {} - } - } - } - - /// `(width, height, pixels, has an Orientation tag)` of a wrapped preview. - fn wrapped(tiff: &[u8]) -> (u32, u32, Vec, bool) { - let t = Tiff::parse(tiff).unwrap(); - let ifd = &t.ifds[0]; - let info = ifd.image().unwrap(); - let chunks = info.chunks(tiff.len() as u64); - let pixels = chunks.iter().flat_map(|c| chunk_bytes(tiff, c).unwrap().to_vec()).collect(); - (info.width, info.height, pixels, ifd.contains(t::ORIENTATION)) - } - - /// No JPEG in the file: the 8-bit RGB IFD0 comes out as a baseline TIFF of the same pixels, without an - /// orientation of its own (the raw file's applies). - #[test] - fn rgb_ifd0_is_the_embedded_preview() { - let bytes = fff(Some(original_header(true)), false); - let preview = crate::embedded_preview(&bytes).expect("a preview"); - assert_eq!(wrapped(&preview), (4, 3, (0..36).collect(), false)); - assert_eq!(crate::embedded_preview_covering(&bytes, 2000), Some(preview)); - } - - /// The largest 8-bit RGB image wins; a bigger 16-bit one (the FFF's copy with a `TransferFunction`) is not - /// used, and nor is a planar or compressed one. - #[test] - fn only_8_bit_chunky_uncompressed_rgb_is_taken() { - let image = |w: u32, h: u32, bits: u16, planar: u16, compression: u16| { - let mut ifd = IfdBuilder::new(); - ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![1])); - ifd.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - ifd.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![bits; 3])); - ifd.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![3])); - ifd.set(t::PHOTOMETRIC, Value::Short(vec![2])); - ifd.set(t::COMPRESSION, Value::Short(vec![compression])); - ifd.set(t::PLANAR_CONFIGURATION, Value::Short(vec![planar])); - let n = (w * h * 3 * u32::from(bits / 8)) as usize; - ifd.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![vec![7; n]] }); - ifd - }; - let bytes = fff_with(None, false, vec![image(16, 12, 16, 1, 1), image(12, 9, 8, 2, 1), image(12, 9, 8, 1, 8)]); - assert_eq!(wrapped(&crate::embedded_preview(&bytes).unwrap()).0, 4, "IFD0's 4 x 3"); - let bytes = fff_with(None, false, vec![image(6, 6, 8, 1, 1)]); - assert_eq!(wrapped(&crate::embedded_preview(&bytes).unwrap()), (6, 6, vec![7; 108], false)); - } - - /// A preview strip cut short by a truncated file gives no preview, not a partial picture. - #[test] - fn short_preview_strip_gives_none() { - let mut ifd0 = rgb_ifd(); - ifd0.set_image(ImageData::Strips { rows_per_strip: 3, strips: vec![vec![1; 30]] }); - let tiff = TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap(); - assert_eq!(rgb_preview(&Tiff::parse(&tiff).unwrap(), &tiff), None); - } -} diff --git a/crates/raw/src/vendor/huffman.rs b/crates/raw/src/vendor/huffman.rs new file mode 100644 index 0000000000..56219ba5f3 --- /dev/null +++ b/crates/raw/src/vendor/huffman.rs @@ -0,0 +1,106 @@ +//! The table-driven Huffman decoder and MSB-first bit reader of the difference codings still decoded here +//! (Panasonic RW2, Sony ARW6): a code names a difference category, the category's additional bits follow as in +//! ITU-T T.81 F.1.2.1. `craft-raw` has the same decoder for the makers it reads (shortcut: a copy until RW2 and +//! ARW move there, then it goes). + +use crate::{RawError, Result}; + +/// A canonical-by-table Huffman decoder with a 12-bit lookup. +pub(crate) struct Huffman { + /// Indexed by the next 12 bits: (symbol, length); length 0 = invalid. + lut: Vec<(u8, u8)>, +} + +impl Huffman { + /// From `(left-aligned 12-bit code, length)` per symbol. + pub fn new(codes: &[(u16, u8)]) -> Result { + let mut lut = vec![(0u8, 0u8); 4096]; + for (sym, &(code, len)) in codes.iter().enumerate() { + if len == 0 { + continue; + } + if len > 12 || sym > 16 { + return Err(RawError::Unsupported(format!("PEF Huffman code of length {len}"))); + } + let first = (code >> (12 - len) << (12 - len)) as usize; + for e in &mut lut[first..first + (1 << (12 - len))] { + if e.1 == 0 { + *e = (sym as u8, len); + } + } + } + Ok(Huffman { lut }) + } +} + +/// MSB-first bit reader that yields zeros past the end. +pub(crate) struct Bits<'a> { + src: &'a [u8], + pos: usize, + acc: u64, + n: u32, +} + +impl<'a> Bits<'a> { + pub fn new(src: &'a [u8]) -> Self { + Bits { src, pos: 0, acc: 0, n: 0 } + } + #[inline] + fn fill(&mut self) { + while self.n <= 56 { + let b = self.src.get(self.pos).copied().unwrap_or(0); + self.pos += 1; + self.acc |= (b as u64) << (56 - self.n); + self.n += 8; + } + } + #[inline] + pub fn peek(&mut self, k: u32) -> u32 { + if self.n < k { + self.fill(); + } + (self.acc >> (64 - k)) as u32 + } + #[inline] + pub fn skip(&mut self, k: u32) { + self.acc <<= k; + self.n -= k; + } + #[inline] + pub fn get(&mut self, k: u32) -> u32 { + if k == 0 { + return 0; + } + let v = self.peek(k); + self.skip(k); + v + } + /// Bits handed out so far (may exceed the source length: zeros are read past its end). + pub fn consumed_bits(&self) -> usize { + self.pos * 8 - self.n as usize + } + /// Whether more bits were handed out than the source holds (the zeros read past its end are lookahead padding, + /// not data; using them would fabricate samples). + pub fn overrun(&self) -> bool { + self.consumed_bits() > self.src.len() * 8 + } +} + +/// Decode one difference: Huffman category then T.81 additional bits. +#[inline] +pub(crate) fn diff(bits: &mut Bits, h: &Huffman) -> Option { + let (sym, len) = h.lut[bits.peek(12) as usize]; + if len == 0 { + return None; + } + bits.skip(len as u32); + let s = sym as u32; + if s == 0 { + return Some(0); + } + if s > 16 { + return None; + } + let v = bits.get(s) as i32; + Some(if v < 1 << (s - 1) { v - (1 << s) + 1 } else { v }) +} diff --git a/crates/raw/src/vendor/kodak.rs b/crates/raw/src/vendor/kodak.rs deleted file mode 100644 index 5d77108ffc..0000000000 --- a/crates/raw/src/vendor/kodak.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! Kodak DCS520C raw TIFF: the CFA sub-IFD holds one lossless JPEG (SOF3) stream of two components. -//! -//! Sources: TIFF 6.0 (container; `GrayResponseCurve` `0x123`; the CFA tags `CFARepeatPatternDim` and `CFAPattern`), -//! ITU T.81 (lossless JPEG, process SOF3), LightCraft's own decoder in [`crate::ljpeg`], the file's `KodakIFD` -//! (`0x8290`, a plain IFD with absolute offsets) and our own black-box analysis of the one CC0 sample from -//! raw.pixls.us (2573, DCS520C; every number below was measured on it): -//! -//! - The raw IFD is `Compression` 7, photometric 32803 (CFA), 12 bits, one strip, `ImageWidth` x `ImageLength` = -//! 1736 x 1160. Its stream is a 12-bit lossless JPEG of 868 x 1160 with two components; the decoder's interleaved -//! output (component 0, component 1, per pixel) is the mosaic row by row, so component 0 is the even columns and -//! component 1 the odd ones. The stream ends exactly at the strip's end. Recognised structurally: a Kodak make -//! and a stream whose width times its component count is the IFD's `ImageWidth`. -//! - `CFAPattern` bytes `01 00 02 01` (anchored at the first sample) are GRBG; the decoded colours follow the IFD0 -//! RGB thumbnail (156 x 104) with that layout. -//! - The samples span only 191..=622 because they are stored companded: IFD `GrayResponseCurve` (`0x123`, 4096 -//! entries) is a non-decreasing table that is the identity below 216 and expands the rest to 12-bit linear -//! values (623 distinct values, stored 622 gives 4095 and so does every higher code). Applying it makes the -//! frame linear with 12-bit white 4095. -//! - No masked border: all four edges are picture. Black differs per colour: the darkest 0.01% of each CFA -//! position's samples sit at 220 (G), 223 (R) and 197 (B) after the table (scene shadows end at the sensor's -//! black), so black is measured per position from the samples. -//! - White balance: five rational triples in the `KodakIFD` look like neutral sensor values (`0x848`, `0x849`, -//! `0x84a`, `0x84c`, `0x84d`). Against the thumbnail's neutral pixels (370 pixels with R, G and B within 6 of -//! each other) the raw G/R is 0.94 and G/B 1.96; `0x848` (1913, 1834, 921) gives 0.96 and 1.99, the others -//! 0.77..1.25 and 2.08..2.96, so its green over red and over blue are the gains. -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg}; -use craft_tiff::image::chunk_bytes; -use craft_tiff::{Ifd, Tiff, tags as t}; -use lightcraft_geom::Orientation; - -/// The vendor IFD pointer (`KodakIFD`). -const KODAK_IFD: u16 = 0x8290; -/// Rational triple (red, green, blue) of neutral sensor values, see the module notes. -const NEUTRAL: u16 = 0x848; -/// TIFF `GrayResponseCurve`. -const RESPONSE_CURVE: u16 = 0x123; -/// Entries of the response curve: one per 12-bit code. -const CURVE_LEN: usize = 4096; - -/// The raw sub-IFD of a Kodak DCS TIFF with this layout: the CFA image whose single lossless JPEG stream has two -/// components, `ImageWidth / 2` columns and `ImageLength` rows, 12 bits. -pub(crate) fn raw_ifd<'a>(tiff: &'a Tiff, bytes: &[u8]) -> Option<&'a Ifd> { - let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str())?; - if !make.to_ascii_uppercase().starts_with("KODAK") { - return None; - } - tiff.all_ifds().into_iter().find(|i| { - if i.u16(t::PHOTOMETRIC) != Some(t::photometric::CFA) || i.u16(t::COMPRESSION) != Some(t::compression::JPEG) { - return false; - } - let Ok(info) = i.image() else { return false }; - let chunks = info.chunks(bytes.len() as u64); - let [chunk] = chunks.as_slice() else { return false }; - let Some(src) = chunk_bytes(bytes, chunk) else { return false }; - matches!( - ljpeg::frame_info(src), - Ok((w, h, 2, 12)) if w.checked_mul(2) == Some(info.width as usize) && h == info.height as usize - ) && i.u64s(RESPONSE_CURVE).is_some_and(|c| c.len() == CURVE_LEN) - }) -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let tiff = Tiff::parse(bytes)?; - let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("Kodak TIFF without IFDs".into()))?; - let raw = raw_ifd(&tiff, bytes).ok_or_else(|| RawError::Unsupported("Kodak raw image not found".into()))?; - let info = raw.image()?; - let (w, h) = (info.width as usize, info.height as usize); - let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { - (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, - _ => return Err(RawError::Unsupported("Kodak raw without a 2x2 CFAPattern".into())), - }; - let curve: Vec = raw - .u64s(RESPONSE_CURVE) - .filter(|c| c.len() == CURVE_LEN && c.windows(2).all(|p| p[0] <= p[1]) && c.iter().all(|&v| v < CURVE_LEN as u64)) - .ok_or_else(|| RawError::Unsupported("Kodak raw without a usable response curve".into()))? - .into_iter() - .map(|v| v as u16) - .collect(); - let (black, data) = if mode == Mode::Full { - let chunks = info.chunks(bytes.len() as u64); - let src = chunks.first().and_then(|c| chunk_bytes(bytes, c)).ok_or_else(|| RawError::Corrupt("Kodak strip outside file".into()))?; - let f = ljpeg::decode(src, n)?; - if f.components != 2 || f.width * 2 != w || f.height != h || f.data.len() != n { - return Err(RawError::Corrupt("Kodak lossless JPEG does not match the image size".into())); - } - let mut d = f.data; - for v in &mut d { - *v = curve.get(usize::from(*v)).copied().unwrap_or(CURVE_LEN as u16 - 1); - } - (measured_black(&d, w), RawData::U16(d)) - } else { - (BlackLevel::uniform(0.0), RawData::U16(Vec::new())) - }; - let wb = kodak_ifd(bytes, &tiff, ifd0) - .and_then(|k| k.f64s(NEUTRAL)) - .filter(|v| v.len() == 3 && v.iter().all(|&x| x > 0.0)) - .map(|v| [(v[1] / v[0]) as f32, 1.0, (v[1] / v[2]) as f32]); - let mut metadata = lightcraft_meta::from_tiff(&tiff); - metadata.width = Some(w as u32); - metadata.height = Some(h as u32); - let img = RawImage { - format: RawFormat::KodakDcs, - width: w, - height: h, - cpp: 1, - data, - cfa: Some(cfa), - bits: 12, - black, - white: vec![(CURVE_LEN - 1) as f32], - active_area: Rect::new(0, 0, w, h), - crop: Rect::new(0, 0, w, h), - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: ColorData::default(), - wb_multipliers: wb, - linearized: false, - pixel_aspect: 1.0, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -/// The vendor IFD (`KodakIFD`): a plain IFD with absolute value offsets. -fn kodak_ifd(bytes: &[u8], tiff: &Tiff, ifd0: &Ifd) -> Option { - let off = u64::from(ifd0.u32(KODAK_IFD)?); - let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; - craft_tiff::parse_ifd_at(bytes, off, tiff.order, 0, false, &opts).ok().map(|(i, _)| i) -} - -/// Black level per CFA position (the mosaic's first sample is position 0): the value below which only 0.01% of that -/// position's samples fall, see the module notes. Uniform 0 for an empty frame. -fn measured_black(d: &[u16], w: usize) -> BlackLevel { - let mut hist = vec![[0u32; CURVE_LEN]; 4]; - let mut count = [0u64; 4]; - for (y, row) in d.chunks(w.max(1)).enumerate() { - for (x, &v) in row.iter().enumerate() { - let p = (y & 1) * 2 + (x & 1); - hist[p][usize::from(v).min(CURVE_LEN - 1)] += 1; - count[p] += 1; - } - } - if count.contains(&0) { - return BlackLevel::uniform(0.0); - } - let values = (0..4) - .map(|p| { - let limit = count[p].div_ceil(10_000); - let mut seen = 0u64; - let level = hist[p] - .iter() - .position(|&c| { - seen += u64::from(c); - seen >= limit - }) - .unwrap_or(0); - level as f32 - }) - .collect(); - BlackLevel { repeat_rows: 2, repeat_cols: 2, values, ..Default::default() } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{decode, probe, probe_info}; - use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; - - const W: usize = 16; - const H: usize = 8; - - /// A response curve: the identity below 100, then steeper, saturating at 4095. - fn curve() -> Vec { - (0..CURVE_LEN as u32).map(|i| if i < 100 { i as u16 } else { (100 + (i - 100) * 7).min(4095) as u16 }).collect() - } - - /// Stored mosaic: values 60..=300, in the range the curve expands. - fn stored() -> Vec { - (0..W * H).map(|i| 60 + ((i * 37) % 241) as u16).collect() - } - - /// A big-endian IFD of `(tag, SRATIONAL triple)` entries at `at` in the file. - fn kodak_ifd_bytes(at: usize, tag: u16, v: [i32; 3]) -> Vec { - let mut b = vec![0, 1]; - b.extend(tag.to_be_bytes()); - b.extend(10u16.to_be_bytes()); - b.extend(3u32.to_be_bytes()); - b.extend(((at + 2 + 12 + 4) as u32).to_be_bytes()); - b.extend([0; 4]); - for x in v { - b.extend(x.to_be_bytes()); - b.extend(1i32.to_be_bytes()); - } - b - } - - fn file(make: &str, stream: Vec, width: u32, with_curve: bool, wb: Option<[i32; 3]>) -> Vec { - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Short(vec![width as u16])); - raw.set(t::IMAGE_LENGTH, Value::Short(vec![H as u16])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); - raw.set(t::COMPRESSION, Value::Short(vec![7])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![32803])); - raw.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])); - if with_curve { - raw.set(RESPONSE_CURVE, Value::Short(curve())); - } - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![1, 0, 2, 1])); - raw.set_image(ImageData::Strips { rows_per_strip: H as u32, strips: vec![stream] }); - let build = |ptr: u32| { - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii(make.into())); - ifd0.set(t::MODEL, Value::Ascii("DCS520C".into())); - if wb.is_some() { - ifd0.set(KODAK_IFD, Value::Long(vec![ptr])); - } - ifd0.add_sub_ifd(raw.clone()); - TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap() - }; - let mut bytes = build(0); - if let Some(v) = wb { - let at = bytes.len().next_multiple_of(2); - bytes = build(at as u32); - bytes.resize(at, 0); - bytes.extend(kodak_ifd_bytes(at, NEUTRAL, v)); - } - bytes - } - - fn stream() -> Vec { - ljpeg::encode(&stored(), W / 2, H, 2, 12, 1, 0) - } - - /// Known answer: two interleaved components are the even and odd columns, the response curve linearises them, - /// the layout is GRBG, white balance comes from the vendor IFD, black is measured per CFA position. - #[test] - fn two_component_stream_decodes_through_the_response_curve() { - let bytes = file("Kodak", stream(), W as u32, true, Some([1900, 1800, 900])); - assert_eq!(probe(&bytes), Some(RawFormat::KodakDcs)); - let r = decode(&bytes).unwrap(); - assert_eq!((r.format, r.width, r.height, r.bits), (RawFormat::KodakDcs, W, H, 12)); - let want: Vec = stored().iter().map(|&v| curve()[usize::from(v)]).collect(); - assert_eq!(r.data, RawData::U16(want.clone())); - assert_eq!(r.cfa.as_ref().unwrap().name(), "GRBG"); - assert_eq!(r.white, vec![4095.0]); - assert_eq!(r.wb_multipliers, Some([1800.0 / 1900.0, 1.0, 2.0])); - // 0.01% of 32 samples is the smallest one of each position - let w = &want; - let min = |y0: usize, x0: usize| (y0..H).step_by(2).flat_map(|y| (x0..W).step_by(2).map(move |x| w[y * W + x])).min().unwrap() as f32; - assert_eq!(r.black.values, vec![min(0, 0), min(0, 1), min(1, 0), min(1, 1)]); - let i = probe_info(&bytes).unwrap(); - assert_eq!((i.format, i.width, i.height, i.wb_multipliers), (RawFormat::KodakDcs, W, H, r.wb_multipliers)); - } - - /// Without the vendor IFD there is no white balance; the layout is recognised from the structure alone, so - /// another make, one component, a stream of another width or a missing curve change nothing for other files. - #[test] - fn only_this_layout_is_claimed() { - assert_eq!(decode(&file("Kodak", stream(), W as u32, true, None)).unwrap().wb_multipliers, None); - assert_ne!(probe(&file("Canon", stream(), W as u32, true, None)), Some(RawFormat::KodakDcs)); - assert_ne!(probe(&file("Kodak", stream(), W as u32 + 2, true, None)), Some(RawFormat::KodakDcs)); - assert_ne!(probe(&file("Kodak", stream(), W as u32, false, None)), Some(RawFormat::KodakDcs)); - let one = ljpeg::encode(&stored()[..W * H / 2], W, H / 2, 1, 12, 1, 0); - assert_ne!(probe(&file("Kodak", one, W as u32, true, None)), Some(RawFormat::KodakDcs)); - } - - /// Hostile input: truncated streams and tables report errors instead of panicking. - #[test] - fn damaged_files_are_errors() { - let s = stream(); - for cut in [s.len() / 2, 40, 0] { - let bytes = file("Kodak", s[..cut].to_vec(), W as u32, true, Some([1, 1, 1])); - if probe(&bytes) == Some(RawFormat::KodakDcs) { - assert!(decode(&bytes).is_err() || cut == s.len()); - } - } - let bytes = file("Kodak", s, W as u32, true, Some([0, 5, 0])); - assert_eq!(decode(&bytes).unwrap().wb_multipliers, None); - } -} diff --git a/crates/raw/src/vendor/mef.rs b/crates/raw/src/vendor/mef.rs deleted file mode 100644 index 8755e9e06c..0000000000 --- a/crates/raw/src/vendor/mef.rs +++ /dev/null @@ -1,279 +0,0 @@ -//! Mamiya MEF (ZD): a big-endian TIFF whose first `SubIFDs` child is an uncompressed 12-bit packed CFA image. -//! -//! Sources: TIFF 6.0 (container, MSB-first bit packing, `CFAPattern`) and our own black-box analysis of the one CC0 -//! MEF sample on raw.pixls.us (Mamiya ZD); every number below was measured on it. -//! -//! - IFD0 is a 144 x 192 RGB thumbnail with three `SubIFDs`: the raw (4016 x 5344, 12 bits, `Compression` 1, -//! photometric CFA, one strip of exactly 1.5 bytes per pixel, two samples in three bytes most significant bits -//! first, as TIFF packs them), a 992 x 1328 and a 240 x 320 RGB preview, all uncompressed and 8 bits. No JPEG. -//! - `CFAPattern` `00 01 01 02`: RGGB; the two green sites agree (means 254 and 256 against 235 and 165). -//! - No masked border and no stored black level: the darkest 0.01% of each site's samples sit at 3..6 and the -//! minimum is 0, so black is 0. White: the saturation plateau, else 4095. -//! - The 992 x 1328 preview shows a 3968 x 5312 window (4 sensor pixels per preview pixel) that starts at column 24, -//! row 12: that offset gives the best correlation of the preview's luminance with the box-filtered mosaic (0.965, -//! against 0.83 for the full frame). It is the default crop. -//! - Orientation is the raw IFD's own `Orientation` (6 on the sample, a portrait shot). -//! - No white-balance tag was found (the maker note holds an ICC-like profile), so the as-shot gains are measured -//! from that preview's neutral pixels ([`crate::wb_estimate`]). -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; -use craft_tiff::image::chunk_bytes; -use craft_tiff::{Ifd, Tiff, tags as t}; -use lightcraft_geom::Orientation; - -/// Where the preview's window starts in the sensor frame, and how many sensor pixels one preview pixel covers. -const CROP_ORIGIN: (usize, usize) = (24, 12); -const PREVIEW_SCALE: usize = 4; - -fn is_mamiya(tiff: &Tiff) -> bool { - tiff.find(t::MAKE).and_then(|e| e.value.as_str()).is_some_and(|m| m.to_ascii_uppercase().starts_with("MAMIYA")) -} - -/// The raw IFD of a Mamiya MEF: CFA, 12 bits, uncompressed, one strip of 1.5 bytes per pixel. -pub(crate) fn raw_ifd(tiff: &Tiff, len: usize) -> Option<&Ifd> { - if !is_mamiya(tiff) { - return None; - } - tiff.all_ifds().into_iter().find(|i| { - let Ok(info) = i.image() else { return false }; - let (w, h) = (info.width as u64, info.height as u64); - i.u16(t::PHOTOMETRIC) == Some(t::photometric::CFA) - && i.u16(t::COMPRESSION).unwrap_or(1) == 1 - && i.u16(t::BITS_PER_SAMPLE) == Some(12) - && w > 0 - && w % 2 == 0 - && matches!(info.chunks(len as u64).as_slice(), [c] if Some(c.len) == (w * 3 / 2).checked_mul(h)) - }) -} - -/// The largest uncompressed 8-bit RGB sub-IFD (the preview): its pixels, width and height. -fn rgb_preview<'a>(tiff: &Tiff, bytes: &'a [u8]) -> Option<(&'a [u8], usize, usize)> { - tiff.all_ifds() - .into_iter() - .filter_map(|i| { - let info = i.image().ok()?; - let ok = i.u16(t::PHOTOMETRIC) == Some(2) - && i.u16(t::COMPRESSION).unwrap_or(1) == 1 - && i.u16(t::SAMPLES_PER_PIXEL) == Some(3) - && i.u64s(t::BITS_PER_SAMPLE).is_some_and(|b| b.iter().all(|&v| v == 8)); - let (w, h) = (info.width as usize, info.height as usize); - let chunks = info.chunks(bytes.len() as u64); - let [c] = chunks.as_slice() else { return None }; - let px = chunk_bytes(bytes, c)?; - (ok && px.len() >= w.checked_mul(h)?.checked_mul(3)?).then_some((px, w, h)) - }) - .max_by_key(|(_, w, h)| w * h) -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let tiff = Tiff::parse(bytes)?; - let raw = raw_ifd(&tiff, bytes.len()).ok_or_else(|| RawError::Unsupported("Mef raw image not found".into()))?; - let info = raw.image()?; - let (w, h) = (info.width as usize, info.height as usize); - let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { - (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, - _ => return Err(RawError::Unsupported("Mef raw without a 2x2 CFAPattern".into())), - }; - let preview = rgb_preview(&tiff, bytes); - let crop = match preview { - Some((_, pw, ph)) => { - let (cw, ch) = (pw.saturating_mul(PREVIEW_SCALE), ph.saturating_mul(PREVIEW_SCALE)); - if cw > 0 && ch > 0 && CROP_ORIGIN.0 + cw <= w && CROP_ORIGIN.1 + ch <= h { - Rect::new(CROP_ORIGIN.0, CROP_ORIGIN.1, cw, ch) - } else { - Rect::new(0, 0, w, h) - } - } - None => Rect::new(0, 0, w, h), - }; - // the white balance is measured from the samples, so the header probe reads them too - // the strip length is the tag value, so a short file must fail before the sample buffer is sized from it - let chunks = info.chunks(bytes.len() as u64); - let src = chunks - .first() - .and_then(|c| chunk_bytes(bytes, c).filter(|s| s.len() as u64 == c.len)) - .ok_or_else(|| RawError::Corrupt("Mef strip outside file".into()))?; - // 12-bit MSB packing takes 3 bytes per 2 samples; a strip that cannot hold the declared - // samples is a truncated file, not a picture — unpacking it would run past the real bytes - // through every output sample (a short strip asks for the whole allocation and more). - let need = n.div_ceil(2).saturating_mul(3); - if src.len() < need { - return Err(RawError::Corrupt(format!("a Mef strip of {} bytes cannot hold the declared {n} samples", src.len()))); - } - let mut d = vec![0u16; n]; - crate::unpack::unpack_msb(src, 12, &mut d); - let white = super::white_from_data(&d, 12); - let black = BlackLevel::uniform(0.0); - let frame = crate::wb_estimate::Frame { data: &d, width: w, crop, cfa: &cfa, black: &black, white }; - let wb = match preview { - Some((px, pw, ph)) => crate::wb_estimate::as_shot_rgb(px, pw, ph, &frame), - None => crate::wb_estimate::as_shot(bytes, &frame), - }; - let data = if mode == Mode::Full { RawData::U16(d) } else { RawData::U16(Vec::new()) }; - let mut metadata = lightcraft_meta::from_tiff(&tiff); - metadata.width = Some(crop.width as u32); - metadata.height = Some(crop.height as u32); - let orientation = raw.u16(t::ORIENTATION).or_else(|| tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION))).unwrap_or(1); - let img = RawImage { - format: RawFormat::Mef, - width: w, - height: h, - cpp: 1, - data, - cfa: Some(cfa), - bits: 12, - black, - white: vec![white], - active_area: Rect::new(0, 0, w, h), - crop, - orientation: Orientation::from_exif(orientation), - color: ColorData::default(), - wb_multipliers: wb, - linearized: false, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - pixel_aspect: 1.0, - }; - img.validate_for(mode)?; - Ok(img) -} - -#[cfg(test)] -mod tests { - use super::*; - use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; - - fn pack(px: &[u16]) -> Vec { - px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect() - } - - fn sample(w: u32, h: u32, px: &[u16]) -> Vec { - sample_strip(w, h, &pack(px)) - } - - fn sample_strip(w: u32, h: u32, strip: &[u8]) -> Vec { - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); - raw.set(t::COMPRESSION, Value::Short(vec![1])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA])); - raw.set(t::ORIENTATION, Value::Short(vec![6])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![strip.to_vec()] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("Mamiya-OP Co.,Ltd.".into())); - ifd0.set(t::MODEL, Value::Ascii("MAMIYA ZD".into())); - ifd0.add_sub_ifd(raw); - TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap() - } - - /// A strip that cannot hold the declared samples is a truncated file, refused as corrupt - /// instead of unpacked: `unpack_msb` would otherwise run `n` samples through the few real - /// bytes, filling the rest from nothing. - #[test] - fn a_strip_too_short_for_the_declared_samples_is_refused() { - let px: Vec = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); - let f = sample(16, 6, &px); - assert!(crate::decode(&f).is_ok()); - // A truncated file shaped like a real one: IFD tables first, strip last — only its first - // 20 packed bytes remain, while the IFD still declares the full 1.5 B/sample length. The - // probe accepts the file on the declared length; before the byte gate below, `unpack_msb` - // ran the dimension-sized allocation through those 20 bytes, filling it from nothing. - let u32be = |b: &[u8], a: usize| u32::from_be_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]); - let full = pack(&px); - let at = f.windows(full.len()).position(|w| w == full).expect("strip bytes in the file"); - let after_strip = at + full.len(); - let moved = after_strip - (at + 20); - let mut g = f[..8].to_vec(); - g.extend(std::iter::repeat_n(0u8, at + 20 - 8)); - g.extend_from_slice(&f[after_strip..]); - // repoint the first-IFD pointer and ifd0's MAKE / MODEL / SubIfds offsets (the tables now - // sit `moved` earlier); the raw sub-IFD's strip offset and byte count are patched below - let poke = |b: &mut [u8], a: usize| { - let v = u32::from_be_bytes([b[a], b[a + 1], b[a + 2], b[a + 3]]); - if v as usize >= after_strip { - b[a..a + 4].copy_from_slice(&(v - moved as u32).to_be_bytes()); - } - }; - let ifd0_at = u32be(&g, 4) as usize - moved; - g[4..8].copy_from_slice(&(ifd0_at as u32).to_be_bytes()); - let n = u16::from_be_bytes([g[ifd0_at], g[ifd0_at + 1]]) as usize; - for i in 0..n { - poke(&mut g, ifd0_at + 2 + i * 12 + 8); - } - // the raw sub-IFD: entries follow its count; tag 273 (StripOffsets) is the seventh, held - // inline — repoint it at the strip's new home, and append the truncated strip for real - let sub_at = u32be(&g, ifd0_at + 2 + 2 * 12 + 8) as usize; - let e_offsets = sub_at + 2 + 6 * 12 + 8; - let strip_at = g.len() as u32; - g[e_offsets..e_offsets + 4].copy_from_slice(&strip_at.to_be_bytes()); - g.extend_from_slice(&full[..20]); - assert_eq!(crate::probe(&g), Some(RawFormat::Mef)); - let r = crate::decode(&g); - assert!(matches!(r, Err(RawError::Corrupt(_))), "{r:?}"); - } - - #[test] - fn decodes_packed_12_bit() { - let px: Vec = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect(); - let f = sample(16, 6, &px); - assert_eq!(crate::probe(&f), Some(RawFormat::Mef)); - let r = crate::decode(&f).unwrap(); - assert_eq!(r.data, RawData::U16(px)); - assert_eq!(r.orientation, Orientation::from_exif(6)); - assert_eq!(r.crop, Rect::new(0, 0, 16, 6)); - assert_eq!(crate::probe_info(&f).unwrap(), r.info()); - } - - #[test] - fn malformed_files_never_panic() { - let px: Vec = (0..16 * 6).map(|i| (i * 7 % 4096) as u16).collect(); - let f = sample(16, 6, &px); - for n in 0..f.len() { - let _ = crate::decode(&f[..n]); - } - for i in 0..f.len() { - for v in [0u8, 0xff] { - let mut g = f.clone(); - g[i] = v; - let _ = crate::decode(&g); - let _ = crate::probe_info(&g); - } - } - } - - /// Rewrite the raw IFD's height, rows per strip and strip length in place (the strip data stays as written). - fn declare(f: &mut [u8], rows: u32, strip_len: u32) { - let tiff = Tiff::parse(f).unwrap(); - let raw = &tiff.ifds[0].sub_ifds[0]; - let spots: Vec<_> = [(t::IMAGE_LENGTH, rows), (t::ROWS_PER_STRIP, rows), (t::STRIP_BYTE_COUNTS, strip_len)] - .into_iter() - .map(|(tag, v)| { - let e = raw.entries.iter().find(|e| e.tag == tag).unwrap(); - (e.offset as usize, matches!(e.value, Value::Short(_)), v) - }) - .collect(); - for (at, short, v) in spots { - if short { - f[at..at + 2].copy_from_slice(&u16::try_from(v).unwrap().to_be_bytes()); - } else { - f[at..at + 4].copy_from_slice(&v.to_be_bytes()); - } - } - } - - #[test] - fn a_strip_longer_than_the_file_is_an_error() { - // #2119: the declared strip length matched the size, so a few bytes of data were decoded as a full frame - let px: Vec = (0..40).map(|i| (i * 13 % 4096) as u16).collect(); - let mut f = sample(20, 2, &px); - declare(&mut f, 2000, 30 * 2000); - assert_eq!(crate::probe(&f), Some(RawFormat::Mef)); - assert!(matches!(crate::probe_info(&f), Err(RawError::Corrupt(_)))); - assert!(matches!(crate::decode(&f), Err(RawError::Corrupt(_)))); - } -} diff --git a/crates/raw/src/vendor/mrw.rs b/crates/raw/src/vendor/mrw.rs deleted file mode 100644 index a59de3d3ef..0000000000 --- a/crates/raw/src/vendor/mrw.rs +++ /dev/null @@ -1,232 +0,0 @@ -//! Minolta / Konica Minolta MRW: a block container (see [`lightcraft_meta::mrw`]) around a 12-bit Bayer mosaic. -//! -//! Sources: the public prose description of the MRW layout (Dalibor Jelínek's MRW notes) and our own black-box -//! analysis of the eight CC0 MRW samples on raw.pixls.us (DiMAGE 7, 7Hi, A1, A2, A200, Dynax / Maxxum / ALPHA-7 -//! Digital); every number below was measured on them. -//! -//! - `PRD` (24 bytes, big-endian): 8 ASCII version bytes, sensor rows and columns (`u16` each), image rows and -//! columns, data size (12 or 16 bits per stored sample), pixel size (12), storage method (`0x59` = 12-bit -//! packed: two samples in three bytes, most significant bits first; `0x52` = one 12-bit sample per big-endian -//! 16-bit word), two unknown bytes and the Bayer layout as a `u16` (`1` = RGGB, `4` = GBRG). The sensor data -//! starts after the header and is exactly sensor rows x columns samples in every sample. -//! - The sensor frame is 8 columns and 6 to 8 rows larger than the image size, but every edge holds picture (no -//! masked border), so the whole frame is the active area and the image size is the default crop. -//! - Black is 0: the darkest samples are 0 in every packed file and 13..34 in the unpacked ones, with no offset -//! left to subtract. White is the saturation plateau where the frame has one (3964 on the A1, 3965 on a clipped -//! DiMAGE 7, 4020 on the A200, 4076 on the 7D), else 4095. -//! - The layout code was checked against the embedded preview: with `1` the two greens are the equal (0,1) and -//! (1,0) positions; in the A200 (`4`) the greens are (0,0) and (1,1), and only red at (1,0) reproduces the -//! preview's red-dominated colour. -//! - `WBG` (12 bytes): four scale bytes, then four big-endian `u16` coefficients in the order of the Bayer cell -//! read row by row (RGGB: R G G B, GBRG: G B R G). Red over green and blue over green are the as-shot gains; -//! applied to the raw channel means they reproduce the preview's colour balance within the colour matrix's -//! reach on all eight samples. -//! - `TTW` is a TIFF with IFD0 (orientation), Exif and the maker note; the preview JPEG sits in it with its first -//! byte overwritten (see `preview::scan_for_jpeg`). -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, unpack}; -use craft_tiff::{Tiff, tags as t}; -use lightcraft_geom::Orientation; - -/// Storage method codes in `PRD`. -const PACKED_12: u8 = 0x59; -const WORDS_16: u8 = 0x52; - -/// What `PRD` says about the sensor data. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Prd { - sensor: (usize, usize), - image: (usize, usize), - packed: bool, - cfa: &'static str, -} - -fn be16(b: &[u8], at: usize) -> Option { - b.get(at..at + 2).map(|s| u16::from_be_bytes([s[0], s[1]])) -} - -fn prd(b: &[u8]) -> Result { - let u = |at| be16(b, at).map(usize::from).ok_or_else(|| RawError::Corrupt("Mrw PRD block too short".into())); - let (sh, sw, ih, iw) = (u(8)?, u(10)?, u(12)?, u(14)?); - let (size, storage) = (b.get(16).copied(), b.get(18).copied()); - let packed = match (size, storage) { - (Some(12), Some(PACKED_12)) => true, - (Some(16), Some(WORDS_16)) => false, - _ => return Err(RawError::Unsupported(format!("Mrw storage {size:?}/{storage:?} is not decoded yet"))), - }; - let cfa = match u(22)? { - 1 => "RGGB", - 4 => "GBRG", - other => return Err(RawError::Unsupported(format!("Mrw Bayer layout {other}"))), - }; - if sw == 0 || sh == 0 || (packed && sw % 2 != 0) { - return Err(RawError::Corrupt("Mrw sensor size".into())); - } - Ok(Prd { sensor: (sw, sh), image: (iw.min(sw), ih.min(sh)), packed, cfa }) -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let m = lightcraft_meta::mrw::parse(bytes).ok_or_else(|| RawError::Corrupt("Mrw block header".into()))?; - let p = prd(m.block(b"PRD").ok_or_else(|| RawError::Unsupported("Mrw file without a PRD block".into()))?)?; - let (w, h) = p.sensor; - let n = w.checked_mul(h).filter(|n| *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; - let need = if p.packed { n / 2 * 3 } else { n * 2 }; - let src = bytes - .get(m.data_offset..) - .and_then(|s| s.get(..need)) - .ok_or_else(|| RawError::Corrupt(format!("Mrw sensor data truncated (needs {need} bytes)")))?; - let cfa = Cfa::bayer_static(p.cfa); - let (data, white) = if mode == Mode::Full { - let mut d = vec![0u16; n]; - if p.packed { - unpack::unpack_msb(src, 12, &mut d); - } else { - unpack::read_u16s(src, craft_tiff::ByteOrder::Big, &mut d); - for v in &mut d { - *v = (*v).min(4095); - } - } - let white = super::white_from_data(&d, 12); - (RawData::U16(d), white) - } else { - (RawData::U16(Vec::new()), 4095.0) - }; - let wb = m.block(b"WBG").and_then(|b| wb_from(b, &cfa)); - let tiff = m.block(b"TTW").and_then(|b| Tiff::parse(b).ok()); - let mut metadata = tiff.as_ref().map(lightcraft_meta::from_tiff).unwrap_or_default(); - metadata.width = Some(p.image.0 as u32); - metadata.height = Some(p.image.1 as u32); - let orientation = tiff.as_ref().and_then(|t| t.ifds.first()).and_then(|i| i.u16(t::ORIENTATION)).unwrap_or(1); - let img = RawImage { - format: RawFormat::Mrw, - width: w, - height: h, - cpp: 1, - data, - cfa: Some(cfa), - bits: 12, - black: BlackLevel::uniform(0.0), - white: vec![white], - active_area: Rect::new(0, 0, w, h), - crop: Rect::new(0, 0, p.image.0, p.image.1), - orientation: Orientation::from_exif(orientation), - color: ColorData::default(), - wb_multipliers: wb, - linearized: false, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - pixel_aspect: 1.0, - }; - img.validate_for(mode)?; - Ok(img) -} - -/// As-shot gains from `WBG`: four coefficients in Bayer-cell order after four scale bytes. -fn wb_from(b: &[u8], cfa: &Cfa) -> Option<[f32; 3]> { - let mut sum = [0f32; 3]; - let mut count = [0f32; 3]; - for (i, &c) in cfa.pattern.iter().enumerate().take(4) { - let v = f32::from(be16(b, 4 + 2 * i)?); - let k = usize::from(c).min(2); - sum[k] += v; - count[k] += 1.0; - } - if count.contains(&0.0) || sum.iter().any(|&s| s <= 0.0) { - return None; - } - let mean = |k: usize| sum[k] / count[k]; - Some([mean(0) / mean(1), 1.0, mean(2) / mean(1)]) -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - - /// A synthetic MRW: `PRD` with the given storage, `WBG`, a `TTW` TIFF with orientation 6, then the samples. - pub(crate) fn sample(w: u16, h: u16, packed: bool, layout: u16, wbg: [u16; 4], samples: &[u16]) -> Vec { - let mut prd = b"21810002".to_vec(); - for v in [h, w, h - 2, w - 2] { - prd.extend_from_slice(&v.to_be_bytes()); - } - prd.extend_from_slice(&[if packed { 12 } else { 16 }, 12, if packed { PACKED_12 } else { WORDS_16 }, 0, 0, 0]); - prd.extend_from_slice(&layout.to_be_bytes()); - let mut wb = vec![2u8; 4]; - for v in wbg { - wb.extend_from_slice(&v.to_be_bytes()); - } - let mut ifd0 = craft_tiff::IfdBuilder::new(); - ifd0.set(t::MAKE, craft_tiff::Value::Ascii("Minolta Co., Ltd.".into())); - ifd0.set(t::ORIENTATION, craft_tiff::Value::Short(vec![6])); - let ttw = craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap(); - let mut body = Vec::new(); - for (name, data) in [(b"PRD", &prd), (b"WBG", &wb), (b"TTW", &ttw)] { - body.push(0); - body.extend_from_slice(name); - body.extend_from_slice(&(data.len() as u32).to_be_bytes()); - body.extend_from_slice(data); - } - let mut f = b"\0MRM".to_vec(); - f.extend_from_slice(&(body.len() as u32).to_be_bytes()); - f.extend_from_slice(&body); - if packed { - for p in samples.chunks(2) { - let (a, b) = (p[0], p.get(1).copied().unwrap_or(0)); - f.extend_from_slice(&[(a >> 4) as u8, ((a & 15) << 4) as u8 | (b >> 8) as u8, b as u8]); - } - } else { - for v in samples { - f.extend_from_slice(&v.to_be_bytes()); - } - } - f - } - - #[test] - fn decodes_packed_and_word_storage() { - let (w, h) = (8u16, 6u16); - let px: Vec = (0..48).map(|i| (i * 85) as u16 % 4096).collect(); - for packed in [true, false] { - let f = sample(w, h, packed, 1, [408, 256, 256, 450], &px); - assert_eq!(crate::probe(&f), Some(RawFormat::Mrw)); - let r = crate::decode(&f).unwrap(); - assert_eq!((r.width, r.height, r.bits), (8, 6, 12)); - assert_eq!(r.data, RawData::U16(px.clone()), "packed {packed}"); - assert_eq!(r.cfa.as_ref().map(Cfa::name).as_deref(), Some("RGGB")); - assert_eq!(r.crop, Rect::new(0, 0, 6, 4)); - assert_eq!(r.orientation, Orientation::from_exif(6)); - assert_eq!(r.metadata.make.as_deref(), Some("Minolta Co., Ltd.")); - let wb = r.wb_multipliers.unwrap(); - assert!((wb[0] - 408.0 / 256.0).abs() < 1e-6 && (wb[2] - 450.0 / 256.0).abs() < 1e-6, "{wb:?}"); - assert_eq!(crate::probe_info(&f).unwrap(), r.info()); - } - } - - /// GBRG (layout 4): the coefficients follow the cell, so the second is blue and the third red. - #[test] - fn gbrg_white_balance_follows_the_cell() { - let f = sample(4, 4, true, 4, [255, 416, 480, 255], &[100; 16]); - let r = crate::decode(&f).unwrap(); - assert_eq!(r.cfa.as_ref().map(Cfa::name).as_deref(), Some("GBRG")); - let wb = r.wb_multipliers.unwrap(); - assert!((wb[0] - 480.0 / 255.0).abs() < 1e-6 && (wb[2] - 416.0 / 255.0).abs() < 1e-6, "{wb:?}"); - } - - /// Truncations and corrupted header bytes give errors, never panics. - #[test] - fn malformed_files_never_panic() { - let f = sample(8, 6, true, 1, [408, 256, 256, 450], &[7; 48]); - for n in 0..f.len() { - assert!(crate::decode(&f[..n]).is_err() || n == f.len()); - } - for i in 8..f.len().min(120) { - for v in [0u8, 0xff, 0x52, 0x59] { - let mut g = f.clone(); - g[i] = v; - let _ = crate::decode(&g); - let _ = crate::probe_info(&g); - } - } - assert!(matches!(crate::decode(b"\0MRM\0\x01\0\0"), Err(RawError::Corrupt(_)))); - assert!(matches!(crate::decode(b"\0MRM\0\0\0\0"), Err(RawError::Unsupported(w)) if w.contains("Mrw"))); - } -} diff --git a/crates/raw/src/vendor/nef.rs b/crates/raw/src/vendor/nef.rs deleted file mode 100644 index 916acae60f..0000000000 --- a/crates/raw/src/vendor/nef.rs +++ /dev/null @@ -1,1429 +0,0 @@ -//! Nikon NEF / NRW — uncompressed and Huffman-compressed (lossless, lossy) variants. -//! -//! Sources: TIFF 6.0 (the raw image is a standard CFA SubIFD), Laurent Clévy's NEF structure notes (prose: IFD -//! layout, SubIFDs, maker note header) and the ExifTool Nikon tag-name documentation (`0x000c` WB_RBLevels, -//! `0x003d` BlackLevel, `0x0096` NEFLinearizationTable). The Huffman-compressed data (compression 34713) is decoded -//! by [`super::nefc`], which documents its clean-room sources; "lossy after split" files are decoded when their strip follows the -//! rule documented there; files it can't decode are reported as [`RawError::Unsupported`] and their embedded previews still work. So are High Efficiency NEFs -//! (HE / HE★, Z 8, Z 9, Z 6III, Z f): they keep compression 34713 but carry a wavelet codestream that starts with -//! the JPEG XS markers SOC + CAP (ISO/IEC 21122-1, `FF10 FF50`) and have no `0x0096` table (issue #193). -//! Strips labelled 34713 without a `0x0096` -//! linearization table are packed uncompressed data in several measured layouts ([`PackedLayout`]) or, when the strip -//! is exactly three bytes per pixel, Nikon small raw ([`small_raw`]); the D1X's genuinely Huffman-coded strip stays -//! refused. - -use super::{nefc, white_from_data}; -use crate::tiffraw::{Packing, check_image, read_image}; -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; -use craft_tiff::image::ImageInfo; -use craft_tiff::tags::{self as t, photometric}; -use craft_tiff::{ByteOrder, Ifd, Tiff, makernote}; -use lightcraft_geom::Orientation; - -const WB_RB_LEVELS: u16 = 0x000c; -const BLACK_LEVEL: u16 = 0x003d; -const LINEARIZATION_TABLE: u16 = 0x0096; -const CROP_AREA: u16 = 0x0045; -/// JPEG XS start of codestream (SOC, `FF10`) followed by its mandatory capabilities marker (CAP, `FF50`). -const JPEG_XS_START: [u8; 4] = [0xff, 0x10, 0xff, 0x50]; -/// Why a High Efficiency NEF shows its embedded preview: the UI shows the part before " (". -pub(crate) const HIGH_EFFICIENCY: &str = - "Nikon High Efficiency NEF (HE / HE★, a JPEG XS-based codec with no public specification; shoot RAW Lossless compressed to edit the raw data)"; -/// Maker note `0x0014`, the "NRW" data block of Coolpix raws: `"NRW "` + a 4-character version, then fields. In -/// version `0104` the `u32` at byte `0x20` is the black level in sample units (200 in the four 12-bit files here -/// that have 200 as their darkest samples, 0 in the one whose samples reach 0). -const NRW_DATA: u16 = 0x0014; -const NRW_BLACK_AT: usize = 0x20; - -/// The NRW data block, when the maker note has one. -fn nrw_data(mn: Option<&makernote::MakerNote>) -> Option<(&[u8], ByteOrder)> { - let m = mn?; - m.ifd.bytes(NRW_DATA).filter(|b| b.starts_with(b"NRW ")).map(|b| (b, m.order)) -} - -/// Black level from the NRW data block, bounded to a quarter of the sample range so an unknown version's field -/// can't turn into a large offset. -fn nrw_black(mn: Option<&makernote::MakerNote>, bits: u32) -> Option { - let (b, order) = nrw_data(mn)?; - let v = order.u32(b.get(NRW_BLACK_AT..NRW_BLACK_AT + 4)?.try_into().ok()?); - (u64::from(v) < (1u64 << bits.min(16)) / 4).then_some(v as f32) -} - -/// Nikon CropArea is `[left, top, width, height]` in sensor pixels (maker-note tag documentation). -/// Keep the active area/CFA origin unchanged: the default crop is applied after demosaicing. -fn default_crop(mn: Option<&makernote::MakerNote>, w: usize, h: usize) -> Rect { - let fallback = Rect::new(0, 0, w, h); - let Some(values) = mn.and_then(|m| m.ifd.u64s(CROP_AREA)) else { return fallback }; - let [x, y, width, height] = values.as_slice() else { return fallback }; - if *width == 0 || *height == 0 || x.checked_add(*width).is_none_or(|v| v > w as u64) || y.checked_add(*height).is_none_or(|v| v > h as u64) { - return fallback; - } - Rect::new(*x as usize, *y as usize, *width as usize, *height as usize) -} - -/// A body that records no CropArea, measured on its own files: the image area inside the sensor data (where the -/// camera's full-size JPEG sits when the two are aligned) and, when the data's own top would be wrong, the level -/// where its channels clip. -struct MeasuredBody { - model: &'static str, - /// Sensor data size and sample depth of the measured files. - size: (usize, usize), - bits: u32, - /// Image area in sensor pixels: x, y, width, height. - crop: (usize, usize, usize, usize), - white: Option, -} - -/// * **NIKON D4** (148 uncompressed 14-bit NEFs from one body, 2023–2026, ISO 100–10000): the data is 4992 × 3292, -/// with 2 columns of optical black left of the image and 42 right of it, then 8 empty ones; the camera's -/// 4928 × 3280 JPEG sits at (8, 6). Without this area the optical black shows as purple stripes on both sides. -/// Green saturates at 15546–15672 while red and blue run on to 15687–16383, so the data's own top (~16300) leaves -/// clipped highlights magenta; one level of 15520 for every channel turns them white and keeps the white balance. -/// * **NIKON D7100** (issue #1248; 14-bit NEFs from the public zjqc/photographing-art repository, with their -/// Lightroom Classic exports): the data holds picture, not masked lines, beyond the camera's frame. In full frame -/// it is 6036 × 4020 and the camera's JPEG is 6000 × 4000; in the 1.3x crop mode it is 4812 × 3212 and the JPEG -/// 4800 × 3200. Fitting renders of the full data to Lightroom's exports (feature matches, homography) puts -/// Lightroom's frame, the camera JPEG's size, at (18, 10) and (6, 6): within 0.5 px mean on DSC_1316, DSC_2763 -/// and DSC_1486. Without it, renders are larger than Lightroom's and its crops land up to 6 px off (18 px in -/// full frame). -/// * **NIKON D90** (550 compressed 12-bit NEFs from one body, 10 measured): the data is 4352 × 2868 and its last 42 -/// columns (from 4310) are filler at a flat ~254 whatever the exposure, above the dark image samples (black 0), so -/// the masked-column test keeps them and they develop as a pink band on the right. The camera's 4288 × 2848 JPEG -/// sits at (10, 10). Green saturates at 3840–3851 while red and blue run on to 4095; one level of 3830 keeps -/// clipped highlights white. -/// * **NIKON D7000** and **NIKON D5100** (and the Coolpix A, the same readout): the data is 4992 × 3280, the picture its -/// first 4948 columns, then 36 masked ones at one level (~600, with a black level of 0) and 8 of 0. The masked -/// columns sit above the dark-column trim's threshold, so without this area they show as a coloured bar on the right -/// edge (the top in portrait; issue #976). The camera's 4928 × 3264 JPEG sits at (8, 8): in the D5100's 3 CC0 -/// samples, and in the D7000's one clean one, with the D5100 and Coolpix A as siblings (see below). -/// * **The other bodies** below keep masked or dark lines inside the whole data (a survey of every Nikon raw on raw.pixls.us): -/// each crop is its camera JPEG's frame as `cargo xtask raw-frame` measures it on raw.pixls.us CC0 samples (the -/// D200, D3200 and Nikon 1 V1 also on other publicly posted sample files), with at least 3 clean -/// files agreeing: of the model (bit depths pooled: both read out the same area), or, with at least -/// one of its own, together with models of the same readout (data and JPEG size) that agree on the same frame -/// (*siblings*). The D4's 12-bit mode reads out the 14-bit area measured above; the Df, the same readout, agrees on -/// (8, 6) in 6 files. Bodies whose crop holds only picture beyond the camera frame have no entry (no change). -const MEASURED_BODIES: &[MeasuredBody] = &[ - MeasuredBody { model: "NIKON D4", size: (4992, 3292), bits: 14, crop: (8, 6, 4928, 3280), white: Some(15520.0) }, - MeasuredBody { model: "NIKON D4", size: (4992, 3292), bits: 12, crop: (8, 6, 4928, 3280), white: None }, - MeasuredBody { model: "NIKON D7100", size: (6036, 4020), bits: 14, crop: (18, 10, 6000, 4000), white: None }, - MeasuredBody { model: "NIKON D7100", size: (4812, 3212), bits: 14, crop: (6, 6, 4800, 3200), white: None }, - MeasuredBody { model: "NIKON D90", size: (4352, 2868), bits: 12, crop: (10, 10, 4288, 2848), white: Some(3830.0) }, - MeasuredBody { model: "NIKON D7000", size: (4992, 3280), bits: 14, crop: (8, 8, 4928, 3264), white: None }, - MeasuredBody { model: "NIKON D7000", size: (4992, 3280), bits: 12, crop: (8, 8, 4928, 3264), white: None }, - MeasuredBody { model: "NIKON D5100", size: (4992, 3280), bits: 14, crop: (8, 8, 4928, 3264), white: None }, - // siblings: D7000 (4), D5100 (3); masked: right 36 - MeasuredBody { model: "COOLPIX A", size: (4992, 3280), bits: 14, crop: (8, 8, 4928, 3264), white: None }, - // 6 files each; masked: left 2, right 2 - MeasuredBody { model: "NIKON D3", size: (4288, 2844), bits: 12, crop: (15, 6, 4256, 2832), white: None }, - MeasuredBody { model: "NIKON D3", size: (4288, 2844), bits: 14, crop: (15, 6, 4256, 2832), white: None }, - MeasuredBody { model: "NIKON D3S", size: (4288, 2844), bits: 12, crop: (15, 6, 4256, 2832), white: None }, - MeasuredBody { model: "NIKON D3S", size: (4288, 2844), bits: 14, crop: (15, 6, 4256, 2832), white: None }, - MeasuredBody { model: "NIKON D700", size: (4288, 2844), bits: 12, crop: (15, 6, 4256, 2832), white: None }, - MeasuredBody { model: "NIKON D700", size: (4288, 2844), bits: 14, crop: (15, 6, 4256, 2832), white: None }, - // 6 and 4 files; masked: right up to 32 - MeasuredBody { model: "NIKON D300", size: (4352, 2868), bits: 12, crop: (15, 10, 4288, 2848), white: None }, - MeasuredBody { model: "NIKON D300", size: (4352, 2868), bits: 14, crop: (15, 10, 4288, 2848), white: None }, - MeasuredBody { model: "NIKON D300S", size: (4352, 2868), bits: 12, crop: (15, 10, 4288, 2848), white: None }, - MeasuredBody { model: "NIKON D300S", size: (4352, 2868), bits: 14, crop: (15, 10, 4288, 2848), white: None }, - // D2X (1) and D2Xs (2) as siblings; dark: right 1 - MeasuredBody { model: "NIKON D2Xs", size: (4320, 2868), bits: 12, crop: (16, 10, 4288, 2848), white: None }, - // D3000, D40X, D60, D80: one file each, siblings; masked: right 4, bottom 3 - MeasuredBody { model: "NIKON D3000", size: (3904, 2616), bits: 12, crop: (14, 9, 3872, 2592), white: None }, - MeasuredBody { model: "NIKON D40X", size: (3904, 2616), bits: 12, crop: (14, 9, 3872, 2592), white: None }, - MeasuredBody { model: "NIKON D60", size: (3904, 2616), bits: 12, crop: (14, 9, 3872, 2592), white: None }, - MeasuredBody { model: "NIKON D80", size: (3904, 2616), bits: 12, crop: (14, 9, 3872, 2592), white: None }, - // 3 files; masked: left 1, right 3 (the D80's data size, framed elsewhere) - MeasuredBody { model: "NIKON D200", size: (3904, 2616), bits: 12, crop: (16, 12, 3872, 2592), white: None }, - // 22 files; masked: right 46 - MeasuredBody { model: "NIKON D3200", size: (6080, 4012), bits: 12, crop: (8, 6, 6016, 4000), white: None }, - // 8 clean of 19, the rest ~0.3 px between pixels on the same frame; dark: bottom 2 - MeasuredBody { model: "NIKON 1 V1", size: (3904, 2606), bits: 12, crop: (12, 6, 3872, 2592), white: None }, - // Best guesses, short of the evidence rule; every frame below keeps the masked lines out by several pixels. - // D3100: 3 of 4 clean files at (24, 6), the 4th at (22, 7); masked: left 6, right 22 - MeasuredBody { model: "NIKON D3100", size: (4672, 3084), bits: 12, crop: (24, 6, 4608, 3072), white: None }, - // D5000: 4 of 5 clean files at (11, 10), the 5th at (11, 12); the D90's sensor, whose own files also align at - // x = 11; masked: right 42 (the same filler as the D90's) - MeasuredBody { model: "NIKON D5000", size: (4352, 2868), bits: 12, crop: (11, 10, 4288, 2848), white: None }, - // D40: 2 of 2 clean files at (16, 9); masked: right 1. The D50 / D70 / D70s share its data size but not its frame - MeasuredBody { model: "NIKON D40", size: (3040, 2014), bits: 12, crop: (16, 9, 3008, 2000), white: None }, - // D50, D70, D70s (one readout): one clean D50 and one clean D70 file at (15, 7); the D70s's 2 files align - // between pixels next to it, at (15.4, 6.9) and (15.6, 6.4); masked: right 1 - MeasuredBody { model: "NIKON D50", size: (3040, 2014), bits: 12, crop: (15, 7, 3008, 2000), white: None }, - MeasuredBody { model: "NIKON D70", size: (3040, 2014), bits: 12, crop: (15, 7, 3008, 2000), white: None }, - MeasuredBody { model: "NIKON D70s", size: (3040, 2014), bits: 12, crop: (15, 7, 3008, 2000), white: None }, - // 3 files; dark: bottom 4 - MeasuredBody { model: "NIKON D4S", size: (4936, 3288), bits: 12, crop: (4, 4, 4928, 3280), white: None }, - MeasuredBody { model: "NIKON D4S", size: (4936, 3288), bits: 14, crop: (4, 4, 4928, 3280), white: None }, - // 4 files; dark: bottom up to 4 - MeasuredBody { model: "NIKON D5600", size: (6016, 4016), bits: 12, crop: (8, 8, 6000, 4000), white: None }, - MeasuredBody { model: "NIKON D5600", size: (6016, 4016), bits: 14, crop: (8, 8, 6000, 4000), white: None }, - // 4 files each; masked: right 8 - MeasuredBody { model: "NIKON D600", size: (6080, 4028), bits: 12, crop: (8, 6, 6016, 4016), white: None }, - MeasuredBody { model: "NIKON D600", size: (6080, 4028), bits: 14, crop: (8, 6, 6016, 4016), white: None }, - MeasuredBody { model: "NIKON D610", size: (6080, 4028), bits: 12, crop: (8, 6, 6016, 4016), white: None }, - MeasuredBody { model: "NIKON D610", size: (6080, 4028), bits: 14, crop: (8, 6, 6016, 4016), white: None }, - // D800: 6 files; D800E: 2, with the D800 as sibling; masked: right 14 (issue #914, the top in portrait) - MeasuredBody { model: "NIKON D800", size: (7424, 4924), bits: 12, crop: (8, 6, 7360, 4912), white: None }, - MeasuredBody { model: "NIKON D800", size: (7424, 4924), bits: 14, crop: (8, 6, 7360, 4912), white: None }, - MeasuredBody { model: "NIKON D800E", size: (7424, 4924), bits: 14, crop: (8, 6, 7360, 4912), white: None }, - // 3 files; dark: bottom 1 - MeasuredBody { model: "NIKON D810", size: (7380, 4928), bits: 12, crop: (12, 8, 7360, 4912), white: None }, - MeasuredBody { model: "NIKON D810", size: (7380, 4928), bits: 14, crop: (12, 8, 7360, 4912), white: None }, - // 6 files; masked: left 2, right 42 (the D4's readout) - MeasuredBody { model: "NIKON Df", size: (4992, 3292), bits: 12, crop: (8, 6, 4928, 3280), white: None }, - MeasuredBody { model: "NIKON Df", size: (4992, 3292), bits: 14, crop: (8, 6, 4928, 3280), white: None }, -]; - -fn measured_body(model: &str, w: usize, h: usize, bits: u32) -> Option<&'static MeasuredBody> { - MEASURED_BODIES.iter().find(|b| b.model == model.trim() && b.size == (w, h) && b.bits == bits) -} - -/// Pixel height over width from the raw IFD's resolution tags: the D1X and D1H write 600 x 300 per inch for a -/// 4028 x 1324 frame, rows twice as tall as the columns are wide. Only ratios from 1.5 to 4 count (a frame -/// squashed 3:1 or 2:1), the rest is rounding or a stray tag. -pub(crate) fn pixel_aspect_of(raw: &Ifd) -> f32 { - match (raw.f64(t::X_RESOLUTION), raw.f64(t::Y_RESOLUTION)) { - (Some(x), Some(y)) if x > 0.0 && y > 0.0 && (1.5..=4.0).contains(&(x / y)) => (x / y).round() as f32, - _ => 1.0, - } -} - -fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> { - tiff.all_ifds() - .into_iter() - .filter(|i| i.u16(t::PHOTOMETRIC) == Some(photometric::CFA)) - .max_by_key(|i| i.u64(t::IMAGE_WIDTH).unwrap_or(0).saturating_mul(i.u64(t::IMAGE_LENGTH).unwrap_or(0))) -} - -/// Rows the masked-column test reads, from the top of the frame. The header probe ([`Mode::Header`]) decodes -/// only these (a compressed strip is one sequential Huffman stream, so it can stop here; an uncompressed one reads -/// just its first strips), and the full decode judges the active width from the same rows, so -/// [`crate::probe_info`] equals [`RawImage::info`] of the decoded image (issue #708). On every corpus NEF the -/// answer is the same for 8 to 512 rows as for the whole frame: the masked columns decode to 0 (compressed) or -/// ~19 (uncompressed) while live columns sit at the black level (~150 at 12 bit, ~600 at 14 bit) or above. -pub(crate) const MASK_ROWS: usize = 128; - -/// Width without the optically masked columns some bodies append on the right (the D5100 and D7000 write 8, with -/// no maker-note tag that says so, in compressed and uncompressed files alike): trailing columns (at most 64) whose -/// mean over the first [`MASK_ROWS`] rows of `d` is below 1% of the nominal white level and a tenth of the image -/// interior. Kept even for CFA phase. -pub(crate) fn trailing_masked_columns(d: &[u16], w: usize, bits: u32) -> usize { - let rows = d.len().checked_div(w).unwrap_or(0).min(MASK_ROWS); - if w < 128 || rows == 0 { - return w; - } - let col_mean = |x: usize| (0..rows).map(|y| d.get(y * w + x).copied().unwrap_or(0) as f64).sum::() / rows as f64; - let interior = (w / 4..w * 3 / 4).step_by(w / 64).map(col_mean).sum::() / 32.0; - let white = ((1u32 << bits.clamp(1, 16)) - 1) as f64; - let dark = (white * 0.01).min(interior * 0.1); - let mut aw = w; - while aw > w - 64 && col_mean(aw - 1) < dark { - aw -= 1; - } - aw & !1 -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let tiff = Tiff::parse(bytes)?; - let ifd0 = &tiff.ifds[0]; - let raw = raw_ifd(&tiff).ok_or_else(|| RawError::Unsupported("NEF without a CFA image IFD".into()))?; - let info = raw.image()?; - let (w, h) = (info.width as usize, info.height as usize); - let bits = info.bits() as u32; - let make = ifd0.string(t::MAKE).unwrap_or_default(); - let mn = - tiff.exif().and_then(|e| e.get(t::MAKER_NOTE)).and_then(|e| makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)); - if let Some(strip) = small_raw_strip(&info, bytes.len(), mn.as_ref()) { - return small_raw(bytes, &tiff, &info, strip, mode); - } - // the header probe reads only the rows the masked-column test needs - let rows = match mode { - Mode::Full => h, - Mode::Header => h.min(MASK_ROWS), - }; - let data = if info.compression == t::compression::NIKON { - compressed(bytes, &info, mn.as_ref(), rows)? - } else { - uncompressed(bytes, &info, tiff.order, mn.as_ref(), rows)? - }; - let RawData::U16(ref samples) = data else { return Err(RawError::Unsupported("float NEF".into())) }; - - // Maker note 0x003d is in 14-bit units whatever the sample depth: 12-bit files from the D750, D780, D850, - // D7500 and Z 50 store 600 / 1008 / 400 / 400 / 1008 while their darkest samples are 150 / ~252 / 99 / 99 / ~250 - // (our measurements on CC0 raw.pixls.us samples; the same bodies' 14-bit files match the tag as is). - let black_scale = if bits == 12 { 0.25 } else { 1.0 }; - let black = match mn.as_ref().and_then(|m| m.ifd.f64s(BLACK_LEVEL)).as_deref() { - Some([a, b, c, d]) if [a, b, c, d].iter().all(|v| **v < 16384.0) => BlackLevel { - repeat_rows: 2, - repeat_cols: 2, - values: [a, b, c, d].iter().map(|v| (**v * black_scale) as f32).collect(), - ..Default::default() - }, - _ => BlackLevel::uniform(nrw_black(mn.as_ref(), bits).unwrap_or_else(|| be16_black(&info, bytes.len() as u64, mn.as_ref(), samples))), - }; - let wb = mn - .as_ref() - .and_then(|m| m.ifd.f64s(WB_RB_LEVELS)) - .filter(|v| v.len() >= 2 && v[0] > 0.1 && v[1] > 0.1 && v[0] < 10.0 && v[1] < 10.0) - .map(|v| [v[0] as f32, 1.0, v[1] as f32]); - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { - (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, - _ => Cfa::bayer_static("RGGB"), - }; - let model = ifd0.string(t::MODEL).unwrap_or_default(); - let body = measured_body(&model, w, h, bits); - let active_w = trailing_masked_columns(samples, w, bits); - // the white level is measured from the whole image (or known for a measured body); the probe (no samples in its - // result) takes the nominal one - let white = match (body.and_then(|b| b.white), mode) { - (Some(white), _) => white, - (None, Mode::Full) => white_from_data(samples, bits), - (None, Mode::Header) => ((1u32 << bits.clamp(1, 16)) - 1) as f32, - }; - let crop = match body { - Some(&MeasuredBody { crop: (x, y, cw, ch), .. }) if x + cw <= active_w && y + ch <= h => Rect::new(x, y, cw, ch), - _ => default_crop(mn.as_ref(), active_w, h), - }; - let pixel_aspect = pixel_aspect_of(raw); - let mut metadata = lightcraft_meta::from_tiff(&tiff); - metadata.width = Some(crop.width as u32); - metadata.height = Some(crate::stretched_height(crop.height, pixel_aspect) as u32); - let img = RawImage { - format: RawFormat::Nef, - width: w, - height: h, - cpp: 1, - data: match mode { - Mode::Full => data, - Mode::Header => RawData::U16(Vec::new()), - }, - cfa: Some(cfa), - bits, - black, - white: vec![white], - active_area: Rect::new(0, 0, active_w, h), - crop, - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: ColorData { kelvin_presets: crate::kelvin_builtin::find(Some(&make), &model), ..Default::default() }, - wb_multipliers: wb, - linearized: false, - pixel_aspect, - // Nikon's in-file distortion correction, about the optical centre (which follows the sensor shift) - opcodes: OpcodeLists { - list3: super::nef_lens::distortion(&model, raw, Rect::new(0, 0, active_w, h), crop).into_iter().collect(), - ..Default::default() - }, - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -/// Uncompressed strips: 16-bit words or 12-bit packed, told apart by the strip size. Packed 12-bit data is an MSB-first -/// byte stream, except in files with an NRW data block (Coolpix), where it is MSB-first inside little-endian 32-bit -/// words (the rows are whole words). Reads the first `rows` rows (the strips that hold them) of the `info.height`. -fn uncompressed(bytes: &[u8], info: &ImageInfo, order: ByteOrder, mn: Option<&makernote::MakerNote>, rows: usize) -> Result { - let (w, h) = (info.width as usize, info.height as usize); - let bits = info.bits() as u32; - let row_samples = w * info.samples_per_pixel as usize; - let chunks = info.chunks(bytes.len() as u64); - let rows_in_first = chunks.first().map(|c| c.height as usize).unwrap_or(h).max(1); - let bytes_per_row = chunks.first().map(|c| c.len as usize / rows_in_first).unwrap_or(0); - let packing = if bytes_per_row >= row_samples * 2 { - Packing::Word16 - } else if bits == 12 && bytes_per_row * 8 >= row_samples * 12 && bytes_per_row * 8 < row_samples * 13 { - if nrw_data(mn).is_some() && bytes_per_row.is_multiple_of(4) { Packing::Words32Msb } else { Packing::Msb } - } else if info.compression == 1 && bits != 8 && bits != 16 { - return Err(RawError::Unsupported(format!("NEF uncompressed packing ({bytes_per_row} bytes per {row_samples}-sample row)"))); - } else { - Packing::Msb - }; - if rows >= h { - return read_image(bytes, info, order, packing); - } - // the whole image's limits apply either way; then only the strips holding the first `rows` rows are unpacked - check_image(bytes, info)?; - let top = ImageInfo { height: rows as u32, ..info.clone() }; - read_image(bytes, &top, order, packing) -} - -/// Packed layouts of strips that are labelled compression 34713 but have no linearization table (maker note -/// `0x0096`): they hold plain packed samples, not Huffman codes. The layouts were measured from CC0 raw.pixls.us -/// files by a clean-room black-box analysis (strip byte-count identity, same-colour smoothness and correlation with -/// the camera JPEG against at least eight alternative packings). Every layout is a single strip with -/// `stride = StripByteCounts / height`, selected only when `stride * height` equals the strip size exactly. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum PackedLayout { - /// LSB-first bit stream of `bits` per sample (12: 3 bytes per 2 samples, 14: 7 bytes per 4), rows byte aligned. - /// 12-bit rows are `3w/2` bytes (older bodies) or padded to 16 bytes (Z 6, D6); 14-bit rows are `7w/4` bytes - /// padded to 16 bytes. - Lsb { stride: usize }, - /// D100: 16-byte chunks of fifteen data bytes holding ten MSB-first 12-bit samples, plus one zero pad byte. The - /// rows carry more samples than the IFD width (3040 against 3034); the extra columns are not image. - Chunked16 { stride: usize }, - /// Coolpix NRW: one big-endian 16-bit word per pixel, rows `2w` bytes with no header or padding; the 12-bit sample - /// is the upper 12 bits of the word (the low nibble is zero, rarely 8). - Be16, -} - -fn packed_layout(w: usize, h: usize, bits: u32, strip: u64) -> Option { - if w == 0 || h == 0 || !matches!(bits, 12 | 14) { - return None; - } - let strip = usize::try_from(strip).ok()?; - if !strip.is_multiple_of(h) { - return None; - } - let stride = strip / h; - let tight = w.checked_mul(bits as usize)?.div_ceil(8); - let tight = if bits == 12 && w.is_multiple_of(2) || bits == 14 && w.is_multiple_of(4) { tight } else { return None }; - let padded = tight.checked_next_multiple_of(16)?; - let lsb_ok = match bits { - 12 => stride == tight || stride == padded, - _ => stride == padded, - }; - if lsb_ok { - return Some(PackedLayout::Lsb { stride }); - } - None -} - -fn d100_layout(w: usize, h: usize, bits: u32, strip: u64) -> Option { - let strip = usize::try_from(strip).ok()?; - if bits != 12 || h == 0 || !strip.is_multiple_of(h) { - return None; - } - let stride = strip / h; - let per_row = stride / 16 * 10; - (stride.is_multiple_of(16) && per_row >= w && per_row < w.checked_add(10)?).then_some(PackedLayout::Chunked16 { stride }) -} - -/// 12-bit strips of exactly `2 * w * h` bytes: big-endian 16-bit words (Coolpix P330, P7700, P7800 NRW, found by a -/// clean-room black-box analysis of the CC0 files). Tried after the other layouts, whose strides (`1.5w` to -/// `1.5w + 15`, or ten samples per 16 bytes) only reach `2w` for rows narrower than 40 samples, so it can't take a -/// strip they handle. -fn be16_layout(w: usize, h: usize, bits: u32, strip: u64) -> Option { - let want = w.checked_mul(h)?.checked_mul(2)?; - (bits == 12 && w > 0 && h > 0 && usize::try_from(strip).ok()? == want).then_some(PackedLayout::Be16) -} - -/// Black level of the big-endian 16-bit layout, which carries neither `0x003d` nor an NRW block and has no masked -/// pixels (the borders of the frame are image). The darkest samples of the three measured bodies are 214 (P330), -/// 217 (P7700) and 201 (P7800, the only one with a dark enough frame: its per-channel 1st percentile is 209 / 225 / -/// 223), and the other 12-bit Coolpix NRWs state 200 in their NRW block; so 200, never above the darkest sample. -const BE16_BLACK: f32 = 200.0; - -fn be16_black(info: &ImageInfo, file_len: u64, mn: Option<&makernote::MakerNote>, samples: &[u16]) -> f32 { - let has_table = mn.is_some_and(|m| m.ifd.bytes(LINEARIZATION_TABLE).is_some()); - let single = matches!(info.chunks(file_len).as_slice(), [c] if be16_layout(info.width as usize, info.height as usize, info.bits() as u32, c.len).is_some()); - if info.compression != t::compression::NIKON || has_table || info.samples_per_pixel != 1 || !single { - return 0.0; - } - let darkest = samples.iter().copied().min().unwrap_or(0); - BE16_BLACK.min(f32::from(darkest)) -} - -/// Unpack a [`PackedLayout`] strip into `w * h` samples. Short input leaves the missing samples zero. -fn unpack_packed(src: &[u8], w: usize, h: usize, bits: u32, layout: PackedLayout) -> Vec { - use rayon::prelude::*; - let mut out = vec![0u16; w * h]; - let stride = match layout { - PackedLayout::Lsb { stride } | PackedLayout::Chunked16 { stride } => stride, - PackedLayout::Be16 => w.saturating_mul(2), - }; - out.par_chunks_mut(w).enumerate().for_each(|(y, row)| { - let Some(line) = src.get(y * stride..) else { return }; - let line = &line[..stride.min(line.len())]; - match layout { - PackedLayout::Lsb { .. } => crate::unpack::unpack_lsb(line, bits, row), - PackedLayout::Be16 => { - let (words, _) = line.as_chunks::<2>(); - for (dst, word) in row.iter_mut().zip(words) { - *dst = u16::from_be_bytes(*word) >> 4; - } - } - PackedLayout::Chunked16 { .. } => { - let mut samples = vec![0u16; line.len() / 16 * 10]; - for (i, dst) in samples.chunks_mut(10).enumerate() { - if let Some(chunk) = line.get(i * 16..i * 16 + 15) { - crate::unpack::unpack_msb(chunk, 12, dst); - } - } - let n = row.len().min(samples.len()); - row[..n].copy_from_slice(&samples[..n]); - } - } - }); - out -} - -/// Nikon Huffman-compressed strip (see [`super::nefc`]); the decode table is maker note `0x0096`. Without a table the -/// strip may be packed uncompressed data (see [`PackedLayout`]). -fn compressed(bytes: &[u8], info: &ImageInfo, mn: Option<&makernote::MakerNote>, rows: usize) -> Result { - let starts_with = |magic: &[u8]| { - let start = info.chunks(bytes.len() as u64).first().and_then(|c| usize::try_from(c.offset).ok()); - start.and_then(|o| bytes.get(o..o.checked_add(magic.len())?)) == Some(magic) - }; - if starts_with(&JPEG_XS_START) { - return Err(RawError::Unsupported(HIGH_EFFICIENCY.into())); - } - let Some(table) = mn.and_then(|m| Some((m.ifd.bytes(LINEARIZATION_TABLE)?, m.order))) else { - return packed(bytes, info, rows); - }; - if info.samples_per_pixel != 1 { - return Err(RawError::Unsupported(format!("Nikon compressed NEF with {} samples per pixel", info.samples_per_pixel))); - } - let bits = info.bits() as u32; - let table = nefc::parse_table(table.0, table.1, bits)?; - // one strip in every sample; several would be contiguous parts of the same bit stream - let chunks = info.chunks(bytes.len() as u64); - let (Some(first), Some(last)) = (chunks.first(), chunks.last()) else { return Err(RawError::Corrupt("NEF: no image data".into())) }; - let end = last.offset.saturating_add(last.len).min(bytes.len() as u64); - let src = usize::try_from(first.offset).ok().zip(usize::try_from(end).ok()).and_then(|(a, b)| bytes.get(a..b)); - let src = src.ok_or_else(|| RawError::Corrupt("NEF: image data outside the file".into()))?; - Ok(RawData::U16(nefc::decode_rows(src, info.width as usize, info.height as usize, rows, bits, &table)?)) -} - -/// A table-less "compressed" strip: packed samples when the strip size matches a measured layout exactly. -fn packed(bytes: &[u8], info: &ImageInfo, rows: usize) -> Result { - let (w, h) = (info.width as usize, info.height as usize); - let bits = info.bits() as u32; - let chunks = info.chunks(bytes.len() as u64); - let layout = match chunks.as_slice() { - [c] if info.samples_per_pixel == 1 => { - packed_layout(w, h, bits, c.len).or_else(|| d100_layout(w, h, bits, c.len)).or_else(|| be16_layout(w, h, bits, c.len)) - } - _ => None, - }; - let (Some(layout), [c]) = (layout, chunks.as_slice()) else { - return Err(RawError::Unsupported("Nikon compressed NEF without a linearization table (maker note 0x96)".into())); - }; - let src = craft_tiff::image::chunk_bytes(bytes, c) - .filter(|src| u64::try_from(src.len()).ok() == Some(c.len)) - .ok_or_else(|| RawError::Corrupt("NEF: incomplete image strip".into()))?; - if (w as u64).saturating_mul(h as u64) > crate::MAX_SAMPLES as u64 { - return Err(RawError::Limit("image too large")); - } - Ok(RawData::U16(unpack_packed(src, w, rows.min(h), bits, layout))) -} - -/// Nikon small raw (sRAW), measured clean-room from the CC0 raw.pixls.us D810 (2036) and D4S (2227) samples. The raw SubIFD is labelled compression 34713, -/// 12 bits, one CFA sample per pixel, but it carries no linearization table (maker note `0x0096`) and its single strip -/// is exactly `3 * width * height` bytes. It holds a YCbCr 4:2:2 image of the IFD size, not a CFA mosaic (the CFA -/// tags are dummies): -/// -/// - the strip is an LSB-first 12-bit stream (`s0 = b0 | (b1 & 0x0f) << 8`, `s1 = b1 >> 4 | b2 << 4`), a row is `3 * width` -/// bytes with no padding, i.e. `2 * width` samples; -/// - the samples come in groups of four, `[Y_left, Y_right, Cb, Cr]`, for the pixel pair `(2k, 2k + 1)`: chroma is -/// halved horizontally and not vertically; -/// - luma is linear and already black-subtracted (the darkest samples are near 0) and never uses the top two bits -/// (maxima 873 and 1004 of 4095), so the white level is 1023; chroma is centred on 2048 (fitted neutral 2045-2049). -/// -/// The chroma is a camera colour-difference scale, not JFIF Cb/Cr. In linear terms the stored values behave as -/// `R - Y = R_GAIN * (Cr - 2048)` and `B - Y = B_GAIN * (Cb - 2048)` on the luma scale: regressing the camera JPEG's -/// linear `(R - Y) / Y` and `(B - Y) / Y` on `(Cr - 2048) / Y` and `(Cb - 2048) / Y` over mid-tone pixels gave slopes -/// 4.92 / 5.09 (D810, correlation 0.94 / 0.88) and 3.52 / 3.73 (D4S, 0.98 / 0.97); the gains below are the rounded -/// means. They are approximate (the two bodies differ by about 30 %), the luma is not tone-mapped, and the data is -/// treated as already white balanced (neutral D4S areas have `Cb`, `Cr` within 2 of 2048 and equal JPEG R, G, B). G -/// follows from the luma equation with the BT.601 weights. The chroma is upsampled horizontally with linear -/// interpolation, centred between the two pixels of a pair. Output is linear RGB scaled by 16 (to a 14-bit range), -/// like Sony's downsized ARWs. -const SMALL_RAW_WHITE: f32 = 1023.0; -const SMALL_RAW_SCALE: f32 = 16.0; -const SMALL_RAW_CHROMA_ZERO: f32 = 2048.0; -const SMALL_RAW_R_GAIN: f32 = 4.2; -const SMALL_RAW_B_GAIN: f32 = 4.4; - -/// The strip of a small raw: compression 34713, 12 bits, no maker note `0x0096`, one strip of exactly -/// `3 * width * height` bytes (even width). -fn small_raw_strip(info: &ImageInfo, file_len: usize, mn: Option<&makernote::MakerNote>) -> Option { - if info.compression != t::compression::NIKON || info.bits() != 12 || info.samples_per_pixel != 1 { - return None; - } - if mn.is_some_and(|m| m.ifd.bytes(LINEARIZATION_TABLE).is_some()) { - return None; - } - let (w, h) = (info.width as u64, info.height as u64); - let chunks = info.chunks(file_len as u64); - match chunks.as_slice() { - [c] if w.is_multiple_of(2) && w > 0 && h > 0 && w.checked_mul(h).and_then(|n| n.checked_mul(3)) == Some(c.len) => Some(*c), - _ => None, - } -} - -/// Decode one row of a small raw (`3 * width` bytes) into `3 * width` linear RGB values on the 14-bit scale. -/// Short input reads as zero bytes. -fn small_raw_row(src: &[u8], w: usize, out: &mut [u16]) { - let Some(n) = w.checked_mul(3).filter(|n| *n <= out.len() && *n <= crate::MAX_SAMPLES) else { return }; - if w == 0 || !w.is_multiple_of(2) { - return; - } - let mut s = vec![0u16; 2 * w]; - crate::unpack::unpack_lsb(&src[..src.len().min(n)], 12, &mut s); - let pairs = w / 2; - let chroma = |k: usize| { - let g = &s[4 * k + 2..4 * k + 4]; - (f32::from(g[0]) - SMALL_RAW_CHROMA_ZERO, f32::from(g[1]) - SMALL_RAW_CHROMA_ZERO) - }; - for k in 0..pairs { - let (cb, cr) = chroma(k); - for side in 0..2 { - let (nb, nr) = if side == 0 { chroma(k.saturating_sub(1)) } else { chroma((k + 1).min(pairs - 1)) }; - let (u, v) = (0.75 * cb + 0.25 * nb, 0.75 * cr + 0.25 * nr); - let y = f32::from(s[4 * k + side]); - let r = y + SMALL_RAW_R_GAIN * v; - let b = y + SMALL_RAW_B_GAIN * u; - let g = (y - 0.299 * r - 0.114 * b) / 0.587; - let dst = (2 * k + side) * 3; - for (i, value) in [r, g, b].into_iter().enumerate() { - out[dst + i] = (value * SMALL_RAW_SCALE).round().clamp(0.0, 65535.0) as u16; - } - } - } -} - -fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: craft_tiff::image::Chunk, mode: Mode) -> Result { - use rayon::prelude::*; - let (w, h) = (info.width as usize, info.height as usize); - let stride = w.checked_mul(3).ok_or(RawError::Limit("image too large"))?; - let count = stride.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; - let src = craft_tiff::image::chunk_bytes(bytes, &strip) - .filter(|src| u64::try_from(src.len()).ok() == Some(strip.len)) - .ok_or_else(|| RawError::Corrupt("NEF: incomplete image strip".into()))?; - let data = match mode { - Mode::Full => { - let mut data = vec![0u16; count]; - data.par_chunks_mut(stride).enumerate().for_each(|(y, out)| { - small_raw_row(src.get(y * stride..).unwrap_or(&[]), w, out); - }); - data - } - Mode::Header => Vec::new(), - }; - let mut metadata = lightcraft_meta::from_tiff(tiff); - metadata.width = Some(w as u32); - metadata.height = Some(h as u32); - let img = RawImage { - format: RawFormat::Nef, - width: w, - height: h, - cpp: 3, - data: RawData::U16(data), - cfa: None, - bits: 14, - black: BlackLevel::uniform(0.0), - white: vec![SMALL_RAW_WHITE * SMALL_RAW_SCALE], - active_area: Rect::new(0, 0, w, h), - crop: Rect::new(0, 0, w, h), - orientation: Orientation::from_exif(tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION)).unwrap_or(1)), - color: ColorData::default(), - // the stored colour is already white balanced (see above) - wb_multipliers: Some([1.0; 3]), - linearized: false, - pixel_aspect: 1.0, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -#[cfg(test)] -mod tests { - use super::*; - use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; - - fn nef(compression: u16, bits: u16, strips: Vec>, w: u32, h: u32, rps: u32) -> Vec { - nef_with_note(compression, bits, strips, w, h, rps, None) - } - - /// [`nef`] with an optional maker note (`Nikon\0` v2 header + embedded big-endian TIFF holding `note`). - fn nef_with_note(compression: u16, bits: u16, strips: Vec>, w: u32, h: u32, rps: u32, note: Option) -> Vec { - nef_in(ByteOrder::Big, compression, bits, strips, w, h, rps, note) - } - - /// [`nef_with_note`] in either byte order (file and maker note). - #[allow(clippy::too_many_arguments)] - fn nef_in(order: ByteOrder, compression: u16, bits: u16, strips: Vec>, w: u32, h: u32, rps: u32, note: Option) -> Vec { - nef_model_in(order, "NIKON TEST", compression, bits, strips, w, h, rps, note) - } - - /// [`nef_in`] from camera `model`. - #[allow(clippy::too_many_arguments)] - fn nef_model_in( - order: ByteOrder, - model: &str, - compression: u16, - bits: u16, - strips: Vec>, - w: u32, - h: u32, - rps: u32, - note: Option, - ) -> Vec { - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![bits])); - raw.set(t::COMPRESSION, Value::Short(vec![compression])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![2, 1, 1, 0])); - raw.set_image(ImageData::Strips { rows_per_strip: rps, strips }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); - ifd0.set(t::MODEL, Value::Ascii(model.into())); - if let Some(mn) = note { - let mut bytes = b"Nikon\0\x02\x10\0\0".to_vec(); - bytes.extend(TiffWriter::new(order, false).write(&[mn]).unwrap()); - let mut exif = IfdBuilder::new(); - exif.set(t::MAKER_NOTE, Value::Undefined(bytes)); - ifd0.set_child(t::EXIF_IFD, exif); - } - ifd0.add_sub_ifd(raw); - TiffWriter::new(order, false).write(&[ifd0]).unwrap() - } - - /// A Z 6II NEF carrying NikonNEFInfo gets Nikon's distortion correction as one warp, in the header probe and - /// the full decode alike, and keeps it through DNG export; another body with the same data gets none. - #[test] - fn nikon_in_file_distortion_becomes_a_warp() { - use super::super::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; - let (w, h) = (48u32, 32u32); - let file = |model: &str| { - let words: Vec = (0..w * h).flat_map(|i| (600 + (i % 97) as u16 * 50).to_be_bytes()).collect(); - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14])); - raw.set(t::COMPRESSION, Value::Short(vec![1])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - let info = nef_info_blob(&[ - (0x0005, distortion_block(3, 21.6, 4, [0.039895, 0.019211, -0.127218], -0.025043)), - (0x0008, offset_block(1.5, -0.75)), - ]); - raw.set(0xc7d5, Value::Undefined(info)); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![words] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); - ifd0.set(t::MODEL, Value::Ascii(model.into())); - ifd0.add_sub_ifd(raw); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() - }; - let bytes = file("NIKON Z 6_2"); - let header = decode(&bytes, Mode::Header).unwrap(); - let full = decode(&bytes, Mode::Full).unwrap(); - assert_eq!(header.info(), full.info()); - assert_eq!(header.opcodes.list3, full.opcodes.list3); - let [crate::Opcode::WarpRectilinear { planes, center }] = full.opcodes.list3.as_slice() else { panic!("{:?}", full.opcodes.list3) }; - assert!((planes[0][0] - 1.0 / (1.0 - 0.025043)).abs() < 1e-5, "{planes:?}"); - assert!((center[0] * 47.0 - (23.5 + 1.5)).abs() < 0.01 && (center[1] * 31.0 - (15.5 - 0.75)).abs() < 0.01, "{center:?}"); - let dng = crate::write_dng(&full, &Default::default()).unwrap(); - assert_eq!(crate::decode(&dng).unwrap().opcodes.list3, full.opcodes.list3); - full.develop(crate::Method::Bilinear).unwrap(); - assert!(decode(&file("NIKON D850"), Mode::Full).unwrap().opcodes.list3.is_empty()); - } - - #[test] - fn preview_color_space_is_read_from_the_nikon_note() { - for (value, expected) in [(1, Some(crate::PreviewColorSpace::Srgb)), (2, Some(crate::PreviewColorSpace::AdobeRgb)), (3, None)] { - let mut mn = IfdBuilder::new(); - mn.set(0x001e, Value::Short(vec![value])); - let bytes = nef_with_note(1, 14, vec![vec![0; 128]], 8, 8, 8, Some(mn)); - assert_eq!(crate::embedded_preview_color_space(&bytes), expected); - } - assert_eq!(crate::embedded_preview_color_space(&nef(1, 14, vec![vec![0; 128]], 8, 8, 8)), None); - assert_eq!(crate::embedded_preview_color_space(b"not a TIFF"), None); - } - - /// Issue #778: any make's raw falls back to its EXIF ColorSpace, with Uncalibrated + InteropIndex "R03" read as - /// Adobe RGB; the Nikon note wins; a DNG is left alone. - #[test] - fn preview_color_space_falls_back_to_the_exif_color_space() { - let file = |make: &str, cs: u16, interop: Option<&str>, note: Option, dng: bool| { - let mut exif = IfdBuilder::new(); - exif.set(0xA001, Value::Short(vec![cs])); - if let Some(i) = interop { - let mut io = IfdBuilder::new(); - io.set(0x0001, Value::Ascii(i.into())); - exif.set_child(t::INTEROP_IFD, io); - } - if let Some(v) = note { - let mut mn = IfdBuilder::new(); - mn.set(0x001e, Value::Short(vec![v])); - let mut bytes = b"Nikon".to_vec(); - bytes.extend(TiffWriter::new(ByteOrder::Little, false).write(&[mn]).unwrap()); - exif.set(t::MAKER_NOTE, Value::Undefined(bytes)); - } - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii(make.into())); - if dng { - ifd0.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0])); - } - ifd0.set_child(t::EXIF_IFD, exif); - TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap() - }; - use crate::PreviewColorSpace::{AdobeRgb, Srgb}; - let f = crate::embedded_preview_color_space; - assert_eq!(f(&file("SONY", 0xFFFF, Some("R03"), None, false)), Some(AdobeRgb)); - assert_eq!(f(&file("SONY", 1, Some("R98"), None, false)), Some(Srgb)); - assert_eq!(f(&file("SONY", 0xFFFF, Some("R98"), None, false)), None); - assert_eq!(f(&file("SONY", 0xFFFF, None, None, false)), None); - assert_eq!(f(&file("Canon", 0xFFFF, Some("R03"), None, false)), Some(AdobeRgb)); - assert_eq!(f(&file("NIKON CORPORATION", 1, Some("R98"), Some(2), false)), Some(AdobeRgb)); - assert_eq!(f(&file("NIKON CORPORATION", 0xFFFF, Some("R03"), None, false)), Some(AdobeRgb)); - assert_eq!(f(&file("Canon", 0xFFFF, Some("R03"), None, true)), None); - } - - #[test] - fn nikon_crop_area_preserves_sensor_origin_and_rejects_invalid_rectangles() { - let (w, h) = (32, 24); - let words: Vec = (0..w * h).flat_map(|i| (100 + i as u16).to_be_bytes()).collect(); - for (values, expected) in [ - (vec![2, 4, 28, 16], Rect::new(2, 4, 28, 16)), - (vec![31, 4, 28, 16], Rect::new(0, 0, 32, 24)), - (vec![2, 4, 0, 16], Rect::new(0, 0, 32, 24)), - (vec![u32::MAX, 4, 28, 16], Rect::new(0, 0, 32, 24)), - (vec![2, 4, 28], Rect::new(0, 0, 32, 24)), - ] { - let mut mn = IfdBuilder::new(); - mn.set(CROP_AREA, Value::Long(values)); - let bytes = nef_with_note(1, 14, vec![words.clone()], w, h, h, Some(mn)); - let raw = crate::decode(&bytes).unwrap(); - assert_eq!(raw.crop, expected); - assert_eq!(raw.active_area, Rect::new(0, 0, 32, 24)); - assert_eq!(raw.metadata.width, Some(expected.width as u32)); - assert_eq!(raw.metadata.height, Some(expected.height as u32)); - let developed = raw.develop(crate::Method::Bilinear).unwrap(); - assert_eq!((developed.width, developed.height), (expected.width, expected.height)); - } - } - - /// The D4 records no CropArea: its measured image area and saturation level apply to files of its data size and - /// depth only. - #[test] - fn measured_d4_image_area_and_white_level() { - let (w, h) = (4992usize, 3292usize); - let decode_as = |model: &str, bits: u16| { - let mut nef = nef(1, bits, vec![vec![0x10; w * h * 2]], w as u32, h as u32, h as u32); - let at = nef.windows(10).position(|b| b == b"NIKON TEST").unwrap(); - let name = format!("{model:<10}"); - nef[at..at + 10].copy_from_slice(name.as_bytes()); - crate::decode(&nef).unwrap() - }; - let d4 = decode_as("NIKON D4", 14); - assert_eq!(d4.crop, Rect::new(8, 6, 4928, 3280)); - assert_eq!(d4.white, vec![15520.0]); - assert_eq!((d4.metadata.width, d4.metadata.height), (Some(4928), Some(3280))); - let developed = d4.develop(crate::Method::Bilinear).unwrap(); - assert_eq!((developed.width, developed.height), (4928, 3280)); - // the 12-bit mode reads out the same area but keeps the white level from its data - let d4_12 = decode_as("NIKON D4", 12); - assert_eq!(d4_12.crop, Rect::new(8, 6, 4928, 3280)); - assert_ne!(d4_12.white, vec![15520.0]); - let other = decode_as("NIKON D5", 14); - assert_eq!(other.crop, Rect::new(0, 0, w, h)); - assert_ne!(other.white, vec![15520.0]); - } - - /// Issue #976: the D7000 and D5100 record no CropArea, and their 36 masked columns at ~600 were developed as a - /// coloured bar. Their measured area applies to the measured models, data sizes and depths only. - #[test] - fn measured_d7000_and_d5100_image_area() { - let (w, h) = (4992usize, 3280usize); - let decode_as = |model: &str, bits: u16| { - let nef = nef_model_in(ByteOrder::Big, model, 1, bits, vec![vec![0x10; w * h * 2]], w as u32, h as u32, h as u32, None); - crate::decode(&nef).unwrap() - }; - for (model, bits) in [("NIKON D7000", 14), ("NIKON D7000", 12), ("NIKON D5100", 14)] { - let raw = decode_as(model, bits); - assert_eq!(raw.crop, Rect::new(8, 8, 4928, 3264), "{model} {bits}-bit"); - assert_eq!((raw.metadata.width, raw.metadata.height), (Some(4928), Some(3264))); - let developed = raw.develop(crate::Method::Bilinear).unwrap(); - assert_eq!((developed.width, developed.height), (4928, 3264)); - } - // another model, or the D5100's unmeasured 12-bit mode, keeps the whole data - for (model, bits) in [("NIKON D7100", 14), ("NIKON D5100", 12), ("NIKON D7000 ", 16)] { - assert_eq!(decode_as(model, bits).crop, Rect::new(0, 0, w, h), "{model} {bits}-bit"); - } - } - - /// The D200, D3200 and Nikon 1 V1 keep masked or dark lines in their whole data (the D200 shares the D80's data - /// size but frames it elsewhere), measured on public sample files beyond the CC0 ones; the D3100, D5000, D40, D50, - /// D70 and D70s get best-guess frames (the D40 shares the D50 / D70 / D70s data size but not their frame). - #[test] - fn measured_older_dx_bodies_image_area() { - let decode_as = |model: &str, (w, h): (usize, usize)| { - let nef = nef_model_in(ByteOrder::Big, model, 1, 12, vec![vec![0x10; w * h * 2]], w as u32, h as u32, h as u32, None); - crate::decode(&nef).unwrap() - }; - for (model, size, crop) in [ - ("NIKON D200", (3904, 2616), Rect::new(16, 12, 3872, 2592)), - ("NIKON D80", (3904, 2616), Rect::new(14, 9, 3872, 2592)), - ("NIKON D3200", (6080, 4012), Rect::new(8, 6, 6016, 4000)), - ("NIKON 1 V1", (3904, 2606), Rect::new(12, 6, 3872, 2592)), - ("NIKON D3100", (4672, 3084), Rect::new(24, 6, 4608, 3072)), - ("NIKON D5000", (4352, 2868), Rect::new(11, 10, 4288, 2848)), - ("NIKON D40", (3040, 2014), Rect::new(16, 9, 3008, 2000)), - ("NIKON D50", (3040, 2014), Rect::new(15, 7, 3008, 2000)), - ("NIKON D70", (3040, 2014), Rect::new(15, 7, 3008, 2000)), - ("NIKON D70s", (3040, 2014), Rect::new(15, 7, 3008, 2000)), - ] { - assert_eq!(decode_as(model, size).crop, crop, "{model}"); - } - // the V1's area on the V2's data size: no entry, the whole data - assert_eq!(decode_as("NIKON 1 V1", (4620, 3084)).crop, Rect::new(0, 0, 4620, 3084)); - } - - /// Every measured entry is a crop inside its data, once per model, data size and depth, with a white level (if - /// any) inside its bit range. - #[test] - fn measured_bodies_are_consistent() { - let mut seen = std::collections::HashSet::new(); - for b in MEASURED_BODIES { - let (x, y, w, h) = b.crop; - assert!(w > 0 && h > 0 && x + w <= b.size.0 && y + h <= b.size.1, "{}: crop outside its data", b.model); - assert!(seen.insert((b.model, b.size, b.bits)), "{} {:?} {}-bit listed twice", b.model, b.size, b.bits); - assert!(matches!(b.bits, 12 | 14), "{}: {}-bit", b.model, b.bits); - assert!(b.white.is_none_or(|v| v > 0.0 && v < (1u32 << b.bits) as f32), "{}: white level", b.model); - assert_eq!(b.model.trim(), b.model, "{}: model names are matched trimmed", b.model); - } - } - - /// Issue #1248: the D7100 records no CropArea, and its data holds picture beyond Lightroom's frame in both - /// image areas (full frame and 1.3x crop), so renders came out larger and Lightroom crops landed off. - #[test] - fn measured_d7100_image_area() { - let decode_as = |model: &str, (w, h): (usize, usize)| { - let mut nef = nef(1, 14, vec![vec![0x10; w * h * 2]], w as u32, h as u32, h as u32); - // the fixture's model is "NIKON TEST" plus its NUL: 11 bytes to overwrite - let at = nef.windows(11).position(|b| b == b"NIKON TEST\0").unwrap(); - let name = format!("{model:\0<11}"); - nef[at..at + 11].copy_from_slice(name.as_bytes()); - crate::decode(&nef).unwrap() - }; - for (size, crop) in [((6036, 4020), Rect::new(18, 10, 6000, 4000)), ((4812, 3212), Rect::new(6, 6, 4800, 3200))] { - let d7100 = decode_as("NIKON D7100", size); - assert_eq!(d7100.crop, crop); - assert_eq!((d7100.metadata.width, d7100.metadata.height), (Some(crop.width as u32), Some(crop.height as u32))); - assert_ne!(d7100.white, vec![15520.0]); - let developed = d7100.develop(crate::Method::Bilinear).unwrap(); - assert_eq!((developed.width, developed.height), (crop.width, crop.height)); - assert_eq!(decode_as("NIKON D7200", size).crop, Rect::new(0, 0, size.0, size.1)); - } - } - - /// The D90's last 42 columns are filler at a flat ~254, above its dark image samples: without the measured - /// area they stay in the image and develop as a pink band on the right. - #[test] - fn measured_d90_drops_the_filler_columns() { - let (w, h) = (4352usize, 2868usize); - let mut px = vec![40u16; w * h]; - for row in px.chunks_mut(w) { - row[4310..].fill(254); - } - let mut nef = nef(1, 12, vec![px.iter().flat_map(|v| v.to_le_bytes()).collect()], w as u32, h as u32, h as u32); - let at = nef.windows(10).position(|b| b == b"NIKON TEST").unwrap(); - nef[at..at + 10].copy_from_slice(b"NIKON D90 "); - let d90 = crate::decode(&nef).unwrap(); - assert_eq!(d90.crop, Rect::new(10, 10, 4288, 2848)); - assert!(d90.crop.x + d90.crop.width <= 4310, "the filler columns are outside the image"); - assert_eq!(d90.white, vec![3830.0]); - assert_eq!((d90.metadata.width, d90.metadata.height), (Some(4288), Some(2848))); - } - - /// Issue #708: the active width is judged from the first [`MASK_ROWS`] rows in both modes, so the header probe - /// (which reads only those rows' strips) and the full decode agree whether the masked columns are there or not. - #[test] - fn masked_columns_are_judged_from_the_top_rows_in_both_modes() { - let (w, h, rps) = (256usize, MASK_ROWS + 64, 8u32); - let file = |masked_rows: std::ops::Range| { - let words: Vec = (0..w * h) - .map(|i| if masked_rows.contains(&(i / w)) && i % w >= w - 8 { 0u16 } else { 1000 + (i % 7) as u16 }) - .flat_map(|v| v.to_be_bytes()) - .collect(); - nef(1, 14, words.chunks(w * 2 * rps as usize).map(|c| c.to_vec()).collect(), w as u32, h as u32, rps) - }; - for (masked_rows, expected_width) in [(0..h, w - 8), (0..MASK_ROWS, w - 8), (MASK_ROWS..h, w), (0..0, w)] { - let bytes = file(masked_rows.clone()); - let full = crate::decode(&bytes).unwrap(); - assert_eq!(full.active_area.width, expected_width, "masked rows {masked_rows:?}"); - assert_eq!(full.crop.width, expected_width); - assert_eq!(crate::probe_info(&bytes).unwrap(), full.info(), "masked rows {masked_rows:?}"); - } - // the shared rule on its own: nominal white, trailing columns at most 64, even width - let d: Vec = (0..w * 4).map(|i| if i % w >= w - 9 { 0 } else { 600 }).collect(); - assert_eq!(trailing_masked_columns(&d, w, 14), w - 10, "nine dark columns trim to an even width"); - assert_eq!(trailing_masked_columns(&d, w, 12), w - 10); - assert_eq!(trailing_masked_columns(&d[..w - 1], w, 14), w, "less than a row of samples leaves the width alone"); - assert_eq!(trailing_masked_columns(&[0; 64], 64, 14), 64, "narrow images are left alone"); - assert_eq!(trailing_masked_columns(&[], 0, 14), 0); - } - - #[test] - fn black_level_tag_is_in_14_bit_units() { - let (w, h) = (16usize, 4usize); - let words: Vec = (0..w * h).flat_map(|i| (100 + i as u16).to_be_bytes()).collect(); - let note = || { - let mut mn = IfdBuilder::new(); - mn.set(BLACK_LEVEL, Value::Short(vec![400, 404, 408, 412])); - mn - }; - let black = |bits| crate::decode(&nef_with_note(1, bits, vec![words.clone()], w as u32, h as u32, h as u32, Some(note()))).unwrap().black; - assert_eq!(black(12).values, vec![100.0, 101.0, 102.0, 103.0]); - assert_eq!(black(14).values, vec![400.0, 404.0, 408.0, 412.0]); - } - - #[test] - fn uncompressed_word16_and_packed12() { - let (w, h) = (16usize, 6usize); - let px: Vec = (0..w * h).map(|i| (i * 131 % 4096) as u16).collect(); - let words: Vec = px.iter().flat_map(|v| v.to_be_bytes()).collect(); - let bytes = nef(1, 12, words.chunks(w * 2 * 3).map(|c| c.to_vec()).collect(), w as u32, h as u32, 3); - assert_eq!(crate::probe(&bytes), Some(RawFormat::Nef)); - let r = crate::decode(&bytes).unwrap(); - assert_eq!(r.data, RawData::U16(px.clone())); - assert_eq!(r.cfa.as_ref().unwrap().name(), "BGGR"); - // 12-bit MSB packed - let mut packed = Vec::new(); - for pair in px.chunks(2) { - let (a, b) = (pair[0] as u32, pair[1] as u32); - let v = (a << 12) | b; - packed.extend_from_slice(&[(v >> 16) as u8, (v >> 8) as u8, v as u8]); - } - let bytes = nef(1, 12, vec![packed], w as u32, h as u32, h as u32); - assert_eq!(crate::decode(&bytes).unwrap().data, RawData::U16(px)); - } - - /// An NRW data block (`"NRW 0104"`, fields from byte 8) with `black` at byte `0x20`, as a maker note. - fn nrw_note(black: u32) -> IfdBuilder { - let mut block = b"NRW 0104".to_vec(); - block.resize(0x20, 0); - block.extend_from_slice(&black.to_le_bytes()); - block.resize(0x40, 0); - let mut mn = IfdBuilder::new(); - mn.set(NRW_DATA, Value::Undefined(block)); - mn - } - - /// 12-bit samples as an MSB-first bit stream inside 32-bit words in `order` (rows are whole words). - fn words32(px: &[u16], w: usize, order: ByteOrder) -> Vec { - let mut out = Vec::new(); - for row in px.chunks(w) { - let stream = row.iter().fold(Vec::new(), |mut bits: Vec, v| { - bits.extend((0..12).rev().map(|b| v >> b & 1 == 1)); - bits - }); - for word in stream.chunks(32) { - let v = word.iter().enumerate().fold(0u32, |a, (i, b)| a | (*b as u32) << (31 - i)); - out.extend_from_slice(&match order { - ByteOrder::Little => v.to_le_bytes(), - ByteOrder::Big => v.to_be_bytes(), - }); - } - } - out - } - - #[test] - fn nrw_block_selects_32_bit_word_packing_and_supplies_the_black_level() { - let (w, h) = (16usize, 6usize); - let px: Vec = (0..w * h).map(|i| (200 + i * 131 % 3800) as u16).collect(); - let packed = words32(&px, w, ByteOrder::Little); - assert_eq!(packed.len(), w * h * 3 / 2); - let decode = |note: Option| { - crate::decode(&nef_in(ByteOrder::Little, 1, 12, vec![packed.clone()], w as u32, h as u32, h as u32, note)).unwrap() - }; - let r = decode(Some(nrw_note(200))); - assert_eq!(r.data, RawData::U16(px.clone())); - assert_eq!(r.black.values, vec![200.0]); - assert_eq!(decode(Some(nrw_note(0))).black.values, vec![0.0]); - // an implausible field is not a black level - assert_eq!(decode(Some(nrw_note(60000))).black.values, vec![0.0]); - // without the block the same bytes are an MSB-first byte stream - let plain = decode(None); - assert_ne!(plain.data, RawData::U16(px)); - assert_eq!(plain.black.values, vec![0.0]); - // the maker-note black level (14-bit units) wins when present - let mut both = nrw_note(200); - both.set(BLACK_LEVEL, Value::Short(vec![400, 404, 408, 412])); - assert_eq!(decode(Some(both)).black.values, vec![100.0, 101.0, 102.0, 103.0]); - } - - #[test] - fn compressed_without_table_is_unsupported() { - let bytes = nef(34713, 14, vec![vec![0; 64]], 8, 8, 8); - let Err(RawError::Unsupported(why)) = crate::decode(&bytes) else { panic!("expected unsupported") }; - assert!(why.contains("linearization table"), "{why}"); - } - - /// Issue #193: a High Efficiency NEF (Z f, Z 8: compression 34713, no `0x0096` table, a JPEG XS codestream) is - /// named as such instead of being blamed on the missing table, and the header probe reports the same reason. - #[test] - fn high_efficiency_nef_is_named() { - let mut strip = vec![0xff, 0x10, 0xff, 0x50, 0x00, 0x22]; - strip.resize(64, 0); - let bytes = nef(34713, 14, vec![strip], 8, 8, 8); - for result in [crate::decode(&bytes).map(|_| ()), crate::probe_info(&bytes).map(|_| ())] { - let Err(RawError::Unsupported(why)) = result else { panic!("expected unsupported") }; - assert_eq!(why, HIGH_EFFICIENCY); - assert!(why.starts_with("Nikon High Efficiency NEF ("), "{why}"); - } - // a strip too short to hold the markers is still the missing-table case, not a panic - let short = nef(34713, 14, vec![vec![0xff, 0x10]], 1, 1, 1); - assert!(matches!(crate::decode(&short), Err(RawError::Unsupported(w)) if w.contains("linearization table"))); - } - - fn samples(n: usize, bits: u32) -> Vec { - (0..n).map(|i| (((i * 2654435761usize) >> 7) as u32 % (1 << bits)) as u16).collect() - } - - fn pack_lsb(row: &[u16], bits: u32) -> Vec { - let (mut out, mut acc, mut n) = (Vec::new(), 0u64, 0u32); - for &v in row { - acc |= (v as u64) << n; - n += bits; - while n >= 8 { - out.push(acc as u8); - acc >>= 8; - n -= 8; - } - } - if n > 0 { - out.push(acc as u8); - } - out - } - - fn pack_msb12(row: &[u16]) -> Vec { - let mut out = Vec::new(); - for pair in row.chunks(2) { - let (a, b) = (pair[0], pair.get(1).copied().unwrap_or(0)); - out.extend([(a >> 4) as u8, ((a & 15) << 4) as u8 | (b >> 8) as u8, b as u8]); - } - out - } - - /// Rows of `samples` packed by `row`, each padded with `pad` bytes of 0xA5 (never decoded). - fn strip(data: &[u16], w: usize, pad: usize, row: impl Fn(&[u16]) -> Vec) -> Vec { - data.chunks(w).flat_map(|r| row(r).into_iter().chain(std::iter::repeat_n(0xA5, pad))).collect() - } - - fn decoded(strip: Vec, bits: u16, w: u32, h: u32) -> Result> { - let bytes = nef(34713, bits, vec![strip], w, h, h); - match crate::decode(&bytes)?.data { - RawData::U16(d) => Ok(d), - _ => Err(RawError::Unsupported("float".into())), - } - } - - #[test] - fn packed_34713_layouts_round_trip() { - let (w, h) = (40usize, 6usize); - let d12 = samples(w * h, 12); - let d14 = samples(w * h, 14); - // group A: 12-bit, 3w/2 bytes per row - assert_eq!(decoded(strip(&d12, w, 0, |r| pack_lsb(r, 12)), 12, 40, 6).unwrap(), d12); - // group B: 12-bit, rows padded to 16 bytes (60 -> 64) - assert_eq!(decoded(strip(&d12, w, 4, |r| pack_lsb(r, 12)), 12, 40, 6).unwrap(), d12); - // group C: 14-bit, 70 bytes -> 80 - assert_eq!(decoded(strip(&d14, w, 10, |r| pack_lsb(r, 14)), 14, 40, 6).unwrap(), d14); - // group E: 16-byte chunks, 15 data bytes (ten samples) + a zero byte; 16 chunks = 160 samples (at 40 wide the - // 64-byte stride would be group B's) - let (w, h) = (160usize, 3usize); - let d12 = samples(w * h, 12); - let e = strip(&d12, w, 0, |r| r.chunks(10).flat_map(|c| pack_msb12(c).into_iter().chain([0u8])).collect()); - assert_eq!(e.len(), 256 * h); - assert_eq!(decoded(e, 12, 160, 3).unwrap(), d12); - } - - /// Z 6II "Packed 14 bits" (maker note 0x93 = 10, issue #769): 6064x4040, 14-bit, one strip of 4040 rows of 10624 - /// bytes (6064 * 14 / 8 = 10612, padded to a multiple of 16). Four rows keep the real stride. - #[test] - fn packed_14_bit_z6ii_geometry_with_row_padding() { - let (w, h) = (6064usize, 4usize); - let d14 = samples(w * h, 14); - let s = strip(&d14, w, 12, |r| pack_lsb(r, 14)); - assert_eq!(s.len(), 10624 * h); - assert_eq!(decoded(s, 14, w as u32, h as u32).unwrap(), d14); - assert_eq!(packed_layout(6064, 4040, 14, 42_920_960), Some(PackedLayout::Lsb { stride: 10624 })); - } - - #[test] - fn packed_layout_refuses_overflowing_dimensions() { - for bits in [12, 14] { - assert!(packed_layout(usize::MAX - 3, 1, bits, u64::MAX).is_none()); - } - assert!(d100_layout(usize::MAX, 1, 12, u64::MAX).is_none()); - } - - /// Header probes inspect only the same top rows that the masked-column test uses. Routing - /// still validates the complete strip's layout, so header and full decode keep the same crop. - #[test] - fn packed_header_probe_reads_only_the_mask_rows() { - let (w, h) = (160usize, MASK_ROWS + 7); - let data = samples(w * h, 12); - for image in [strip(&data, w, 0, |r| pack_lsb(r, 12)), be16(&data)] { - let bytes = nef(34713, 12, vec![image], w as u32, h as u32, h as u32); - let tiff = Tiff::parse(&bytes).unwrap(); - let info = raw_ifd(&tiff).unwrap().image().unwrap(); - let RawData::U16(top) = packed(&bytes, &info, MASK_ROWS).unwrap() else { panic!("integer samples") }; - assert_eq!(top, data[..w * MASK_ROWS]); - let header = decode(&bytes, Mode::Header).unwrap(); - let full = decode(&bytes, Mode::Full).unwrap(); - assert_eq!((header.active_area, header.crop), (full.active_area, full.crop)); - assert!(matches!(header.data, RawData::U16(ref samples) if samples.is_empty())); - } - } - - #[test] - fn packed_d100_rows_carry_extra_columns() { - // IFD width 154, rows hold 160 samples (16 chunks); the last 6 are dropped - let (w, wide, h) = (154usize, 160usize, 3usize); - let wide_data = samples(wide * h, 12); - let e = strip(&wide_data, wide, 0, |r| r.chunks(10).flat_map(|c| pack_msb12(c).into_iter().chain([0u8])).collect()); - let got = decoded(e, 12, w as u32, h as u32).unwrap(); - let want: Vec = wide_data.chunks(wide).flat_map(|r| r[..w].iter().copied()).collect(); - assert_eq!(got, want); - } - - #[test] - fn packed_34713_wrong_sizes_stay_refused() { - let d12 = samples(40 * 6, 12); - let good = strip(&d12, 40, 0, |r| pack_lsb(r, 12)); - // one byte more or fewer, a stride that is neither tight nor 16-aligned, a 13-bit file - for len in [good.len() - 1, good.len() + 1, good.len() + 6] { - let mut s = good.clone(); - s.resize(len, 0); - assert!(matches!(decoded(s, 12, 40, 6), Err(RawError::Unsupported(_))), "len {len}"); - } - assert!(matches!(decoded(good.clone(), 13, 40, 6), Err(RawError::Unsupported(_)))); - // 14-bit rows must be padded to 16 bytes - let d14 = samples(40 * 6, 14); - assert!(matches!(decoded(strip(&d14, 40, 0, |r| pack_lsb(r, 14)), 14, 40, 6), Err(RawError::Unsupported(_)))); - } - - /// A small raw strip of `[Y0 Y1 Cb Cr]` groups, rows of `3 * w` bytes, LSB-first 12-bit. - fn small_strip(groups: &[[u16; 4]], w: usize) -> Vec { - let flat: Vec = groups.iter().flatten().copied().collect(); - assert_eq!(flat.len() % (2 * w), 0); - flat.chunks(2 * w).flat_map(|r| pack_lsb(r, 12)).collect() - } - - fn small(strip: Vec, bits: u16, w: u32, h: u32) -> Result { - crate::decode(&nef(34713, bits, vec![strip], w, h, h)) - } - - #[test] - fn small_raw_422_round_trips() { - let (w, h) = (8usize, 3usize); - // flat chroma per row so the interpolation is exact; distinct luma everywhere - let mut groups = Vec::new(); - for y in 0..h { - for k in 0..w / 2 { - let (cb, cr) = (2048 + 10 * y as u16, 2048 - 5 * y as u16); - groups.push([100 + (y * w + 2 * k) as u16, 100 + (y * w + 2 * k + 1) as u16, cb, cr]); - } - } - let raw = small(small_strip(&groups, w), 12, w as u32, h as u32).unwrap(); - assert_eq!((raw.width, raw.height, raw.cpp, raw.cfa.is_none()), (w, h, 3, true)); - assert_eq!(raw.wb_multipliers, Some([1.0; 3])); - let RawData::U16(d) = &raw.data else { panic!() }; - for y in 0..h { - for x in 0..w { - let luma = (100 + y * w + x) as f32; - let (u, v) = (10.0 * y as f32, -5.0 * y as f32); - let (r, b) = (luma + SMALL_RAW_R_GAIN * v, luma + SMALL_RAW_B_GAIN * u); - let g = (luma - 0.299 * r - 0.114 * b) / 0.587; - for (i, want) in [r, g, b].into_iter().enumerate() { - let got = f32::from(d[(y * w + x) * 3 + i]) / SMALL_RAW_SCALE; - assert!((got - want).abs() < 0.1, "({x},{y}) channel {i}: {got} vs {want}"); - } - } - } - } - - #[test] - fn small_raw_neutral_chroma_is_grey_and_chroma_is_interpolated() { - let w = 8usize; - let groups: Vec<[u16; 4]> = (0..w / 2).map(|k| [200 + 40 * k as u16, 200 + 40 * k as u16, 2048, 2048]).collect(); - let raw = small(small_strip(&groups, w), 12, w as u32, 1).unwrap(); - let RawData::U16(d) = &raw.data else { panic!() }; - for x in 0..w { - let px = &d[x * 3..x * 3 + 3]; - assert!(px.iter().all(|&v| v == px[0]), "{px:?}"); - assert_eq!(f32::from(px[0]), (200 + 40 * (x / 2)) as f32 * SMALL_RAW_SCALE); - } - // a step in Cb between the first two pairs is shared 3:1 by the pixels next to the boundary - let mut groups = groups; - groups[1][2] = 2048 + 100; - let raw = small(small_strip(&groups, w), 12, w as u32, 1).unwrap(); - let RawData::U16(d) = &raw.data else { panic!() }; - let blue_minus_luma = |x: usize, luma: f32| f32::from(d[x * 3 + 2]) / SMALL_RAW_SCALE - luma; - assert!((blue_minus_luma(1, 200.0) - SMALL_RAW_B_GAIN * 25.0).abs() < 0.1); - assert!((blue_minus_luma(2, 240.0) - SMALL_RAW_B_GAIN * 75.0).abs() < 0.1); - } - - #[test] - fn small_raw_wrong_sizes_and_depths_are_refused() { - let (w, h) = (8usize, 3usize); - let good = small_strip(&vec![[100, 100, 2048, 2048]; w / 2 * h], w); - assert!(small(good.clone(), 12, w as u32, h as u32).is_ok()); - for len in [good.len() - 1, good.len() + 1] { - let mut s = good.clone(); - s.resize(len, 0); - assert!(matches!(small(s, 12, w as u32, h as u32), Err(RawError::Unsupported(_))), "len {len}"); - } - assert!(matches!(small(good.clone(), 14, w as u32, h as u32), Err(RawError::Unsupported(_)))); - // odd width: 3 bytes per pixel does not split into pixel pairs - assert!(matches!(small(vec![0; 3 * 7 * 3], 12, 7, 3), Err(RawError::Unsupported(_)))); - } - - #[test] - fn small_raw_short_input_does_not_panic() { - for len in [0, 1, 2, 3, 5, 11, 12, 13] { - let mut out = vec![0u16; 12]; - small_raw_row(&vec![0xFF; len], 4, &mut out); - } - let mut bytes = nef(34713, 12, vec![vec![0x55; 3 * 8 * 3]], 8, 3, 3); - bytes.truncate(bytes.len() - 40); - assert!(crate::decode(&bytes).is_err(), "a truncated small-raw strip is corrupt"); - } - - #[test] - fn small_raw_header_has_full_geometry_without_allocating_pixels() { - let (w, h) = (8usize, 3usize); - let bytes = nef(34713, 12, vec![small_strip(&vec![[100, 110, 2048, 2048]; w / 2 * h], w)], w as u32, h as u32, h as u32); - let header = decode(&bytes, Mode::Header).unwrap(); - let full = decode(&bytes, Mode::Full).unwrap(); - assert_eq!(header.info(), full.info()); - assert!(matches!(header.data, RawData::U16(ref samples) if samples.is_empty())); - assert!(matches!(full.data, RawData::U16(ref samples) if samples.len() == 3 * w * h)); - } - - #[test] - fn small_raw_rejects_excessive_dimensions_before_allocation() { - let bytes = nef(34713, 12, vec![vec![0; 72]], 8, 3, 3); - let tiff = Tiff::parse(&bytes).unwrap(); - let mut info = raw_ifd(&tiff).unwrap().image().unwrap(); - let strip = info.chunks(bytes.len() as u64)[0]; - info.width = u32::MAX - 1; - info.height = u32::MAX; - assert!(matches!(small_raw(&bytes, &tiff, &info, strip, Mode::Header), Err(RawError::Limit(_)))); - let mut out = [0; 12]; - small_raw_row(&[], usize::MAX, &mut out); - small_raw_row(&[], 3, &mut out); - assert_eq!(out, [0; 12]); - } - - /// Big-endian 16-bit words holding the 12-bit samples in their upper bits. - fn be16(data: &[u16]) -> Vec { - data.iter().flat_map(|v| (v << 4).to_be_bytes()).collect() - } - - #[test] - fn coolpix_be16_words_decode_and_wrong_sizes_are_refused() { - let (w, h) = (40usize, 6usize); - let d12 = samples(w * h, 12); - let good = be16(&d12); - assert_eq!(good.len(), 2 * w * h); - assert_eq!(decoded(good.clone(), 12, 40, 6).unwrap(), d12); - // a half-LSB in the low nibble does not change the sample - let mut half = good.clone(); - for b in half.iter_mut().skip(1).step_by(2) { - *b |= 8; - } - assert_eq!(decoded(half, 12, 40, 6).unwrap(), d12); - // any other strip size, or another bit depth, is not this layout - for len in [good.len() - 2, good.len() - 1, good.len() + 1, good.len() + 2, good.len() + 16] { - let mut s = good.clone(); - s.resize(len, 0); - assert!(matches!(decoded(s, 12, 40, 6), Err(RawError::Unsupported(_))), "len {len}"); - } - assert!(matches!(decoded(good.clone(), 13, 40, 6), Err(RawError::Unsupported(_)))); - // the black level is 200, but never above the darkest sample - let black = |data: &[u16]| crate::decode(&nef(34713, 12, vec![be16(data)], 40, 6, 6)).unwrap().black.values[0]; - let mut d = d12.clone(); - for v in &mut d { - *v = (*v).max(300); - } - assert_eq!(black(&d), 200.0); - d[5] = 150; - assert_eq!(black(&d), 150.0); - } - - #[test] - fn coolpix_be16_does_not_take_other_layouts() { - // every width where another group's stride equals 2w must still go to that group (the narrow rows where they - // coincide are below the real-world widths; the other groups are tried first) - for w in (2..=400usize).step_by(2) { - let strip = 2 * w as u64 * 6; - let other = packed_layout(w, 6, 12, strip).or_else(|| d100_layout(w, 6, 12, strip)); - if other.is_some() { - assert_eq!(packed_layout(w, 6, 12, strip).or_else(|| d100_layout(w, 6, 12, strip)).or_else(|| be16_layout(w, 6, 12, strip)), other); - } - } - assert_eq!(be16_layout(4032, 3024, 12, 24385536), Some(PackedLayout::Be16)); - assert!(packed_layout(4032, 3024, 12, 24385536).is_none() && d100_layout(4032, 3024, 12, 24385536).is_none()); - assert!(be16_layout(4032, 3024, 14, 24385536).is_none()); - assert!(be16_layout(usize::MAX, usize::MAX, 12, u64::MAX).is_none()); - } - - #[test] - fn packed_34713_short_input_does_not_panic() { - let (w, h) = (40usize, 6usize); - for layout in [PackedLayout::Lsb { stride: 64 }, PackedLayout::Lsb { stride: 80 }, PackedLayout::Chunked16 { stride: 64 }, PackedLayout::Be16] - { - for len in [0, 1, 15, 16, 17, 63, 64, 65, 200] { - let bits = if matches!(layout, PackedLayout::Lsb { stride: 80 }) { 14 } else { 12 }; - assert_eq!(unpack_packed(&vec![0xFF; len], w, h, bits, layout).len(), w * h); - } - } - // a strip that claims more bytes than the file has - let mut bytes = nef(34713, 12, vec![vec![0x55; 60 * 6]], 40, 6, 6); - bytes.truncate(bytes.len() - 100); - assert!(crate::decode(&bytes).is_err(), "a truncated packed strip is corrupt"); - } - /// Keep every directory intact before a relocated tail strip, then remove its last rows. - fn truncated_tail_strip(mut bytes: Vec, keep: usize) -> Vec { - let tiff = Tiff::parse(&bytes).unwrap(); - let raw = raw_ifd(&tiff).unwrap(); - let info = raw.image().unwrap(); - let chunk = info.chunks(bytes.len() as u64)[0]; - let data = craft_tiff::image::chunk_bytes(&bytes, &chunk).unwrap().to_vec(); - let offset_entry = raw.get(t::STRIP_OFFSETS).unwrap().offset as usize; - let start = bytes.len() as u32; - bytes[offset_entry..offset_entry + 4].copy_from_slice(&start.to_be_bytes()); - bytes.extend_from_slice(&data[..keep]); - bytes - } - - #[test] - fn packed_rejects_tail_truncation_with_intact_directories() { - let bytes = nef(34713, 12, vec![vec![0x55; 360]], 40, 6, 6); - for keep in [0, 60, 359] { - let short = truncated_tail_strip(bytes.clone(), keep); - for mode in [Mode::Header, Mode::Full] { - assert!(matches!(decode(&short, mode), Err(RawError::Corrupt(_)))); - } - } - } - - #[test] - fn small_raw_rejects_tail_truncation_with_intact_directories() { - let bytes = nef(34713, 12, vec![vec![0x55; 72]], 8, 3, 3); - for keep in [0, 24, 71] { - let short = truncated_tail_strip(bytes.clone(), keep); - for mode in [Mode::Header, Mode::Full] { - assert!(matches!(decode(&short, mode), Err(RawError::Corrupt(_)))); - } - } - } -} diff --git a/crates/raw/src/vendor/nef_lens.rs b/crates/raw/src/vendor/nef_lens.rs deleted file mode 100644 index ee320c36d1..0000000000 --- a/crates/raw/src/vendor/nef_lens.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Nikon's in-file distortion correction (raw SubIFD tag `0xc7d5`, NikonNEFInfo), expressed as a DNG warp for -//! the shared optics pipeline. -//! -//! Tag identity: the ExifTool Nikon tag-name documentation (NikonNEFInfo `0xc7d5`; its DistortionInfo `0x0005` -//! with DistortionCorrection and RadialDistortionCoefficient1..3). The model below (which stored value multiplies -//! which power, the normalisation, the fill-frame zoom and the optical-centre offset in entry `0x0008`) was inferred -//! independently by matching the raw against the camera's own corrected JPEG; see docs/nikon-lens-corrections.md. -//! No lens database or external decoder code. - -use crate::{Opcode, Rect}; -use craft_tiff::{ByteOrder, Ifd, ParseOptions, parse_ifd_at}; - -const NEF_INFO: u16 = 0xc7d5; -const DISTORTION_INFO: u16 = 0x0005; -const CENTRE_OFFSET: u16 = 0x0008; -/// Bodies whose files were checked against the camera's JPEG (docs/nikon-lens-corrections.md). Matching tags on -/// another body do not establish its pixel pitch or image area; add a body only after checking its files. -const VALIDATED: &[&str] = &["NIKON Z 6_2", "NIKON Z 8", "NIKON Z f"]; -/// The normalisation radius every checked file stores: the FX half-diagonal in millimetres. -const FX_HALF_DIAGONAL_MM: f64 = 21.6; -const SAMPLES: usize = 256; - -/// `r_src = r_out * (1 + k3 rho^2 + k2 rho^4 + k1 rho^6) / (1 + zoom)` around the optical centre, `rho` the radius -/// over the half-diagonal of the image area (`k1..k3` as ExifTool names them, in the order they are stored). -#[derive(Clone, Copy, Debug, PartialEq)] -struct Distortion { - k: [f64; 3], - zoom: f64, -} - -/// A signed rational at `at` (`i32 / i32`), when it is one. -fn rational(b: &[u8], at: usize, order: ByteOrder) -> Option { - let n = order.u32(b.get(at..at + 4)?.try_into().ok()?) as i32; - let d = order.u32(b.get(at + 4..at + 8)?.try_into().ok()?) as i32; - (d > 0).then(|| f64::from(n) / f64::from(d)).filter(|v| v.is_finite()) -} - -/// The NikonNEFInfo entries: the blob is `"Nikon\0"`, a 4-byte version, then a little TIFF stream. -fn nef_info(raw: &Ifd) -> Option<(Ifd, ByteOrder)> { - let tiff = raw.bytes(NEF_INFO)?.strip_prefix(b"Nikon\0")?.get(4..)?; - let (order, false) = craft_tiff::Tiff::sniff(tiff)? else { return None }; - let first = order.u32(tiff.get(4..8)?.try_into().ok()?); - let opts = ParseOptions { follow_children: false, ..Default::default() }; - let (ifd, _) = parse_ifd_at(tiff, u64::from(first), order, 0, false, &opts).ok()?; - Some((ifd, order)) -} - -/// DistortionInfo: `"0100"`, the correction mode (0 none), the normalisation radius (mm) at 8, the term count (4) -/// at 16, the coefficients at 20 / 28 / 36 and the zoom at 64, each a signed rational. -fn distortion_info(b: &[u8], order: ByteOrder) -> Option { - if b.get(0..4)? != b"0100" || *b.get(4)? == 0 { - return None; - } - let norm = rational(b, 8, order)?; - let terms = order.u32(b.get(16..20)?.try_into().ok()?); - if (norm - FX_HALF_DIAGONAL_MM).abs() > 0.05 || terms != 4 { - return None; - } - let k = [rational(b, 20, order)?, rational(b, 28, order)?, rational(b, 36, order)?]; - let zoom = rational(b, 64, order)?; - // real lenses stay far inside these (the checked files: |k| < 0.13, |zoom| < 0.09) - (k.iter().all(|v| v.abs() < 1.0) && zoom.abs() < 0.5).then_some(Distortion { k, zoom }) -} - -/// Entry `0x0008`: `"0100"`, then the optical centre's offset from the image-area centre in pixels (x right, -/// y down), two signed rationals. Zero when the lens stabilises (the sensor stays centred). -fn centre_offset(b: &[u8], order: ByteOrder) -> Option<(f64, f64)> { - (b.get(0..4)? == b"0100").then_some(())?; - Some((rational(b, 4, order)?, rational(b, 12, order)?)) -} - -/// The correction of a `model` NEF whose raw IFD is `raw`, for the image area `crop` inside `active` (both in -/// sensor pixels), as an `OpcodeList3` warp in active-area coordinates. `None` for unvalidated bodies, other -/// image areas, missing or implausible data, and maps that fold. -pub(super) fn distortion(model: &str, raw: &Ifd, active: Rect, crop: Rect) -> Option { - if !VALIDATED.contains(&model.trim()) { - return None; - } - let crop = crop.clipped(active.width, active.height); - if active.width < 2 || active.height < 2 || crop.width < 2 || crop.height < 2 { - return None; - } - // the stored radius is the FX half-diagonal: only the full 3:2 image area (not a DX or other crop of the - // sensor) is normalised by it - if (crop.width as f64 / crop.height as f64 - 1.5).abs() > 0.005 || (crop.width as f64) < active.width as f64 * 0.95 { - return None; - } - let (info, order) = nef_info(raw)?; - let d = distortion_info(info.bytes(DISTORTION_INFO)?, order)?; - let (ox, oy) = info.bytes(CENTRE_OFFSET).and_then(|b| centre_offset(b, order)).unwrap_or((0.0, 0.0)); - let (cw, ch) = (crop.width as f64 - 1.0, crop.height as f64 - 1.0); - if ox.abs() > cw * 0.05 || oy.abs() > ch * 0.05 { - return None; - } - let half_diagonal = cw.hypot(ch) / 2.0; - let poly = |rho: f64| { - let x = rho * rho; - 1.0 + x * (d.k[2] + x * (d.k[1] + x * d.k[0])) - }; - // DNG normalises by the farthest active-area corner from the centre; the image area reaches at most there - let (ax, ay) = (active.width as f64 - 1.0, active.height as f64 - 1.0); - let (cx, cy) = (crop.x as f64 + cw / 2.0 + ox, crop.y as f64 + ch / 2.0 + oy); - let farthest = cx.max(ax - cx).hypot(cy.max(ay - cy)); - let a = farthest / half_diagonal; - // the source radius must grow with the output radius out to the farthest corner, or the map folds - let mut previous = -1.0; - for j in 0..=SAMPLES { - let rho = a * j as f64 / SAMPLES as f64; - let source = rho * poly(rho) / (1.0 + d.zoom); - if !source.is_finite() || source <= previous { - return None; - } - previous = source; - } - let s = 1.0 / (1.0 + d.zoom); - let a2 = a * a; - let planes = vec![[s, d.k[2] * a2 * s, d.k[1] * a2 * a2 * s, d.k[0] * a2 * a2 * a2 * s, 0.0, 0.0]]; - Some(Opcode::WarpRectilinear { planes, center: [cx / ax, cy / ay] }) -} - -#[cfg(test)] -pub(in crate::vendor) mod tests { - use super::*; - use craft_tiff::{Entry, IfdBuilder, TiffWriter, Value}; - - const AREA: Rect = Rect { x: 0, y: 0, width: 6064, height: 4040 }; - const CROP: Rect = Rect { x: 8, y: 8, width: 6048, height: 4024 }; - - fn rat(v: f64, den: i32) -> [u8; 8] { - let mut b = [0u8; 8]; - b[..4].copy_from_slice(&((v * f64::from(den)).round() as i32).to_le_bytes()); - b[4..].copy_from_slice(&den.to_le_bytes()); - b - } - - /// DistortionInfo as the checked files lay it out (84 bytes, little-endian). - pub(in crate::vendor) fn distortion_block(mode: u8, norm: f64, terms: u32, k: [f64; 3], zoom: f64) -> Vec { - let mut b = vec![0u8; 84]; - b[..4].copy_from_slice(b"0100"); - b[4] = mode; - b[5] = 1; - b[8..16].copy_from_slice(&rat(norm, 4096)); - b[16..20].copy_from_slice(&terms.to_le_bytes()); - for (i, v) in k.iter().enumerate() { - b[20 + 8 * i..28 + 8 * i].copy_from_slice(&rat(*v, 1 << 20)); - } - b[44..52].copy_from_slice(&rat(0.0, 1)); - b[52..60].copy_from_slice(&rat(0.0, 1)); - b[64..72].copy_from_slice(&rat(zoom, 1 << 20)); - b - } - - pub(in crate::vendor) fn offset_block(x: f64, y: f64) -> Vec { - let mut b = b"0100".to_vec(); - b.extend_from_slice(&rat(x, 256)); - b.extend_from_slice(&rat(y, 256)); - b.extend_from_slice(&[0, 0, 0, 0]); - b - } - - /// A NikonNEFInfo (`0xc7d5`) blob with the given entries. - pub(in crate::vendor) fn nef_info_blob(entries: &[(u16, Vec)]) -> Vec { - let mut info = IfdBuilder::new(); - for (tag, data) in entries { - info.set(*tag, Value::Undefined(data.clone())); - } - let tiff = TiffWriter::new(ByteOrder::Little, false).write(&[info]).unwrap(); - let mut blob = b"Nikon\0\x01\x03\0\0".to_vec(); - blob.extend_from_slice(&tiff); - blob - } - - /// A raw IFD carrying a NikonNEFInfo blob with the given entries. - pub(super) fn raw_with(entries: &[(u16, Vec)]) -> Ifd { - Ifd { entries: vec![Entry { tag: NEF_INFO, value: Value::Undefined(nef_info_blob(entries)), offset: 0 }], ..Default::default() } - } - - // a Z 24-70 f/4 S at 24 mm and at 70 mm, as stored in two of the checked files - const WIDE: ([f64; 3], f64) = ([0.039895, 0.019211, -0.127218], -0.025043); - const TELE: ([f64; 3], f64) = ([0.01681, -0.010601, 0.056758], 0.088301); - - fn warp(model: &str, raw: &Ifd) -> Option<([f64; 6], [f64; 2])> { - match distortion(model, raw, AREA, CROP)? { - Opcode::WarpRectilinear { planes, center } => Some((planes[0], center)), - _ => None, - } - } - - /// The source radius the warp gives for an output radius `rho` (in image-area half-diagonals) about the centre. - fn source_rho(p: [f64; 6], centre: [f64; 2], rho: f64) -> f64 { - let (ax, ay) = (AREA.width as f64 - 1.0, AREA.height as f64 - 1.0); - let (cx, cy) = (centre[0] * ax, centre[1] * ay); - let m = cx.max(ax - cx).hypot(cy.max(ay - cy)); - let hd = (CROP.width as f64 - 1.0).hypot(CROP.height as f64 - 1.0) / 2.0; - let t2 = (rho * hd / m).powi(2); - rho * (p[0] + t2 * (p[1] + t2 * (p[2] + t2 * p[3]))) - } - - #[test] - fn the_warp_is_the_stored_polynomial_over_the_zoom() { - for (k, zoom) in [WIDE, TELE] { - let raw = raw_with(&[(DISTORTION_INFO, distortion_block(3, 21.6, 4, k, zoom))]); - let (p, c) = warp("NIKON Z 6_2", &raw).unwrap(); - for rho in [0.0, 0.25, 0.5, 0.75, 1.0] { - let x = rho * rho; - let want = rho * (1.0 + k[2] * x + k[1] * x * x + k[0] * x * x * x) / (1.0 + zoom); - assert!((source_rho(p, c, rho) - want).abs() < 2e-6, "{k:?} at {rho}"); - } - // centred on the image area, which sits 8 px in from the sensor's top-left - assert!((c[0] - (8.0 + 6047.0 / 2.0) / 6063.0).abs() < 1e-12 && (c[1] - (8.0 + 4023.0 / 2.0) / 4039.0).abs() < 1e-12); - } - } - - #[test] - fn the_optical_centre_follows_the_sensor_shift() { - let raw = raw_with(&[(DISTORTION_INFO, distortion_block(3, 21.6, 4, TELE.0, TELE.1)), (CENTRE_OFFSET, offset_block(-90.1, 18.59))]); - let (_, c) = warp("NIKON Z 6_2", &raw).unwrap(); - assert!((c[0] * 6063.0 - (8.0 + 6047.0 / 2.0 - 90.1)).abs() < 0.01, "{c:?}"); - assert!((c[1] * 4039.0 - (8.0 + 4023.0 / 2.0 + 18.59)).abs() < 0.01, "{c:?}"); - } - - #[test] - fn refuses_unvalidated_bodies_and_unknown_layouts() { - let good = distortion_block(3, 21.6, 4, WIDE.0, WIDE.1); - assert!(warp("NIKON Z 6_2", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); - assert!(warp("NIKON Z f", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); - assert!(warp("NIKON Z 8", &raw_with(&[(DISTORTION_INFO, good.clone())])).is_some()); - for model in ["", "NIKON Z 6", "NIKON Z 6_3", "NIKON Z 9", "NIKON D850", "NIKON Z 6_2 x"] { - assert!(warp(model, &raw_with(&[(DISTORTION_INFO, good.clone())])).is_none(), "{model}"); - } - // correction off, a DX radius, another term count, a wild coefficient or zoom, no NEFInfo at all - for bad in [ - distortion_block(0, 21.6, 4, WIDE.0, WIDE.1), - distortion_block(3, 14.2, 4, WIDE.0, WIDE.1), - distortion_block(3, 21.6, 3, WIDE.0, WIDE.1), - distortion_block(3, 21.6, 4, [0.0, 0.0, 1.5], 0.0), - distortion_block(3, 21.6, 4, WIDE.0, 0.9), - b"0200".iter().copied().chain([0u8; 80]).collect(), - vec![0u8; 12], - ] { - assert!(warp("NIKON Z 6_2", &raw_with(&[(DISTORTION_INFO, bad)])).is_none()); - } - assert!(warp("NIKON Z 6_2", &Ifd::default()).is_none()); - // a map that folds (the source radius turns back) is refused - assert!(warp("NIKON Z 6_2", &raw_with(&[(DISTORTION_INFO, distortion_block(3, 21.6, 4, [-0.9, 0.0, 0.0], 0.0))])).is_none()); - } - - #[test] - fn only_the_full_3_2_image_area_is_corrected() { - let raw = raw_with(&[(DISTORTION_INFO, distortion_block(3, 21.6, 4, WIDE.0, WIDE.1))]); - // a DX or 1:1 crop of the sensor would need another normalisation - assert!(distortion("NIKON Z 6_2", &raw, AREA, Rect::new(1016, 676, 4032, 2688)).is_none(), "DX"); - assert!(distortion("NIKON Z 6_2", &raw, AREA, Rect::new(1016, 8, 4024, 4024)).is_none()); - assert!(distortion("NIKON Z 6_2", &raw, AREA, Rect::new(0, 0, 1, 1)).is_none()); - // a sensor-shift offset beyond 5 % of the frame is not trusted - let far = raw_with(&[(DISTORTION_INFO, distortion_block(3, 21.6, 4, WIDE.0, WIDE.1)), (CENTRE_OFFSET, offset_block(900.0, 0.0))]); - assert!(warp("NIKON Z 6_2", &far).is_none()); - } -} diff --git a/crates/raw/src/vendor/nefc.rs b/crates/raw/src/vendor/nefc.rs deleted file mode 100644 index 27c7467f9b..0000000000 --- a/crates/raw/src/vendor/nefc.rs +++ /dev/null @@ -1,794 +0,0 @@ -//! Nikon Huffman-compressed NEF image data (TIFF compression 34713): "lossless compressed" and "lossy compressed" -//! (type 1 and type 2) at 12 and 14 bits. -//! -//! **Clean-room.** No raw-decoder source code (dcraw, LibRaw, rawspeed, rawloader/rawler, darktable, RawTherapee, -//! libopenraw, ExifTool's Perl code, …) was read or consulted. What we used: -//! -//! - Prose format descriptions: Laurent Clévy, "Nikon Electronic File (NEF) format" (), -//! the maker-note tag table and the "0x96 (linearization table) tag format" table (version bytes, four `u16` -//! predictor seeds at offset 2, curve size at 10, curve at 12, split value at 562 for lossy type 2, "lossy type -//! 2 reads an incomplete table and interpolation is required"); Bill Claff, "NEF Compression" -//! (): a lossy encoding curve followed by a -//! non-adaptive (fixed-table) Huffman stage, and the number of encoded values per camera (683, 769, 1025, 2753, -//! 3073, 4097 …), which confirmed our curve interpolation; the libopenraw format notes -//! (, prose only); ExifTool's Nikon tag-name documentation -//! (`0x0093` NEFCompression, `0x0096` NEFLinearizationTable); ITU-T T.81 Annex F/H for the "difference category -//! + additional bits" coding and canonical (BITS/HUFFVAL) Huffman codes. -//! - Our own black-box analysis of CC0 samples from raw.pixls.us. Nikon's Huffman tables are not stored in the -//! files and no prose source lists them, so they were recovered from the data: several cameras (D5100, D300, -//! D700) were shot with the same scene in compressed and uncompressed modes; a beam search assigned code words -//! to difference categories so that the decoded compressed image matched the uncompressed one (likelihood of -//! the decoded values given the reference, minus the bits consumed, plus a description-length penalty per new -//! code word). Each table was then verified on ~45 files from ~35 bodies (D40 … D850, Df, Z 6, Z 50, 1 J1): with -//! the right table the whole strip decodes and ends within the last byte of the data, with every value inside -//! the encoded range. The predictor and difference coding are the same as Pentax PEF (see `pef.rs`). -//! -//! Format, as established: -//! - One strip, MSB-first bit stream, no byte stuffing, continuous across rows. Per pixel a canonical Huffman code -//! gives the category `n`, followed by `n` additional bits (T.81: a leading 0 means a negative difference). -//! - Each pixel is predicted from the same-colour pixel two to the left; the first two pixels of a row from the -//! first two pixels of the previous row of the same parity, starting at the seeds of maker note `0x0096`. -//! - Lossless (`0x0096` version `0x46`): the decoded values are the samples. Lossy (version `0x44`): they index a -//! curve. Type 1 (`0x44 0x10`) stores the full curve; type 2 (`0x44 0x20`, `0x44 0x40`) stores 257 points, -//! one every `2^bits / 256` codes (`0x20`) or `2^bits / 1024` codes (`0x40`), linearly interpolated. The span -//! was established from the files: in every `0x20` file the first interval of the 257 points rises by -//! `2^bits / 256` (16 at 12 bit, 64 at 14 bit) and in every `0x40` file by `2^bits / 1024` (4 and 16), i.e. -//! the curve is the identity in the dark part, one code per sample. Read with a point every `2^bits / 256` -//! codes instead, the 12 `0x40` files that are not split decoded to values that never exceeded 255 (12 bit) or -//! 1023 (14 bit) and whose darkest 0.01 % sat at a quarter of the black level of maker note `0x003d` (63 against -//! 252 in 12-bit units); with the first-interval step they sit at that black level. -//! - Values in the maker note are in the maker note's byte order (newer bodies write little-endian notes). -//! -//! "Lossy after split" (non-zero split row at `0x0096` offset 562, type 2 tables only, found in 11 of the CC0 -//! samples): derived by black-box analysis of those files. Rows below the split row use the lossy Huffman path -//! above unchanged. Row `split` starts at the very next bit (no alignment); from there every pixel is a word of -//! `bits - 4` bits (8 at 12 bit, 10 at 14 bit), MSB first, with no row padding. A word is a complete prefix code -//! for a difference category `n` followed by the top `W - prefix length` bits of the T.81 additional bits (the low -//! bits are dropped); the difference is the centre of the magnitude bin that was kept. The predictor is the same -//! as above and the running value is not clamped (only the sample index is, before the curve lookup). The camera -//! ends the strip with 0 to 7 one-bits after the last full row, which the decoder checks. -//! -//! Not supported (returned as [`RawError::Unsupported`], the embedded preview is used instead): -//! - "Lossy after split" files whose fixed-rate section does not end within the last byte of the strip (see -//! below): refused rather than decoded wrongly. -//! - Other `0x0096` versions, bit depths other than 12/14. -//! - Code words that never occurred in any sample (the lossy 12-bit 8-bit code word `11111110`, and code words -//! longer than 9 bits in the lossy tables) are rejected as corrupt; they cannot code a difference within the -//! lossy value range anyway. - -use super::pef::{Bits, Huffman, diff}; -use crate::{MAX_SAMPLES, RawError, Result}; -use craft_tiff::ByteOrder; - -/// A table code word whose symbol was never observed (see the module docs). -const UNSEEN: u8 = u8::MAX; - -/// Canonical Huffman table: number of codes of length 1..=16 and the symbols (difference categories) in code order. -struct Table { - counts: &'static [u8], - symbols: &'static [u8], -} - -const LOSSLESS_12: Table = Table { counts: &[0, 1, 4, 2, 3, 1, 2], symbols: &[5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12] }; -const LOSSLESS_14: Table = Table { counts: &[0, 1, 4, 2, 2, 3, 1, 2], symbols: &[7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14] }; -const LOSSY_12: Table = Table { counts: &[0, 1, 5, 1, 1, 1, 1, 1, 1], symbols: &[5, 4, 3, 6, 2, 7, 1, 0, 8, 9, UNSEEN, 10] }; -const LOSSY_14: Table = Table { counts: &[0, 1, 4, 3, 1, 1, 1, 1, 1], symbols: &[5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12] }; - -impl Table { - /// `(left-aligned 12-bit code, length)` per symbol, for [`Huffman::new`]. - fn codes(&self) -> Vec<(u16, u8)> { - let mut out = vec![(0u16, 0u8); 17]; - let mut code = 0u32; - let mut symbols = self.symbols.iter(); - for (i, &n) in self.counts.iter().enumerate() { - let len = i as u32 + 1; - for _ in 0..n { - if let Some(&s) = symbols.next() - && let Some(slot) = out.get_mut(s as usize) - { - *slot = ((code << (12 - len)) as u16, len as u8); - } - code += 1; - } - code <<= 1; - } - out - } -} - -/// How the decoded values map to samples. -#[derive(Clone, Debug, PartialEq)] -pub(crate) enum Encoding { - /// The decoded values are the samples (`0..2^bits`). - Lossless, - /// The decoded values index this curve. - Lossy(Vec), -} - -/// Maker note `0x0096` (NEF linearization table), parsed. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct DecodeTable { - pub encoding: Encoding, - /// Predictor seeds `[row parity][column]`. - pub seeds: [[i32; 2]; 2], - /// First row of the fixed-rate section ("lossy after split"), 0 when the whole strip is Huffman coded. - pub split: usize, -} - -/// Parse maker note `0x0096` for a `bits`-bit image. `order` is the maker note's byte order. -pub(crate) fn parse_table(t: &[u8], order: ByteOrder, bits: u32) -> Result { - let u16_at = |o: usize| t.get(o..o + 2).and_then(|s| <[u8; 2]>::try_from(s).ok()).map(|b| order.u16(b)); - let short = || RawError::Corrupt(format!("NEF: linearization table too short ({} bytes)", t.len())); - if bits != 12 && bits != 14 { - return Err(RawError::Unsupported(format!("Nikon compressed NEF with {bits}-bit samples"))); - } - let (v0, v1) = (t.first().copied().ok_or_else(short)?, t.get(1).copied().ok_or_else(short)?); - let mut seeds = [[0i32; 2]; 2]; - for (i, s) in seeds.iter_mut().flatten().enumerate() { - *s = u16_at(2 + 2 * i).ok_or_else(short)? as i32; - } - let mut split = 0; - let encoding = match (v0, v1) { - (0x46, _) => Encoding::Lossless, - (0x44, 0x10 | 0x20 | 0x40) => { - let n = u16_at(10).ok_or_else(short)? as usize; - let points: Vec = (0..n).map(|i| u16_at(12 + 2 * i)).collect::>().ok_or_else(short)?; - if n < 2 { - return Err(RawError::Corrupt(format!("NEF: linearization curve of {n} points"))); - } - if v1 == 0x10 { - Encoding::Lossy(points) - } else { - split = u16_at(562).unwrap_or(0) as usize; - // type 2: `n` points covering `range` codes, one every `range / (n - 1)`; the curve's first interval - // rises by exactly that step (identity in the dark part) and the table version sets the span: - // `0x20` covers all 2^bits codes, `0x40` the first quarter (see the module docs) - let range = if v1 == 0x40 { 1usize << (bits - 2) } else { 1usize << bits }; - if n - 1 > range || !range.is_multiple_of(n - 1) { - return Err(RawError::Unsupported(format!("NEF: {n}-point lossy curve for {bits}-bit data"))); - } - let step = range / (n - 1); - let mut curve = Vec::with_capacity(range + 1); - for pair in points.windows(2) { - let &[a, b] = pair else { continue }; - let (a, b) = (a as u32, b as u32); - for k in 0..step as u32 { - let s = step as u32; - curve.push(((a * (s - k) + b * k) / s) as u16); - } - } - curve.extend(points.last().copied()); - Encoding::Lossy(curve) - } - } - _ => return Err(RawError::Unsupported(format!("Nikon compressed NEF version {v0:#04x} {v1:#04x}"))), - }; - Ok(DecodeTable { encoding, seeds, split }) -} - -/// Difference-category prefix codes of the fixed-rate section: `(prefix bits, prefix length, category n)`. -/// A word of `W` bits is a prefix followed by `W - length` bits of the T.81 additional bits of category `n`. -/// (The 14-bit `010` = category 12 never occurs in the samples; its category is deduced.) -const FIXED_12: &[(u32, u32, u32)] = &[ - (0b00, 2, 9), - (0b010, 3, 10), - (0b011, 3, 8), - (0b100, 3, 7), - (0b101, 3, 6), - (0b110, 3, 5), - (0b1110, 4, 4), - (0b11110, 5, 3), - (0b111110, 6, 2), - (0b1111110, 7, 1), - (0b11111110, 8, 0), -]; -const FIXED_14: &[(u32, u32, u32)] = &[ - (0b00, 2, 8), - (0b010, 3, 12), - (0b011, 3, 11), - (0b100, 3, 10), - (0b101, 3, 9), - (0b110, 3, 7), - (0b1110, 4, 6), - (0b11110, 5, 5), - (0b111110, 6, 4), - (0b1111110, 7, 3), - (0b11111110, 8, 2), - (0b111111110, 9, 1), - (0b1111111110, 10, 0), -]; - -/// Word (`bits - 4` bits) to dequantised difference for the fixed-rate section; `None` marks the unused all-ones word. -fn fixed_word_table(bits: u32) -> Vec> { - let (w, codes) = if bits == 12 { (8, FIXED_12) } else { (10, FIXED_14) }; - let mut lut = vec![None; 1usize << w]; - for &(prefix, len, n) in codes { - let kept = w - len; - for m in 0..1u32 << kept { - let e = n.saturating_sub(kept); - let ex = (m << e) as i32; - let half = (1i32 << e) >> 1; - let d = if n == 0 { - 0 - } else if ex >= 1 << (n - 1) { - ex + half - } else if e > 0 { - ex + half - (1 << n) - } else { - ex - ((1 << n) - 1) - }; - if let Some(slot) = lut.get_mut(((prefix << kept) | m) as usize) { - *slot = Some(d); - } - } - } - lut -} - -/// Decode a whole `w × h` Nikon Huffman-compressed strip `src` with `bits`-bit samples. -#[cfg(test)] -pub(crate) fn decode(src: &[u8], w: usize, h: usize, bits: u32, table: &DecodeTable) -> Result> { - decode_rows(src, w, h, h, bits, table) -} - -/// The first `rows` rows (`w × rows` samples) of a `w × h` strip. The stream is sequential, so a header-only probe -/// decodes just the rows its masked-column test looks at (issue #708) instead of the whole image. The size and -/// truncation checks still cover the whole image; the "lossy after split" end-of-strip rule (and corruption -/// further down) can only be seen when the whole strip is decoded. -pub(crate) fn decode_rows(src: &[u8], w: usize, h: usize, rows: usize, bits: u32, table: &DecodeTable) -> Result> { - if bits != 12 && bits != 14 { - return Err(RawError::Unsupported(format!("Nikon compressed NEF with {bits}-bit samples"))); - } - let whole = w.checked_mul(h).filter(|&n| n > 0 && n <= MAX_SAMPLES).ok_or(RawError::Limit("NEF image size"))?; - // every code word is at least 2 bits long: a strip that can't hold the image is truncated (also bounds the - // allocation by the file size) - if whole / 4 > src.len() { - return Err(RawError::Corrupt(format!("NEF: {} bytes of compressed data for {w}x{h} pixels", src.len()))); - } - let rows = rows.min(h); - let n = w.saturating_mul(rows); - let huff = Huffman::new( - &match (&table.encoding, bits) { - (Encoding::Lossless, 12) => LOSSLESS_12, - (Encoding::Lossless, _) => LOSSLESS_14, - (Encoding::Lossy(_), 12) => LOSSY_12, - (Encoding::Lossy(_), _) => LOSSY_14, - } - .codes(), - )?; - let (lut, max): (&[u16], i32) = match &table.encoding { - Encoding::Lossless => (&[], (1i32 << bits) - 1), - Encoding::Lossy(curve) => (curve, curve.len() as i32 - 1), - }; - if table.split != 0 && table.split >= h { - return Err(RawError::Corrupt(format!("NEF: split row {} outside the {h} rows", table.split))); - } - let fixed = if table.split != 0 { fixed_word_table(bits) } else { Vec::new() }; - let word = bits - 4; - let mut out = vec![0u16; n]; - let mut stream = Bits::new(src); - let mut vpred = table.seeds; - let mut clipped = 0usize; - for (y, row) in out.chunks_exact_mut(w).enumerate() { - let seeds = vpred.get_mut(y & 1).ok_or(RawError::Limit("NEF row"))?; - let mut hpred = [0i32; 2]; - for (x, o) in row.iter_mut().enumerate() { - let d = if table.split != 0 && y >= table.split { - let code = stream.get(word) as usize; - fixed.get(code).copied().flatten().ok_or_else(|| RawError::Corrupt(format!("NEF: invalid fixed-rate word at row {y}")))? - } else { - diff(&mut stream, &huff).ok_or_else(|| RawError::Corrupt(format!("NEF: invalid Huffman code at row {y}")))? - }; - // a run of large differences in a corrupt stream can drive a predictor past i32 (issue #1515) - let overflow = || RawError::Corrupt(format!("NEF: predictor out of range at row {y}")); - let p = if x < 2 { - let s = seeds.get_mut(x).ok_or(RawError::Limit("NEF column"))?; - *s = s.checked_add(d).ok_or_else(overflow)?; - hpred[x & 1] = *s; - *s - } else { - let p = hpred[x & 1].checked_add(d).ok_or_else(overflow)?; - hpred[x & 1] = p; - p - }; - let v = p.clamp(0, max); - clipped += (v != p && (table.split == 0 || y < table.split)) as usize; - *o = if lut.is_empty() { v as u16 } else { lut.get(v as usize).copied().unwrap_or(0) }; - } - // the camera pads the strip; reading more than a few bytes past its end means truncated or corrupt data - if stream.consumed_bits() > src.len() * 8 + 64 { - return Err(RawError::Corrupt(format!("NEF: compressed data ends at row {y} of {h}"))); - } - } - if table.split != 0 && rows == h { - // the fixed-rate section must fill the rest of the strip: whole rows of w words and 0..7 bits of padding. - // A strip may hold a few more rows than the image (one body stores 4022 rows for 4020); anything else means - // the file does not follow the rule, so refuse it instead of decoding it wrongly. - let left = (src.len() * 8).checked_sub(stream.consumed_bits()); - let row_bits = w * word as usize; - if !left.is_some_and(|l| l % row_bits < 8 && l / row_bits <= 4) { - return Err(RawError::Unsupported(format!( - "Nikon \"lossy after split\" NEF whose fixed-rate section (from row {}) does not end within the last byte", - table.split - ))); - } - } - // a wrong table / corrupt stream drifts out of range quickly; real files stay inside (a handful of edge pixels) - if clipped > n / 1000 + 16 { - return Err(RawError::Corrupt(format!("NEF: {clipped} decoded values out of range"))); - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// MSB-first bit writer for the test encoder. - #[derive(Default)] - struct Writer { - out: Vec, - acc: u64, - n: u32, - } - - impl Writer { - fn put(&mut self, v: u32, len: u32) { - for i in (0..len).rev() { - self.acc = (self.acc << 1) | ((v >> i) & 1) as u64; - self.n += 1; - if self.n == 8 { - self.out.push(self.acc as u8); - self.acc = 0; - self.n = 0; - } - } - } - fn finish(mut self) -> Vec { - if self.n > 0 { - self.out.push((self.acc << (8 - self.n)) as u8); - } - self.out.extend_from_slice(&[0; 4]); - self.out - } - } - - fn category(d: i32) -> u32 { - 32 - d.unsigned_abs().leading_zeros() - } - - /// Encode `values` (decoded domain: samples or curve indices) the way the camera does. - fn encode(values: &[i32], w: usize, table: &Table, seeds: [[i32; 2]; 2]) -> Vec { - let codes = table.codes(); - let mut wr = Writer::default(); - let mut vpred = seeds; - for (y, row) in values.chunks(w).enumerate() { - for (x, &v) in row.iter().enumerate() { - let pred = if x < 2 { vpred[y & 1][x] } else { row[x - 2] }; - if x < 2 { - vpred[y & 1][x] = v; - } - let d = v - pred; - let k = category(d); - let (code, len) = codes[k as usize]; - assert!(len > 0, "no code for category {k}"); - wr.put(code as u32 >> (12 - len), len as u32); - let extra = if d < 0 { d + (1 << k) - 1 } else { d }; - wr.put(extra as u32, k); - } - } - wr.finish() - } - - /// Deterministic test image: smooth gradient + texture + hard edges, within `0..=max`. - fn image(w: usize, h: usize, max: i32, seed: u32) -> Vec { - let mut s = seed; - (0..w * h) - .map(|i| { - let (x, y) = ((i % w) as i32, (i / w) as i32); - s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let noise = (s >> 24) as i32 % 9 - 4; - let base = (x * 37 + y * 11) % (max / 2) + if (x / 7 + y / 5) % 3 == 0 { max / 3 } else { 0 }; - (base + noise).clamp(0, max) - }) - .collect() - } - - fn lossless(bits: u32) -> DecodeTable { - let s = 1 << (bits - 3); - DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]], split: 0 } - } - - #[test] - fn tables_are_complete_prefix_codes() { - for t in [LOSSLESS_12, LOSSLESS_14, LOSSY_12, LOSSY_14] { - assert_eq!(t.counts.iter().map(|&c| c as usize).sum::(), t.symbols.len()); - let kraft: f64 = t.counts.iter().enumerate().map(|(i, &c)| c as f64 / (1u64 << (i + 1)) as f64).sum(); - assert!(kraft <= 1.0); - assert!(Huffman::new(&t.codes()).is_ok()); - } - assert_eq!(LOSSLESS_14.codes()[7], (0b00 << 10, 2)); - assert_eq!(LOSSLESS_14.codes()[0], (0b111110 << 6, 6)); - assert_eq!(LOSSY_12.codes()[10], (0b111111110 << 3, 9)); - } - - #[test] - fn lossless_roundtrip_12_and_14() { - for (bits, table) in [(12, LOSSLESS_12), (14, LOSSLESS_14)] { - let (w, h) = (64, 9); - let max = (1 << bits) - 1; - let mut img = image(w, h, max, bits); - // extreme jumps exercise the longest categories - img[5] = 0; - img[7] = max; - img[w + 9] = max; - let t = lossless(bits); - let src = encode(&img, w, &table, t.seeds); - let out = decode(&src, w, h, bits, &t).unwrap(); - assert_eq!(out, img.iter().map(|&v| v as u16).collect::>(), "{bits}-bit"); - } - } - - fn lossy_table(bits: u32, order: ByteOrder) -> Vec { - // version 0x44 0x20, seeds, 257 points of a concave curve, padding up to the split value (0) - let mut t = vec![0x44, 0x20]; - let put = |t: &mut Vec, v: u16| t.extend_from_slice(&if order == ByteOrder::Big { v.to_be_bytes() } else { v.to_le_bytes() }); - for _ in 0..4 { - put(&mut t, 300); - } - put(&mut t, 257); - let max = ((1u32 << bits) - 1) as f64; - for i in 0..257u32 { - put(&mut t, (max * (i as f64 / 64.0).min(1.0).sqrt()) as u16); - } - t.resize(624, 0); - t - } - - #[test] - fn lossy_type2_curve_and_roundtrip() { - for (bits, table) in [(12u32, LOSSY_12), (14, LOSSY_14)] { - for order in [ByteOrder::Big, ByteOrder::Little] { - let t = parse_table(&lossy_table(bits, order), order, bits).unwrap(); - assert_eq!(t.seeds, [[300, 300], [300, 300]]); - let Encoding::Lossy(curve) = &t.encoding else { panic!() }; - let step = (1usize << bits) / 256; - assert_eq!(curve.len(), (1 << bits) + 1); - assert_eq!(curve[64 * step], (1 << bits) - 1); - assert!(curve.windows(2).all(|p| p[0] <= p[1])); - // the encoded range is the curve's rising part - let (w, h) = (48, 7); - let img = image(w, h, 64 * step as i32 - 1, 7); - let src = encode(&img, w, &table, t.seeds); - let out = decode(&src, w, h, bits, &t).unwrap(); - assert_eq!(out, img.iter().map(|&v| curve[v as usize]).collect::>()); - } - } - } - - /// Maker note `0x0096` as bytes, written out by hand: version `0x44 `, four seeds, 257 points (little-endian - /// as newer bodies write it) of a curve whose first 256 points rise by `step` and whose last is the white - /// level, and a zero split value at offset 562. - fn hand_table(v1: u8, seed: u16, step: u16, white: u16) -> Vec { - let mut t = vec![0x44, v1]; - for _ in 0..4 { - t.extend_from_slice(&seed.to_le_bytes()); - } - t.extend_from_slice(&257u16.to_le_bytes()); - for k in 0..256u16 { - t.extend_from_slice(&(k * step).to_le_bytes()); - } - t.extend_from_slice(&white.to_le_bytes()); - t.resize(624, 0); - t - } - - /// Known answers for the `0x44 0x40` curve, from bytes and bit strings written by hand (nothing here uses the - /// decoder's span rule or the test encoder): the first interval of the points rises by `2^bits / 1024`, so - /// the curve is the identity for one code per sample and spans `2^bits / 4` codes. The `0x20` curve of the - /// same sizes keeps its span of all `2^bits` codes. - #[test] - fn lossy_type2_version_0x40_spans_a_quarter_of_the_range() { - // 12 bit: points 0, 4, 8 … 1020, 4095 - let t = parse_table(&hand_table(0x40, 252, 4, 4095), ByteOrder::Little, 12).unwrap(); - let Encoding::Lossy(curve) = &t.encoding else { panic!() }; - assert_eq!(curve.len(), 1025); - assert_eq!(curve[0..6], [0, 1, 2, 3, 4, 5]); - assert_eq!((curve[252], curve[255], curve[1020]), (252, 255, 1020)); - assert_eq!((curve[1021], curve[1022], curve[1023], curve[1024]), (1788, 2557, 3326, 4095)); - // the pixels p0 = 252 + 4, p1 = 252, p2 = p0 - 1, p3 = p1, coded as 011 100 | 11110 | 1110 0 | 11110 - // (LOSSY_12: category 3 = 011, 0 = 11110, 1 = 1110; extra bits 100 = +4, 0 = -1) - let out = decode(&[0x73, 0xdc, 0xf0], 4, 1, 12, &t).unwrap(); - assert_eq!(out, [256, 252, 255, 252]); - // 14 bit: points 0, 16, 32 … 4080, 16383 - let t = parse_table(&hand_table(0x40, 1008, 16, 16383), ByteOrder::Little, 14).unwrap(); - let Encoding::Lossy(curve) = &t.encoding else { panic!() }; - assert_eq!(curve.len(), 4097); - assert_eq!(curve[0..6], [0, 1, 2, 3, 4, 5]); - assert_eq!((curve[1008], curve[4080], curve[4096]), (1008, 4080, 16383)); - // the same pixels coded as 1100 100 | 111110 | 11110 0 | 111110 - // (LOSSY_14: category 3 = 1100, 0 = 111110, 1 = 11110) - let out = decode(&[0xc9, 0xf7, 0x9f, 0x00], 4, 1, 14, &t).unwrap(); - assert_eq!(out, [1012, 1008, 1011, 1008]); - // version 0x20 with the same points is a curve over all 2^bits codes: the points are 16 codes apart - let t = parse_table(&hand_table(0x20, 252, 16, 4095), ByteOrder::Little, 12).unwrap(); - let Encoding::Lossy(curve) = &t.encoding else { panic!() }; - assert_eq!((curve.len(), curve[16], curve[17], curve[4095]), (4097, 16, 17, 4094)); - // 200 points can't be spaced evenly over the 1024 codes of a 12-bit 0x40 table - let mut odd = hand_table(0x40, 252, 4, 4095); - odd[10..12].copy_from_slice(&200u16.to_le_bytes()); - assert!(parse_table(&odd, ByteOrder::Little, 12).is_err()); - } - - /// Pack a string of `0`/`1` (spaces ignored) MSB first, padding the last byte with one-bits like the camera. - fn pack(bits: &str) -> Vec { - let b: Vec = bits.chars().filter(|c| !c.is_whitespace()).map(|c| c == '1').collect(); - b.chunks(8).map(|c| (0..8).fold(0u8, |a, i| (a << 1) | c.get(i).copied().unwrap_or(true) as u8)).collect() - } - - fn split_table(v1: u8, seed: u16, step: u16, white: u16, split: u16) -> DecodeTable { - let mut t = hand_table(v1, seed, step, white); - t[562..564].copy_from_slice(&split.to_le_bytes()); - parse_table(&t, ByteOrder::Little, if step == 4 { 12 } else { 14 }).unwrap() - } - - /// 12-bit "lossy after split": row 0 Huffman coded, rows 1 and 2 as 8-bit words that follow the last Huffman - /// bit directly. Bit strings written by hand from the rule (prefix, then the kept top bits of the extra bits). - const SPLIT_12: &str = "011 100 11110 1110 0 11110 11111110 11110100 11100111 01110000 00000001 11111110 01111111 11111110"; - - #[test] - fn lossy_after_split_known_answers_12_bit() { - let t = split_table(0x40, 252, 4, 4095, 1); - assert_eq!(t.split, 1); - let out = decode(&pack(SPLIT_12), 4, 3, 12, &t).unwrap(); - // row 1: d = 0 (n0), +4 (n3, exact), -8 (n4, exact), +132 (n8 keeps 5 bits: 16 << 3 plus half a bin, 4); - // row 2: -500 (n9 keeps 6 bits: bin 1 of the negative side, centre -508 + 8), then +252 on the running - // value -244 which is not clamped (8, not 252) - assert_eq!(out, [256, 252, 255, 252, 252, 256, 244, 388, 0, 252, 8, 252]); - } - - #[test] - fn lossy_after_split_known_answers_14_bit() { - let t = split_table(0x40, 1008, 16, 16383, 1); - // row 0 as in the 0x40 test above; row 1 in 10-bit words: 0 (n0), +32 (n6, exact), -254 (n8, exact), - // +510 (n9 keeps 7 bits: 127 << 2 plus 2) - let bits = "1100 100 111110 11110 0 111110 1111111110 1110100000 0000000001 1011111111"; - let out = decode(&pack(bits), 4, 2, 14, &t); - // word 3 is `00` + 8 bits: 00 00000001 -> n8 extra 00000001 = -254 - assert_eq!(out.unwrap(), [1012, 1008, 1011, 1008, 1008, 1040, 754, 1550]); - } - - #[test] - fn lossy_after_split_dequantisation_is_symmetric() { - let lut = fixed_word_table(12); - assert_eq!((lut[0b00_000000], lut[0b00_111111]), (Some(-508), Some(508))); - assert_eq!((lut[0b011_00000], lut[0b011_11111]), (Some(-252), Some(252))); - assert_eq!(lut[0b11111110], Some(0)); - assert_eq!(lut[0xff], None); - let lut = fixed_word_table(14); - assert_eq!((lut[0b00_00000000], lut[0b00_11111111]), (Some(-255), Some(255))); - assert_eq!(lut[0b101_0000000], Some(-510)); - assert_eq!(lut[0b1111111110], Some(0)); - assert_eq!(lut[0x3ff], None); - for bits in [12, 14] { - let lut = fixed_word_table(bits); - assert_eq!(lut.iter().filter(|d| d.is_none()).count(), 1, "{bits}-bit: only the all-ones word is unused"); - } - } - - #[test] - fn lossy_after_split_refuses_strips_that_do_not_follow_the_rule() { - let t = split_table(0x40, 252, 4, 4095, 1); - let mut longer = pack(SPLIT_12); - longer.extend_from_slice(&[0xff; 3]); - assert!(matches!(decode(&longer, 4, 3, 12, &t), Err(RawError::Unsupported(_)))); - let shorter = &pack(SPLIT_12)[..10]; - assert!(decode(shorter, 4, 3, 12, &t).is_err()); - // the unused all-ones word - let bad = pack("011 100 11110 1110 0 11110 11111111 11111110 11111110 11111110"); - assert!(matches!(decode(&bad, 4, 2, 12, &t), Err(RawError::Corrupt(_)))); - // a split row beyond the image - assert!(matches!(decode(&pack(SPLIT_12), 4, 1, 12, &t), Err(RawError::Corrupt(_)))); - // through the container - let mut table = hand_table(0x40, 252, 4, 4095); - table[562..564].copy_from_slice(&1u16.to_le_bytes()); - let ok = crate::decode(&nef_file(pack(SPLIT_12), 4, 3, 12, table.clone(), ByteOrder::Little)).unwrap(); - assert_eq!(ok.data, crate::RawData::U16(vec![256, 252, 255, 252, 252, 256, 244, 388, 0, 252, 8, 252])); - let e = crate::decode(&nef_file(longer, 4, 3, 12, table, ByteOrder::Little)); - assert!(matches!(e, Err(RawError::Unsupported(_))), "{e:?}"); - } - - #[test] - fn lossy_type1_full_curve() { - let mut t = vec![0x44, 0x10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 5]; - for v in [0u16, 100, 400, 900, 1600] { - t.extend_from_slice(&v.to_be_bytes()); - } - let parsed = parse_table(&t, ByteOrder::Big, 12).unwrap(); - assert_eq!(parsed.encoding, Encoding::Lossy(vec![0, 100, 400, 900, 1600])); - let img = vec![0, 4, 1, 3, 2, 2, 4, 0]; - let src = encode(&img, 4, &LOSSY_12, parsed.seeds); - assert_eq!(decode(&src, 4, 2, 12, &parsed).unwrap(), vec![0, 1600, 100, 900, 400, 400, 1600, 0]); - } - - #[test] - fn rejects_unsupported_and_malformed_tables() { - let unsupported = |r: Result| matches!(r, Err(RawError::Unsupported(_))); - let corrupt = |r: Result| matches!(r, Err(RawError::Corrupt(_))); - let mut split = lossy_table(12, ByteOrder::Big); - split[562..564].copy_from_slice(&345u16.to_be_bytes()); - assert_eq!(parse_table(&split, ByteOrder::Big, 12).unwrap().split, 345); - assert!(unsupported(parse_table(&[0x49, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ByteOrder::Big, 12))); - assert!(unsupported(parse_table(&lossy_table(12, ByteOrder::Big), ByteOrder::Big, 16))); - assert!(corrupt(parse_table(&[], ByteOrder::Big, 12))); - assert!(corrupt(parse_table(&[0x46, 0x30, 8], ByteOrder::Big, 14))); - assert!(corrupt(parse_table(&lossy_table(12, ByteOrder::Big)[..100], ByteOrder::Big, 12))); - // 300 points don't divide the 12-bit range - let mut odd = lossy_table(12, ByteOrder::Big); - odd[10..12].copy_from_slice(&300u16.to_be_bytes()); - assert!(parse_table(&odd, ByteOrder::Big, 12).is_err()); - assert!(parse_table(&[0x44, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], ByteOrder::Big, 12).is_err()); - } - - /// A minimal NEF: CFA SubIFD with one compressed strip, Exif maker note (`Nikon\0` v2 header + embedded TIFF in - /// `mn_order`) holding the linearization table. - fn nef_file(strip: Vec, w: u32, h: u32, bits: u16, table: Vec, mn_order: ByteOrder) -> Vec { - use craft_tiff::tags::{self as t, photometric}; - use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; - let mut mn = IfdBuilder::new(); - mn.set(0x0096, Value::Undefined(table)); - let mut note = b"Nikon\0\x02\x10\0\0".to_vec(); - note.extend(TiffWriter::new(mn_order, false).write(&[mn]).unwrap()); - let mut exif = IfdBuilder::new(); - exif.set(t::MAKER_NOTE, Value::Undefined(note)); - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![bits])); - raw.set(t::COMPRESSION, Value::Short(vec![t::compression::NIKON])); - raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); - raw.set_image(ImageData::Strips { rows_per_strip: h, strips: vec![strip] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("NIKON CORPORATION".into())); - ifd0.set(t::MODEL, Value::Ascii("NIKON TEST".into())); - ifd0.set_child(t::EXIF_IFD, exif); - ifd0.add_sub_ifd(raw); - TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap() - } - - #[test] - fn decodes_through_the_nef_container() { - // lossless 14-bit, big-endian maker note - let (w, h) = (40usize, 6usize); - let img = image(w, h, 16383, 11); - let mut table = vec![0x46, 0x30]; - for _ in 0..4 { - table.extend_from_slice(&2048u16.to_be_bytes()); - } - table.resize(46, 0); - let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); - let bytes = nef_file(src, w as u32, h as u32, 14, table, ByteOrder::Big); - let r = crate::decode(&bytes).unwrap(); - assert_eq!(r.data, crate::RawData::U16(img.iter().map(|&v| v as u16).collect())); - assert_eq!(r.cfa.as_ref().unwrap().name(), "RGGB"); - assert_eq!(crate::probe_info(&bytes).unwrap(), r.info()); - // lossy 12-bit type 2, little-endian maker note (newer bodies) - let table = lossy_table(12, ByteOrder::Little); - let t = parse_table(&table, ByteOrder::Little, 12).unwrap(); - let Encoding::Lossy(curve) = &t.encoding else { panic!() }; - let img = image(w, h, 1023, 5); - let src = encode(&img, w, &LOSSY_12, t.seeds); - let r = crate::decode(&nef_file(src.clone(), w as u32, h as u32, 12, table.clone(), ByteOrder::Little)).unwrap(); - assert_eq!(r.data, crate::RawData::U16(img.iter().map(|&v| curve[v as usize]).collect())); - // a split file whose strip does not follow the fixed-rate rule is refused, never decoded wrongly - let mut split = table; - split[562..564].copy_from_slice(&3u16.to_le_bytes()); - let e = crate::decode(&nef_file(src, w as u32, h as u32, 12, split, ByteOrder::Little)); - assert!(e.is_err(), "{e:?}"); - } - - /// Issue #708: the header probe of a compressed NEF decodes only the first [`super::super::nef::MASK_ROWS`] - /// rows (the ones the masked-column test reads) instead of the whole Huffman stream, and still finds the masked - /// columns the full decode finds. A strip cut off after those rows proves it: the probe succeeds with the same - /// description while the full decode reports the truncation. - #[test] - fn header_probe_stops_after_the_masked_column_rows() { - use super::super::nef::MASK_ROWS; - let (w, h) = (160usize, MASK_ROWS * 3); - let mut img = image(w, h, 16383, 7); - // eight optically masked columns at 0, as the D5100 / D7000 write them - for row in img.chunks_mut(w) { - row[w - 8..].fill(0); - } - let t = lossless(14); - let table = { - let mut v = vec![0x46, 0x30]; - for s in t.seeds.iter().flatten() { - v.extend_from_slice(&(*s as u16).to_be_bytes()); - } - v.resize(46, 0); - v - }; - let src = encode(&img, w, &LOSSLESS_14, t.seeds); - let whole = nef_file(src.clone(), w as u32, h as u32, 14, table.clone(), ByteOrder::Big); - let full = crate::decode(&whole).unwrap(); - assert_eq!(full.active_area, crate::Rect::new(0, 0, w - 8, h), "the masked columns are found in a compressed file"); - assert_eq!(crate::probe_info(&whole).unwrap(), full.info()); - // the same stream cut off after two thirds of the rows (the first rows' codes are a prefix of the whole) - let cut = encode(&img[..w * (h * 2 / 3)], w, &LOSSLESS_14, t.seeds).len(); - assert!(cut > w * h / 4, "enough bytes to pass the size check"); - let truncated = nef_file(src[..cut].to_vec(), w as u32, h as u32, 14, table, ByteOrder::Big); - assert!(matches!(crate::decode(&truncated), Err(RawError::Corrupt(_))), "the full decode sees the truncation"); - assert_eq!(crate::probe_info(&truncated).unwrap(), full.info(), "the header probe never reads that far"); - // decode_rows itself: a prefix of the whole decode, and the whole image's size check still applies - let top = decode_rows(&src, w, h, MASK_ROWS, 14, &t).unwrap(); - assert_eq!(top.len(), w * MASK_ROWS); - assert_eq!(top[..], decode(&src, w, h, 14, &t).unwrap()[..w * MASK_ROWS]); - assert_eq!(decode_rows(&src, w, h, h + 5, 14, &t).unwrap().len(), w * h, "rows are clamped to the height"); - assert!(decode_rows(&src[..w * h / 4 - 1], w, h, 1, 14, &t).is_err(), "a strip too short for the image is corrupt in any mode"); - } - - /// A long run of the largest difference drove a predictor past i32: a panic in builds with overflow checks, - /// wrapped values otherwise (issue #1515). Both the row and the column predictors now stop with an error. - #[test] - fn predictor_overflow_is_an_error_not_a_panic() { - let codes = LOSSLESS_14.codes(); - let k = (0..codes.len()).rev().find(|&k| codes[k].1 > 0).unwrap(); - let d = (1u32 << k) - 1; - let stream = |n: usize| { - let mut wr = Writer::default(); - let (code, len) = codes[k]; - for _ in 0..n { - wr.put(code as u32 >> (12 - len), len as u32); - wr.put(d, k as u32); - } - wr.finish() - }; - // differences one predictor needs to pass i32::MAX - let steps = (i32::MAX as u32 / d) as usize + 2; - let table = DecodeTable { encoding: Encoding::Lossless, seeds: [[0; 2]; 2], split: 0 }; - // along a row: every other sample adds to the same predictor - let w = 2 * steps + 2; - let err = decode(&stream(w), w, 1, 14, &table).unwrap_err(); - assert!(matches!(err, RawError::Corrupt(ref m) if m.contains("predictor")), "{err}"); - // down two columns: each row adds to the seed of its parity - let h = 2 * steps + 2; - let err = decode(&stream(2 * h), 2, h, 14, &table).unwrap_err(); - assert!(matches!(err, RawError::Corrupt(ref m) if m.contains("predictor")), "{err}"); - } - - #[test] - fn truncated_and_corrupted_streams_error_never_panic() { - let (w, h) = (64, 16); - let t = lossless(14); - let img = image(w, h, 16383, 3); - let src = encode(&img, w, &LOSSLESS_14, t.seeds); - // truncation: too short for the image, or ends early - for cut in [0, 1, 10, src.len() / 2, src.len() - 40] { - assert!(decode(&src[..cut], w, h, 14, &t).is_err(), "cut {cut}"); - } - // garbage and bit flips: an error or (rarely) some image, never a panic - let mut s = 12345u32; - for i in 0..200 { - let mut bad = src.clone(); - for _ in 0..1 + i % 8 { - s = s.wrapping_mul(1_103_515_245).wrapping_add(12345); - let at = (s >> 8) as usize % bad.len(); - bad[at] ^= 1 << (s % 8); - } - let _ = decode(&bad, w, h, 14, &t); - let noise: Vec = (0..src.len()).map(|k| ((k as u32).wrapping_mul(2_654_435_761) >> (i % 24)) as u8).collect(); - let _ = decode(&noise, w, h, 14, &t); - let _ = decode(&noise, w, h, 12, &lossless(12)); - } - // all-ones never forms a valid lossy 12-bit code - assert!(decode(&[0xff; 64], 8, 8, 12, &parse_table(&lossy_table(12, ByteOrder::Big), ByteOrder::Big, 12).unwrap()).is_err()); - // absurd dimensions are limited before allocating - assert!(decode(&src, usize::MAX, 2, 14, &t).is_err()); - assert!(decode(&src, 1 << 20, 1 << 20, 14, &t).is_err()); - assert!(decode(&src, 0, 2, 14, &t).is_err()); - } -} diff --git a/crates/raw/src/vendor/orf.rs b/crates/raw/src/vendor/orf.rs index 78cfdbe54b..b1ce962653 100644 --- a/crates/raw/src/vendor/orf.rs +++ b/crates/raw/src/vendor/orf.rs @@ -152,7 +152,7 @@ pub(crate) fn cfa_from_data(d: &[u16], w: usize, a: Rect) -> Cfa { anti += (s1 - s2).unsigned_abs(); } } - Cfa::bayer_static(if main < anti { "GRBG" } else { "RGGB" }) + crate::bayer(if main < anti { "GRBG" } else { "RGGB" }) } /// Byte offsets of the stored rows of the two-field 12-bit layout, or `None` unless every condition holds diff --git a/crates/raw/src/vendor/pef.rs b/crates/raw/src/vendor/pef.rs deleted file mode 100644 index 466ccdd023..0000000000 --- a/crates/raw/src/vendor/pef.rs +++ /dev/null @@ -1,722 +0,0 @@ -//! Pentax PEF — uncompressed and Pentax Huffman-compressed (compression 65535). -//! -//! Sources: TIFF 6.0 (container), ITU-T T.81 (JPEG) Annex H / F.1.2.1 for the lossless "difference category + -//! additional bits" coding, the ExifTool Pentax tag-name documentation (maker-note `0x0200` BlackPoint, `0x0201` -//! WhitePoint i.e. WB levels, `0x0220` HuffmanTable) and our own black-box analysis of CC0 samples from -//! raw.pixls.us (K10D, K-5 II s, K-3): -//! -//! - The Huffman table is stored in the file (maker note `0x0220`, in the maker note's byte order): a `u16` `d`, -//! 12 further bytes, then `n = d + 12` `u16` codes left-aligned in 12 bits, then `n` code lengths (bytes). -//! Symbol `i` is the difference category `i` (T.81 Table H.2: the number of additional bits). -//! - The bit stream (MSB-first, no byte stuffing, continuous across rows) codes one difference per pixel; the -//! additional bits follow T.81 F.1.2.1 (a leading 0 means a negative value). -//! - Prediction: each pixel is predicted from the previous same-colour pixel in its row (two to the left); the -//! first two pixels of a row are predicted from the first two pixels of the previous row of the same parity -//! (starting at 0). Found by trying candidate predictors and checking the decoded rows are continuous. -//! - Maker note `0x0038`/`0x0039`: the image area's left/top and width/height (verified against the data). - -use super::{black_from_columns, cfa_from_exif, white_from_data}; - -use crate::tiffraw::{Packing, read_image_in}; -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; -use craft_tiff::image::{ImageInfo, chunk_bytes}; -use craft_tiff::{ByteOrder, Tiff, makernote, tags as t}; -use lightcraft_geom::Orientation; - -const CROP_ORIGIN: u16 = 0x0038; -const CROP_SIZE: u16 = 0x0039; -const BLACK_POINT: u16 = 0x0200; -const WB_LEVELS: u16 = 0x0201; -const HUFFMAN: u16 = 0x0220; - -/// A canonical-by-table Huffman decoder with a 12-bit lookup. -pub(crate) struct Huffman { - /// Indexed by the next 12 bits: (symbol, length); length 0 = invalid. - lut: Vec<(u8, u8)>, -} - -impl Huffman { - /// From `(left-aligned 12-bit code, length)` per symbol. - pub fn new(codes: &[(u16, u8)]) -> Result { - let mut lut = vec![(0u8, 0u8); 4096]; - for (sym, &(code, len)) in codes.iter().enumerate() { - if len == 0 { - continue; - } - if len > 12 || sym > 16 { - return Err(RawError::Unsupported(format!("PEF Huffman code of length {len}"))); - } - let first = (code >> (12 - len) << (12 - len)) as usize; - for e in &mut lut[first..first + (1 << (12 - len))] { - if e.1 == 0 { - *e = (sym as u8, len); - } - } - } - Ok(Huffman { lut }) - } -} - -/// MSB-first bit reader that yields zeros past the end. -pub(crate) struct Bits<'a> { - src: &'a [u8], - pos: usize, - acc: u64, - n: u32, -} - -impl<'a> Bits<'a> { - pub fn new(src: &'a [u8]) -> Self { - Bits { src, pos: 0, acc: 0, n: 0 } - } - #[inline] - fn fill(&mut self) { - while self.n <= 56 { - let b = self.src.get(self.pos).copied().unwrap_or(0); - self.pos += 1; - self.acc |= (b as u64) << (56 - self.n); - self.n += 8; - } - } - #[inline] - pub fn peek(&mut self, k: u32) -> u32 { - if self.n < k { - self.fill(); - } - (self.acc >> (64 - k)) as u32 - } - #[inline] - pub fn skip(&mut self, k: u32) { - self.acc <<= k; - self.n -= k; - } - #[inline] - pub fn get(&mut self, k: u32) -> u32 { - if k == 0 { - return 0; - } - let v = self.peek(k); - self.skip(k); - v - } - /// Bits handed out so far (may exceed the source length: zeros are read past its end). - pub fn consumed_bits(&self) -> usize { - self.pos * 8 - self.n as usize - } - /// Whether more bits were handed out than the source holds (the zeros read past its end are lookahead padding, - /// not data; using them would fabricate samples). - pub fn overrun(&self) -> bool { - self.consumed_bits() > self.src.len() * 8 - } -} - -/// Decode one difference: Huffman category then T.81 additional bits. -#[inline] -pub(crate) fn diff(bits: &mut Bits, h: &Huffman) -> Option { - let (sym, len) = h.lut[bits.peek(12) as usize]; - if len == 0 { - return None; - } - bits.skip(len as u32); - let s = sym as u32; - if s == 0 { - return Some(0); - } - if s > 16 { - return None; - } - let v = bits.get(s) as i32; - Some(if v < 1 << (s - 1) { v - (1 << s) + 1 } else { v }) -} - -/// Parse the maker-note Huffman table. -pub(crate) fn table(b: &[u8], order: ByteOrder) -> Result { - let u16_at = |i: usize| b.get(i..i + 2).map(|s| order.u16([s[0], s[1]])); - let d = u16_at(0).ok_or_else(|| RawError::Corrupt("PEF Huffman table too short".into()))? as usize; - let n = d + 12; - if n > 17 || b.len() < 14 + 3 * n { - return Err(RawError::Corrupt(format!("PEF Huffman table: {n} symbols in {} bytes", b.len()))); - } - let codes: Vec<(u16, u8)> = (0..n).map(|i| (u16_at(14 + 2 * i).unwrap_or(0) & 0x0fff, b[14 + 2 * n + i])).collect(); - Huffman::new(&codes) -} - -/// Decode a `w × h` Huffman-coded image. -pub(crate) fn decode_huffman(src: &[u8], h: &Huffman, w: usize, hgt: usize, bits_per: u32) -> Result> { - // every sample takes at least one bit: a stream too short for the declared size is refused before its picture - // is allocated, so a few bytes can't ask for gigabytes (issue #1512) - let samples = w.checked_mul(hgt).ok_or(RawError::Limit("image too large"))?; - if (src.len() as u64).saturating_mul(8) < samples as u64 { - return Err(RawError::Corrupt(format!("PEF: {w} x {hgt} samples need more than the {} bytes of data there", src.len()))); - } - let mut out = vec![0u16; samples]; - let mut bits = Bits::new(src); - let mut vpred = [[0i32; 2]; 2]; - let max = (1i32 << bits_per.min(16)) - 1; - for y in 0..hgt { - let mut hpred = [0i32; 2]; - let row = &mut out[y * w..(y + 1) * w]; - for (x, o) in row.iter_mut().enumerate() { - let d = diff(&mut bits, h).ok_or_else(|| RawError::Corrupt(format!("PEF: invalid Huffman code at row {y}")))?; - // a run of large differences in a corrupt stream can drive a predictor past i32 (issue #1515) - let overflow = || RawError::Corrupt(format!("PEF: predictor out of range at row {y}")); - let p = if x < 2 { - let v = vpred[y & 1][x].checked_add(d).ok_or_else(overflow)?; - vpred[y & 1][x] = v; - hpred[x] = v; - v - } else { - let v = hpred[x & 1].checked_add(d).ok_or_else(overflow)?; - hpred[x & 1] = v; - v - }; - *o = p.clamp(0, max) as u16; - } - if bits.overrun() { - return Err(RawError::Corrupt(format!("PEF: data ends at row {y} of {hgt}"))); - } - } - Ok(out) -} - -/// The image area without leading/trailing lines that hold no picture (masked or empty), kept at even offsets. With -/// the maker-note `black` level, a line is dark when its mean is at most 1/256 of the remaining range (at least 16) -/// above it, the tolerance `cr2::masked_columns` uses: masked lines sit at the black level plus noise, while dark -/// real content (a night sky) is well above. Without it, below 5% of the interior's mean. -fn dark_trimmed(d: &[u16], w: usize, h: usize, black: Option, white: f32) -> Rect { - if w < 256 || h < 256 { - return Rect::new(0, 0, w, h); - } - let (xstep, ystep) = (w / 256, h / 256); - let at = |x: usize, y: usize| d.get(y * w + x).map_or(0.0, |&v| f64::from(v)); - let col_mean = |x: usize| (0..h).step_by(ystep).map(|y| at(x, y)).sum::() / h.div_ceil(ystep) as f64; - let row_mean = |y: usize| (0..w).step_by(xstep).map(|x| at(x, y)).sum::() / w.div_ceil(xstep) as f64; - let interior = (w / 4..w * 3 / 4).step_by(w / 64).map(col_mean).sum::() / 32.0; - let (base, tol) = match black { - Some(b) => (b, ((f64::from(white) - b) / 256.0).max(16.0)), - None => (0.0, interior * 0.05), - }; - // a frame no brighter than masked lines (a lens-cap shot) has nothing to tell them from picture - if interior - base <= tol { - return Rect::new(0, 0, w, h); - } - let range = f64::from(white) - base; - // lines from one edge that hold no picture: within `tol` of the outermost line's level when that sits a little - // above black (K-70, K-1: 65 over BlackPoint), and saturated lines when dark ones follow (645Z) - let run = |mean: &dyn Fn(usize) -> f64| { - let saturated = (0..64).take_while(|&k| mean(k) - base >= range * 0.98).count(); - let outer = mean(saturated) - base; - let level = if outer > 0.0 && outer < range * 0.01 { outer } else { 0.0 }; - match (saturated..64).take_while(|&k| mean(k) - base < level + tol).count() { - 0 => 0, - dark => saturated + dark, - } - }; - let edges = |n: usize, mean: &dyn Fn(usize) -> f64| { - let lo = run(mean).next_multiple_of(2); - let hi = n - run(&|k| mean(n - 1 - k)); - (lo, (hi - lo) & !1) - }; - let (left, width) = edges(w, &col_mean); - let (top, height) = edges(h, &row_mean); - Rect::new(left, top, width, height) -} - -/// Whether every strip or tile of a one-sample-per-pixel image holds exactly the bytes that its rows need when -/// the samples are packed MSB-first at the declared bit depth, rows starting on byte boundaries (TIFF 6.0 -/// section 7). A real PackBits stream of such an image has a different length (almost always shorter), so the -/// exact match is what tells plain samples under a compression tag that says otherwise. -fn is_exactly_packed(info: &ImageInfo, file_len: u64) -> bool { - let bits = u64::from(info.bits()); - if info.samples_per_pixel != 1 || info.planar != 1 || !(1..=16).contains(&bits) || info.byte_counts.len() != info.offsets.len() { - return false; - } - let chunks = info.chunks(file_len); - !chunks.is_empty() && chunks.iter().all(|c| c.len == (u64::from(c.width) * bits).div_ceil(8) * u64::from(c.height)) -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let tiff = Tiff::parse(bytes)?; - let ifd0 = &tiff.ifds[0]; - let info = ifd0.image()?; - let (w, hgt) = (info.width as usize, info.height as usize); - let bits = info.bits() as u32; - if w == 0 || hgt == 0 || w.saturating_mul(hgt) > crate::MAX_SAMPLES { - return Err(RawError::Limit("image too large")); - } - let make = ifd0.string(t::MAKE).unwrap_or_default(); - let mn = - tiff.exif().and_then(|e| e.get(t::MAKER_NOTE)).and_then(|e| makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)); - let pair = |tag: u16| mn.as_ref().and_then(|m| m.ifd.u64s(tag)).filter(|v| v.len() == 2).map(|v| (v[0] as usize, v[1] as usize)); - let tagged = match (pair(CROP_ORIGIN), pair(CROP_SIZE)) { - // checked: the tags are file data; `x + cw` on a hostile value would wrap past the bounds - (Some((x, y)), Some((cw, ch))) - if cw > 0 && ch > 0 && x.checked_add(cw).is_some_and(|end| end <= w) && y.checked_add(ch).is_some_and(|end| end <= hgt) => - { - Some(Rect::new(x, y, cw, ch)) - } - _ => None, - }; - // without crop tags the image area is found from the samples (dark borders) - let read = if tagged.is_some() { mode } else { Mode::Full }; - let data = match info.compression { - 65535 => { - let mn = mn.as_ref().ok_or_else(|| RawError::Corrupt("compressed PEF without maker note".into()))?; - let tb = mn.ifd.bytes(HUFFMAN).ok_or_else(|| RawError::Unsupported("compressed PEF without a Huffman table".into()))?; - let huff = table(tb, mn.order)?; - let chunks = info.chunks(bytes.len() as u64); - let first = chunks.first().ok_or_else(|| RawError::Corrupt("PEF without image data".into()))?; - let mut c = *first; - c.len = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)).max(first.len); - let src = chunk_bytes(bytes, &c) - .or_else(|| bytes.get(first.offset as usize..)) - .ok_or_else(|| RawError::Corrupt("PEF data outside file".into()))?; - if read == Mode::Full { RawData::U16(decode_huffman(src, &huff, w, hgt, bits)?) } else { RawData::U16(Vec::new()) } - } - 1 => { - let strip = info.chunks(bytes.len() as u64).iter().fold(0u64, |a, c| a.saturating_add(c.len)); - let packing = if strip >= (w * hgt * 2) as u64 { Packing::Word16 } else { Packing::Msb }; - read_image_in(read, bytes, &info, tiff.order, packing)? - } - // Some bodies tag plain packed samples as PackBits (32773). Only a strip that holds exactly the packed - // size of its rows is read, as the uncompressed MSB-first samples it is; any other size stays unsupported. - 32773 if is_exactly_packed(&info, bytes.len() as u64) => { - let packed = ImageInfo { compression: 1, ..info.clone() }; - read_image_in(read, bytes, &packed, tiff.order, Packing::Msb)? - } - c => return Err(RawError::Unsupported(format!("PEF compression {c}"))), - }; - let RawData::U16(ref samples) = data else { return Err(RawError::Unsupported("float PEF".into())) }; - - let white = white_from_data(samples, bits); - let black_point = mn.as_ref().and_then(|m| m.ifd.f64s(BLACK_POINT)).filter(|v| v.len() == 4); - let active = match tagged { - Some(r) => r, - None => dark_trimmed(samples, w, hgt, black_point.as_deref().map(|v| v.iter().sum::() / 4.0), white), - }; - let cfa = match (ifd0.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), ifd0.bytes(t::CFA_PATTERN_EP)) { - (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, - // Every body states its layout in the Exif `CFAPattern`, read from the first sample of the stored array, not - // of the image area: the *ist D (origin 19, 11) and the 645D (80, 59) only fit unshifted. The 12-bit 10 MP - // bodies and everything from the K-3 on say RGGB; the K-7 / K-5 / 645D generation says BGGR. Files without the - // tag keep BGGR. - _ => cfa_from_exif(&tiff).unwrap_or_else(|| Cfa::bayer_static("BGGR")), - }; - let black = match black_point.as_deref() { - Some(v @ [_, _, _, _]) => { - // RGGB-ordered levels → per CFA position at the active area origin - let a = cfa.shifted(active.x, active.y); - let values = a.pattern.iter().map(|&c| [v[0], (v[1] + v[2]) / 2.0, v[3]][c as usize] as f32).collect(); - BlackLevel { repeat_rows: 2, repeat_cols: 2, values, ..Default::default() } - } - _ if active.x >= 4 => black_from_columns(samples, w, 0..active.x.saturating_sub(2), 0..hgt, active), - _ => BlackLevel::uniform(0.0), - }; - let wb = mn.as_ref().and_then(|m| m.ifd.f64s(WB_LEVELS)).filter(|v| v.len() == 4 && v.iter().all(|x| *x > 0.0)).map(|v| { - let g = (v[1] + v[2]) / 2.0; - [(v[0] / g) as f32, 1.0, (v[3] / g) as f32] - }); - let mut metadata = lightcraft_meta::from_tiff(&tiff); - metadata.width = Some(active.width as u32); - metadata.height = Some(active.height as u32); - let img = RawImage { - format: RawFormat::Pef, - width: w, - height: hgt, - cpp: 1, - data, - cfa: Some(cfa), - bits, - black, - white: vec![white], - active_area: active, - crop: Rect::new(0, 0, active.width, active.height), - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: ColorData::default(), - wb_multipliers: wb, - linearized: false, - pixel_aspect: 1.0, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Our own prefix code for categories 0..=14: lengths 2,2,3,3,4,5,..., codes assigned canonically. - fn test_table() -> (Vec, Vec<(u16, u8)>) { - let lens: [u8; 15] = [3, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12]; - let mut order: Vec = (0..15).collect(); - order.sort_by_key(|&i| (lens[i], i)); - let mut codes = vec![(0u16, 0u8); 15]; - let (mut code, mut prev) = (0u32, lens[order[0]]); - for (k, &i) in order.iter().enumerate() { - if k > 0 { - code = (code + 1) << (lens[i] - prev); - } - prev = lens[i]; - codes[i] = ((code << (12 - lens[i])) as u16, lens[i]); - } - let mut b = vec![0u8, 3]; - b.extend_from_slice(&[0; 12]); - for c in &codes { - b.extend_from_slice(&c.0.to_be_bytes()); - } - b.extend(codes.iter().map(|c| c.1)); - (b, codes) - } - - /// A compressed PEF declaring far more samples than its data could hold (one bit each at least) is refused - /// before its picture is allocated (issue #1512). - #[test] - fn a_stream_too_short_for_its_size_is_refused_before_allocating() { - let (tb, _) = test_table(); - let h = table(&tb, ByteOrder::Big).unwrap(); - let t = std::time::Instant::now(); - let r = decode_huffman(&[0x55; 4096], &h, 30_000, 30_000, 12); - assert!(matches!(r, Err(RawError::Corrupt(ref m)) if m.contains("need more")), "{r:?}"); - assert!(t.elapsed() < std::time::Duration::from_secs(1)); - } - - fn encode(px: &[u16], w: usize, codes: &[(u16, u8)]) -> Vec { - let mut bits: Vec = Vec::new(); - let put = |v: u32, n: u8, bits: &mut Vec| (0..n).rev().for_each(|i| bits.push(v >> i & 1 == 1)); - let mut vpred = [[0i32; 2]; 2]; - for (y, row) in px.chunks(w).enumerate() { - let mut hpred = [0i32; 2]; - for (x, &v) in row.iter().enumerate() { - let pred = if x < 2 { vpred[y & 1][x] } else { hpred[x & 1] }; - let d = v as i32 - pred; - if x < 2 { - vpred[y & 1][x] = v as i32; - } - hpred[x & 1] = v as i32; - let s = if d == 0 { 0 } else { 32 - d.unsigned_abs().leading_zeros() } as u8; - let (c, l) = codes[s as usize]; - put((c >> (12 - l)) as u32, l, &mut bits); - if s > 0 { - let extra = if d < 0 { (d - 1) as u32 & ((1 << s) - 1) } else { d as u32 }; - put(extra, s, &mut bits); - } - } - } - bits.chunks(8).map(|c| c.iter().enumerate().fold(0u8, |a, (i, &b)| a | (b as u8) << (7 - i))).collect() - } - - #[test] - fn huffman_round_trip() { - let (tb, codes) = test_table(); - let h = table(&tb, ByteOrder::Big).unwrap(); - let (w, hgt) = (37usize, 9usize); - let px: Vec = (0..w * hgt).map(|i| ((i * 7919) % 16384) as u16).collect(); - let src = encode(&px, w, &codes); - assert_eq!(decode_huffman(&src, &h, w, hgt, 14).unwrap(), px); - // truncated data is reported, not a panic - assert!(decode_huffman(&src[..src.len() / 3], &h, w, hgt, 14).is_err()); - assert!(table(&tb[..20], ByteOrder::Big).is_err()); - } - - /// Zero-padded lookahead past the end must not be decoded as samples: with no entropy at all, the zero bits - /// are a valid code (category 1) in this table, so a reader that only limits the refill position accepts them. - #[test] - fn symbols_decoded_from_padding_past_the_end_are_rejected() { - let (tb, codes) = test_table(); - let h = table(&tb, ByteOrder::Big).unwrap(); - assert!(decode_huffman(&[], &h, 2, 1, 14).is_err()); - // the same image with its real entropy still decodes, including the last byte's padding bits - let px = [5u16, 9]; - let src = encode(&px, 2, &codes); - assert_eq!(decode_huffman(&src, &h, 2, 1, 14).unwrap(), px); - // one byte short of the real entropy is rejected - assert!(decode_huffman(&src[..src.len() - 1], &h, 2, 1, 14).is_err()); - } - - /// A long run of the largest difference drove a predictor past i32: a panic in builds with overflow checks, - /// wrapped values otherwise (issue #1515). Both the row and the column predictors now stop with an error. - #[test] - fn predictor_overflow_is_an_error_not_a_panic() { - let (tb, codes) = test_table(); - let h = table(&tb, ByteOrder::Big).unwrap(); - let (c, l) = codes[14]; - let d = (1u32 << 14) - 1; - let stream = |n: usize| { - let mut bits: Vec = Vec::with_capacity(n * (l as usize + 14)); - for _ in 0..n { - (0..l).rev().for_each(|i| bits.push((c >> (12 - l)) >> i & 1 == 1)); - (0..14).rev().for_each(|i| bits.push(d >> i & 1 == 1)); - } - bits.chunks(8).map(|c| c.iter().enumerate().fold(0u8, |a, (i, &b)| a | (b as u8) << (7 - i))).collect::>() - }; - // differences one predictor needs to pass i32::MAX - let steps = (i32::MAX as u32 / d) as usize + 2; - // along a row: every other sample adds to the same predictor - let w = 2 * steps + 2; - let err = decode_huffman(&stream(w), &h, w, 1, 14).unwrap_err(); - assert!(matches!(err, RawError::Corrupt(ref m) if m.contains("predictor")), "{err}"); - // down two columns: each row adds to the predictor of its parity - let rows = 2 * steps + 2; - let err = decode_huffman(&stream(2 * rows), &h, 2, rows, 14).unwrap_err(); - assert!(matches!(err, RawError::Corrupt(ref m) if m.contains("predictor")), "{err}"); - } - - /// A big-endian one-strip PEF-style TIFF of `w × h` 12-bit samples with the given compression tag and strip - /// byte count, around `payload`. - fn tiny_pef(w: u16, h: u16, compression: u16, strip_len: u32, payload: &[u8]) -> Vec { - let entries: [(u16, u16, u32); 9] = [ - (0x0100, 3, w as u32 * 0x1_0000), // ImageWidth - (0x0101, 3, h as u32 * 0x1_0000), // ImageLength - (0x0102, 3, 12 * 0x1_0000), // BitsPerSample - (0x0103, 3, compression as u32 * 0x1_0000), // Compression - (0x0106, 3, 32803 * 0x1_0000), // Photometric: CFA - (0x0111, 4, 8 + 2 + 9 * 12 + 4), // StripOffsets - (0x0115, 3, 0x1_0000), // SamplesPerPixel - (0x0116, 3, h as u32 * 0x1_0000), // RowsPerStrip - (0x0117, 4, strip_len), // StripByteCounts - ]; - let mut f = b"MM\0*\0\0\0\x08".to_vec(); - f.extend_from_slice(&9u16.to_be_bytes()); - for (tag, ty, val) in entries { - f.extend_from_slice(&tag.to_be_bytes()); - f.extend_from_slice(&ty.to_be_bytes()); - f.extend_from_slice(&1u32.to_be_bytes()); - f.extend_from_slice(&val.to_be_bytes()); - } - f.extend_from_slice(&0u32.to_be_bytes()); // no next IFD - f.extend_from_slice(payload); - f - } - - /// Eight 12-bit samples, two rows of four, packed MSB-first: 0x123 0x456 0x789 0xabc / 0xdef 0x012 0x345 0x678. - const PACKED: [u8; 12] = [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78]; - - #[test] - fn packed_samples_under_the_packbits_tag_are_read_when_the_strip_has_exactly_the_packed_size() { - let file = tiny_pef(4, 2, 32773, 12, &PACKED); - let img = decode(&file, Mode::Full).unwrap(); - let RawData::U16(v) = &img.data else { panic!("integer samples") }; - assert_eq!(v, &[0x123, 0x456, 0x789, 0xabc, 0xdef, 0x012, 0x345, 0x678]); - assert_eq!((img.width, img.height, img.bits), (4, 2, 12)); - // the same bytes tagged as plain uncompressed give the same samples - let plain = decode(&tiny_pef(4, 2, 1, 12, &PACKED), Mode::Full).unwrap(); - assert_eq!(plain.data, img.data); - // header-only mode accepts it too - assert!(decode(&file, Mode::Header).is_ok()); - } - - #[test] - fn a_packbits_tagged_strip_of_any_other_size_stays_unsupported() { - for len in [11u32, 13, 6, 24] { - let mut payload = PACKED.to_vec(); - payload.resize(24, 0x55); - let file = tiny_pef(4, 2, 32773, len, &payload); - let err = decode(&file, Mode::Full).unwrap_err(); - assert!(matches!(&err, RawError::Unsupported(m) if m.contains("32773")), "strip of {len} bytes: {err:?}"); - } - } - - /// A 16 x 8 big-endian 12-bit PEF-style file with a 12 x 6 image area at the odd origin (3, 1), the Exif - /// `CFAPattern` `pattern` and an AOC maker note with the area tags (and, for 65535, a Huffman table). The samples - /// are plain 16-bit words (1), packed 12-bit (32773) or Huffman coded (65535). - fn pef_with_pattern(compression: u16, pattern: [u8; 4]) -> Vec { - use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; - let (w, h) = (16usize, 8usize); - let px: Vec = (0..w * h).map(|i| ((i * 37) % 900 + 100) as u16).collect(); - let (tb, codes) = test_table(); - let strip: Vec = match compression { - 1 => px.iter().flat_map(|v| v.to_be_bytes()).collect(), - 32773 => px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4 | p[1] >> 8) as u8, p[1] as u8]).collect(), - _ => encode(&px, w, &codes), - }; - let build = |table_at: u32| { - let mut ifd = IfdBuilder::new(); - ifd.set(0x0100, Value::Long(vec![w as u32])); - ifd.set(0x0101, Value::Long(vec![h as u32])); - ifd.set(0x0102, Value::Short(vec![12])); - ifd.set(0x0103, Value::Short(vec![compression])); - ifd.set(0x0106, Value::Short(vec![32803])); - ifd.set(0x010f, Value::Ascii("PENTAX Corporation".into())); - ifd.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![strip.clone()] }); - // AOC + "MM", then the IFD (area origin, area size and, for Huffman data, the table), next-IFD 0, the table - let mut note = b"AOCMM".to_vec(); - let mut entries = vec![(0x0038u16, 3u16, 2u32, [0u8, 3, 0, 1]), (0x0039, 3, 2, [0, 12, 0, 6])]; - if compression == 65535 { - entries.push((0x0220, 7, tb.len() as u32, table_at.to_be_bytes())); - } - note.extend_from_slice(&(entries.len() as u16).to_be_bytes()); - for (tag, ty, cnt, val) in entries { - note.extend_from_slice(&tag.to_be_bytes()); - note.extend_from_slice(&ty.to_be_bytes()); - note.extend_from_slice(&cnt.to_be_bytes()); - note.extend_from_slice(&val); - } - note.extend_from_slice(&0u32.to_be_bytes()); - if compression == 65535 { - note.extend_from_slice(&tb); - } - let mut exif = IfdBuilder::new(); - exif.set(0xa302, Value::Undefined([&[0, 2, 0, 2][..], &pattern[..]].concat())); - exif.set(0x927c, Value::Undefined(note)); - ifd.set_child(0x8769, exif); - TiffWriter::new(ByteOrder::Big, false).write(&[ifd]).unwrap() - }; - let first = build(0); - if compression != 65535 { - return first; - } - let at = Tiff::parse(&first).unwrap().exif().unwrap().get(0x927c).unwrap().offset; - build((at + 6 + 2 + 3 * 12 + 4) as u32) - } - - #[test] - fn the_pattern_is_the_exif_cfapattern_from_the_array_origin_for_every_compression() { - for compression in [1u16, 32773, 65535] { - for (p, name) in [([0u8, 1, 1, 2], "RGGB"), ([2, 1, 1, 0], "BGGR"), ([1, 0, 2, 1], "GRBG"), ([1, 2, 0, 1], "GBRG")] { - let img = decode(&pef_with_pattern(compression, p), Mode::Full).unwrap(); - assert_eq!(img.active_area, Rect::new(3, 1, 12, 6), "compression {compression}"); - assert_eq!(img.cfa, Some(Cfa::bayer_static(name)), "compression {compression}, Exif {name}"); - } - } - // no tag: the assumed layout stays - let img = decode(&tiny_pef(4, 2, 1, 16, &[0; 16]), Mode::Full).unwrap(); - assert_eq!(img.cfa, Some(Cfa::bayer_static("BGGR"))); - } - - /// A `w x h` big-endian 14-bit PEF of plain 16-bit words without area tags, whose maker note has only a - /// BlackPoint of `black`, with `px(x, y)` as the samples. - fn pef_with_black_point(w: usize, h: usize, black: u16, px: impl Fn(usize, usize) -> u16) -> Vec { - use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; - let strip: Vec = (0..w * h).flat_map(|i| px(i % w, i / w).to_be_bytes()).collect(); - let build = |levels_at: u32| { - let mut ifd = IfdBuilder::new(); - ifd.set(0x0100, Value::Long(vec![w as u32])); - ifd.set(0x0101, Value::Long(vec![h as u32])); - ifd.set(0x0102, Value::Short(vec![14])); - ifd.set(0x0103, Value::Short(vec![1])); - ifd.set(0x0106, Value::Short(vec![32803])); - ifd.set(0x010f, Value::Ascii("PENTAX Corporation".into())); - ifd.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![strip.clone()] }); - // AOC\0 + "MM", one entry (BlackPoint, four shorts stored after the IFD), next-IFD 0, the four levels - let mut note = b"AOC\0MM\0\x01".to_vec(); - note.extend_from_slice(&[0x02, 0x00, 0, 3, 0, 0, 0, 4]); - note.extend_from_slice(&levels_at.to_be_bytes()); - note.extend_from_slice(&0u32.to_be_bytes()); - (0..4).for_each(|_| note.extend_from_slice(&black.to_be_bytes())); - let mut exif = IfdBuilder::new(); - exif.set(0x927c, Value::Undefined(note)); - ifd.set_child(0x8769, exif); - TiffWriter::new(ByteOrder::Big, false).write(&[ifd]).unwrap() - }; - let at = Tiff::parse(&build(0)).unwrap().exif().unwrap().get(0x927c).unwrap().offset; - build((at + 6 + 2 + 12 + 4) as u32) - } - - /// The K-3 Mark III / KP / KF layout (issue #1271): masked columns and rows at the black level, an empty band - /// at zero, around an interior less than 20 times as bright as the black level. - #[test] - fn masked_rows_and_columns_at_the_black_level_are_trimmed_without_crop_tags() { - let (w, h) = (512, 384); - let file = pef_with_black_point(w, h, 256, |x, y| { - if x >= w - 8 { - 0 - } else if y >= h - 14 { - 15 - } else if x < 24 || x >= w - 16 || y < 28 { - 256 - } else { - 1256 + ((x * 7 + y * 13) % 64) as u16 - } - }); - let img = decode(&file, Mode::Full).unwrap(); - assert_eq!(img.black.values, vec![256.0; 4]); - assert_eq!(img.active_area, Rect::new(24, 28, w - 40, h - 42)); - } - - /// A night frame (bright centre, dark sky): 20 lines of real content 100 DN above the black level inside the - /// masked border stay in the picture, whatever the interior's brightness. - #[test] - fn dark_real_content_next_to_the_masked_border_is_kept() { - let (w, h) = (512, 384); - let file = pef_with_black_point(w, h, 256, |x, y| { - if x >= w - 8 { - 0 - } else if y >= h - 14 { - 15 - } else if x < 24 || x >= w - 16 || y < 28 { - 256 + ((x + y) % 3) as u16 - } else if x < 44 || x >= w - 36 || y < 48 || y >= h - 34 { - 356 + ((x * 7 + y * 13) % 16) as u16 - } else { - 3256 + ((x * 7 + y * 13) % 64) as u16 - } - }); - let img = decode(&file, Mode::Full).unwrap(); - assert_eq!(img.active_area, Rect::new(24, 28, w - 40, h - 42)); - } - - /// The K-70 (and K-1) layout: masked lines 65 DN over BlackPoint 64, just above the tolerance over black, and - /// empty rows at the bottom. - #[test] - fn masked_lines_a_little_above_the_black_level_are_trimmed() { - let (w, h) = (320, 288); - let file = pef_with_black_point(w, h, 64, |x, y| { - if y >= h - 12 { - 0 - } else if x < 56 || y < 28 { - 128 + ((x + y) % 3) as u16 - } else { - 2064 + ((x * 7 + y * 13) % 64) as u16 - } - }); - assert_eq!(decode(&file, Mode::Full).unwrap().active_area, Rect::new(56, 28, 264, 248)); - } - - /// The 645Z layout: 12 saturated columns outside 46 masked ones on the right; they hold no picture either. - #[test] - fn saturated_lines_outside_masked_ones_are_trimmed() { - let (w, h) = (400, 288); - let file = pef_with_black_point(w, h, 64, |x, y| { - if x >= w - 12 { - 16316 - } else if x >= w - 58 { - 64 + ((x + y) % 3) as u16 - } else { - 2064 + ((x * 7 + y * 13) % 64) as u16 - } - }); - assert_eq!(decode(&file, Mode::Full).unwrap().active_area, Rect::new(0, 0, w - 58, h)); - } - - /// A blown-out edge with the picture right behind it is picture: nothing is trimmed. - #[test] - fn a_saturated_edge_followed_by_picture_stays() { - let (w, h) = (400, 288); - let file = pef_with_black_point(w, h, 64, |x, y| if x >= w - 12 { 16316 } else { 2064 + ((x * 7 + y * 13) % 64) as u16 }); - assert_eq!(decode(&file, Mode::Full).unwrap().active_area, Rect::new(0, 0, w, h)); - } - - /// A frame at the black level everywhere (a lens-cap shot) has no picture to tell masked lines from: it keeps - /// its whole area. - #[test] - fn a_frame_at_the_black_level_keeps_its_whole_area() { - let (w, h) = (320, 288); - let file = pef_with_black_point(w, h, 64, |x, y| 64 + ((x * 7 + y * 13) % 5) as u16); - assert_eq!(decode(&file, Mode::Full).unwrap().active_area, Rect::new(0, 0, w, h)); - } - - /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow, - /// for the Huffman-coded and the uncompressed samples. - #[test] - fn strip_byte_counts_past_u64_max_do_not_overflow() { - for compression in [65535u16, 1] { - let file = crate::vendor::tests::huge_strip_counts(pef_with_pattern(compression, [0, 1, 1, 2])); - for mode in [Mode::Header, Mode::Full] { - let _ = decode(&file, mode); - } - } - } -} diff --git a/crates/raw/src/vendor/raf.rs b/crates/raw/src/vendor/raf.rs index e485931114..9d4976617d 100644 --- a/crates/raw/src/vendor/raf.rs +++ b/crates/raw/src/vendor/raf.rs @@ -103,7 +103,7 @@ fn camera_name(b: &[u8]) -> String { fn cfa(h: &Header) -> Cfa { match record(h, XTRANS_LAYOUT) { Some(l) if l.len() == 36 && l.iter().all(|&c| c <= 2) => Cfa { width: 6, height: 6, pattern: l.iter().rev().copied().collect() }, - _ => Cfa::bayer_static("RGGB"), + _ => crate::bayer("RGGB"), } } diff --git a/crates/raw/src/vendor/rw2.rs b/crates/raw/src/vendor/rw2.rs index 7938da9d8e..21082795cd 100644 --- a/crates/raw/src/vendor/rw2.rs +++ b/crates/raw/src/vendor/rw2.rs @@ -102,7 +102,7 @@ //! Not supported ([`RawError::Unsupported`], the embedded preview is shown instead): compression 34826, raw formats //! 1 and 3, and bit depths other than the ones above (no samples of any of them). -use super::pef::{Bits, Huffman, diff}; +use super::huffman::{Bits, Huffman, diff}; use super::{active_rows, white_from_data}; use crate::{BlackLevel, Cfa, ColorData, MAX_SAMPLES, Mode, Opcode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; use craft_tiff::{ByteOrder, Ifd, Tiff, Value, tags as t}; @@ -535,7 +535,7 @@ fn fill_defects(data: &mut [u16], w: usize, area: Rect) { } fn cfa(code: u16) -> Cfa { - Cfa::bayer_static(match code { + crate::bayer(match code { 2 => "GRBG", 3 => "GBRG", 4 => "BGGR", diff --git a/crates/raw/src/vendor/srw.rs b/crates/raw/src/vendor/srw.rs deleted file mode 100644 index 298aeed238..0000000000 --- a/crates/raw/src/vendor/srw.rs +++ /dev/null @@ -1,603 +0,0 @@ -//! Samsung SRW: the variants that store the sensor samples uncompressed. -//! -//! Sources: TIFF 6.0 (container: a big- or little-endian TIFF whose IFD0 points at sub-IFDs, one of them the raw -//! image), Exif 2.3 (`CFAPattern`, `PixelXDimension`, `PixelYDimension`; maker note `0x927c`), the ExifTool Samsung -//! tag-name documentation (`SensorAreas` `0xa010`, `EncryptionKey` `0xa020`, `WB_RGGBLevelsUncorrected` `0xa021`, -//! `WB_RGGBLevelsBlack` `0xa028`, `RawData` `0xa048`) and our own black-box analysis of CC0 samples from raw.pixls.us -//! (NX5, NX10, NX11, NX20, NX200, NX210, NX1000, NX1100, EX1, WB2000; every number below was measured on them): -//! -//! - The raw image is the IFD whose `Compression` is a private value (32769..=32773); its `CFAPattern` (`0x828e`) -//! names the 2x2 layout, anchored at the first sample of the stored array. Checked on the files above: the colours -//! of the decoded mosaic follow the camera's JPEG best with exactly that layout (`corpus_samsung_srw`). -//! - Compression 32769 (EX1, WB2000): one 16-bit little-endian word per sample (the TIFF is big-endian, the words are -//! not); the strip holds exactly `width * height * 2` bytes. -//! - Compression 32770 with exactly `width * height * 12 / 8` strip bytes (NX5, NX10, NX11, NX20, NX200, NX210, NX1000, -//! NX1100): 12-bit samples, two in three bytes, rows without padding. The NX5/NX10/NX11 files read them MSB-first, -//! the others LSB-first; the file doesn't say which, the image does: in the wrong order neighbouring same-colour -//! samples differ 5 to 11 times more (10 files, every one decided by that margin), see [`lsb_is_smoother`]. -//! - Every other shape of those and of the other private values (32770 with fewer bytes: NX30, NX300, NX2000, -//! EK-GN120; 32772: NX mini, NX3000, NX3300; 32773: NX1, NX500) is a compressed coding: reported as unsupported. -//! - The maker note is a plain IFD whose value offsets count from the start of the note, not of the TIFF. Several -//! vectors are stored offset by `EncryptionKey`, 11 integers in every file (element `i` of a vector uses key -//! `i mod 11`): `WB_RGGBLevelsUncorrected` and `WB_RGGBLevelsBlack` hold `value + key`, `RawData` holds -//! `value - key`, found by trying both signs and keeping the one that gives plausible numbers (green levels -//! 4096 in all but one file, saturation levels 4095 or 16383, black levels 0 to 3, the dark-column level). -//! - `SensorAreas`: the second rectangle (left, top, right, bottom) is the camera JPEG's framing (its size equals the -//! JPEG's in every file but WB2000's), used as the active area. Registered against the JPEG its centre agrees to -//! within 2 pixels (NX10 family; the NX20 family's JPEG is lens-corrected, edges differ). -//! - The Exif picture size is smaller than the framing in one direction only on the WB2000 (16:9 from a 4:3 sensor): -//! the JPEG is the centre of the framing (registration: top offset 366 = framing top 22 + (2736 - 2048) / 2). -//! - `RawData`: four black levels, then saturation levels (R, G1, G2, B twice). The EX1 saturates at 15881, not at its -//! stated 16383 (85786 samples sit on the plateau), so a plateau below the stated level wins. -//! - Black: `WB_RGGBLevelsBlack` when it states one (NX5, NX10, NX11: 2 to 3, the right-hand dark columns measure -//! 3.5 to 4.5); otherwise the dark rows or columns outside the framing (EX1: eight rows at 2.3); otherwise 0. -//! - `WB_RGGBLevelsUncorrected` divided by its mean green is the as-shot gain: the renders of the 12 files match the -//! camera JPEG at median ΔE76 2.2 to 7.6 (10.7 on the backlit WB2000 sample, 5.7 after registration). -use super::{black_from_columns, white_from_data}; -use crate::unpack::{read_u16s, unpack_lsb, unpack_msb}; -use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result}; -use craft_tiff::image::chunk_bytes; -use craft_tiff::{ByteOrder, Ifd, Tiff, tags as t}; -use lightcraft_geom::Orientation; -use rayon::prelude::*; - -const SENSOR_AREAS: u16 = 0xa010; -const ENCRYPTION_KEY: u16 = 0xa020; -const WB_UNCORRECTED: u16 = 0xa021; -const WB_BLACK: u16 = 0xa028; -const RAW_DATA: u16 = 0xa048; - -/// The private `Compression` values of the raw image IFD. -const COMPRESSIONS: std::ops::RangeInclusive = 32769..=32773; - -/// The maker-note IFD (offsets relative to the note's own start). -fn maker_note(bytes: &[u8], tiff: &Tiff) -> Option { - let e = tiff.exif()?.get(t::MAKER_NOTE)?; - let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() }; - craft_tiff::parse_ifd_at(bytes, e.offset, tiff.order, e.offset, false, &opts).ok().map(|(i, _)| i) -} - -/// A key-offset vector: the entries of `tag` shifted by the maker note's key (`sign` is +1 or -1 times the key). -fn keyed(mn: &Ifd, tag: u16, sign: i64) -> Option> { - let key = mn.u64s(ENCRYPTION_KEY).filter(|k| k.len() == 11)?; - let vals = mn.f64s(tag)?; - // 32-bit entries: the stored value wraps modulo 2^32 (a negative number stored as a LONG) - // (a key value past i64::MAX must not overflow the multiply: only the low 32 bits are kept) - Some(vals.iter().enumerate().map(|(i, &v)| i64::from((v as i64).wrapping_add((key[i % 11] as i64).wrapping_mul(sign)) as i32)).collect()) -} - -/// The raw image's IFD: the one with a private compression value. -fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> { - tiff.all_ifds().into_iter().find(|i| i.u16(t::COMPRESSION).is_some_and(|c| COMPRESSIONS.contains(&c)) && i.contains(t::IMAGE_WIDTH)) -} - -/// How the samples of an IFD are stored, when uncompressed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Coding { - /// One little-endian 16-bit word per sample. - Words, - /// 12-bit samples, two in three bytes: read MSB-first (the NX5, NX10 and NX11 files) or LSB-first (the later - /// bodies' files); the file does not say which, the smoother image does ([`lsb_is_smoother`]). - Packed12, -} - -fn coding(compression: u16, w: usize, h: usize, strip: u64) -> Option { - let n = (w as u64).checked_mul(h as u64)?; - match compression { - 32769 if strip == n.checked_mul(2)? => Some(Coding::Words), - 32770 if w.is_multiple_of(2) && strip == n.checked_mul(12)? / 8 => Some(Coding::Packed12), - _ => None, - } -} - -pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { - let tiff = Tiff::parse(bytes)?; - let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("SRW without IFDs".into()))?; - let raw = raw_ifd(&tiff).ok_or_else(|| RawError::Unsupported("Samsung raw image not found".into()))?; - let info = raw.image()?; - let (w, h) = (info.width as usize, info.height as usize); - let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?; - let chunks = info.chunks(bytes.len() as u64); - let strip = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)); - let Some(coding) = coding(info.compression, w, h, strip).filter(|_| chunks.len() == 1) else { - return Err(RawError::Unsupported(format!( - "Samsung compressed raw (compression {}, {:.2} stored bits per sample)", - info.compression, - strip as f64 * 8.0 / n as f64 - ))); - }; - let data = if mode == Mode::Full { - let src = chunk_bytes(bytes, &chunks[0]).ok_or_else(|| RawError::Corrupt("SRW strip outside file".into()))?; - if src.len() as u64 != strip { - return Err(RawError::Corrupt("SRW strip shorter than its rows".into())); - } - let mut d = vec![0u16; n]; - match coding { - Coding::Words => read_u16s(src, ByteOrder::Little, &mut d), - Coding::Packed12 => { - let stride = w / 2 * 3; - let unpack: fn(&[u8], u32, &mut [u16]) = if lsb_is_smoother(src, w, h) { unpack_lsb } else { unpack_msb }; - d.par_chunks_mut(w).zip(src.par_chunks(stride)).for_each(|(row, s)| unpack(s, 12, row)); - } - } - RawData::U16(d) - } else { - RawData::U16(Vec::new()) - }; - - let mn = maker_note(bytes, &tiff); - // the camera JPEG's framing (left, top, right, bottom), when it lies inside the stored array - let active = mn - .as_ref() - .and_then(|m| m.u64s(SENSOR_AREAS)) - .filter(|v| v.len() == 8) - .map(|v| (v[4] as usize, v[5] as usize, v[6] as usize, v[7] as usize)) - .filter(|&(l, tp, r, b)| l < r && tp < b && r <= w && b <= h) - .map_or(Rect::new(0, 0, w, h), |(l, tp, r, b)| Rect::new(l, tp, r - l, b - tp)); - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { - (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, - _ => return Err(RawError::Unsupported("Samsung raw without a 2x2 CFAPattern".into())), - }; - // saturation levels and black levels (R, G1, G2, B), in the file's own words - let levels = mn.as_ref().and_then(|m| keyed(m, RAW_DATA, 1)).filter(|v| v.len() == 12); - let RawData::U16(samples) = &data else { return Err(RawError::Unsupported("float SRW".into())) }; - // saturation: the file's level, or lower where the samples pile up (EX1 clips at 15882 of its stated 16383) - let stated = levels.as_ref().filter(|v| v[4..].iter().all(|&x| x == v[4]) && (255..=65535).contains(&v[4])).map(|v| v[4] as f32); - let bits = stated.map_or((info.bits() as u32).clamp(8, 16), |s| 32 - (s as u32).leading_zeros()); - let plateau = (!samples.is_empty()).then(|| white_from_data(&active_rows(samples, w, active), bits)); - let white = match (stated, plateau) { - (Some(s), Some(p)) => s.min(p), - (Some(s), None) => s, - (None, Some(p)) => p, - (None, None) => 4095.0, - }; - let tagged_black = - mn.as_ref().and_then(|m| keyed(m, WB_BLACK, -1)).filter(|v| v.len() == 4 && v.iter().all(|&x| (0..=u16::MAX as i64).contains(&x))); - let black = match tagged_black { - Some(v) if v.iter().any(|&x| x > 0) => { - // RGGB-ordered levels -> per CFA position at the active area origin - let a = cfa.shifted(active.x, active.y); - let values = a.pattern.iter().map(|&c| [v[0], (v[1] + v[2]) / 2, v[3]][c as usize] as f32).collect(); - BlackLevel { repeat_rows: 2, repeat_cols: 2, values, ..Default::default() } - } - // the file states no black level: measure the masked band around the active area, when there is one - _ => masked_black(samples, w, h, active, white), - }; - // as-shot white balance: gains with the greens near 4096 (unity) - let wb = mn.as_ref().and_then(|m| keyed(m, WB_UNCORRECTED, -1)).filter(|v| v.len() == 4 && v.iter().all(|&x| x > 0)).map(|v| { - let g = (v[1] + v[2]) as f64 / 2.0; - [(v[0] as f64 / g) as f32, 1.0, (v[3] as f64 / g) as f32] - }); - let mut metadata = lightcraft_meta::from_tiff(&tiff); - let crop = picture_crop(&tiff, active); - metadata.width = Some(crop.width as u32); - metadata.height = Some(crop.height as u32); - let img = RawImage { - format: RawFormat::Srw, - width: w, - height: h, - cpp: 1, - data, - cfa: Some(cfa), - bits, - black, - white: vec![white], - active_area: active, - crop, - orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: ColorData::default(), - wb_multipliers: wb, - linearized: false, - pixel_aspect: 1.0, - opcodes: OpcodeLists::default(), - metadata, - lens_metadata: Default::default(), - }; - img.validate_for(mode)?; - Ok(img) -} - -/// Which bit order unpacks 12-bit samples of `w` x `h` (in `src`, `w / 2 * 3` bytes per row) into the image: in -/// the right order neighbouring samples of one colour differ by little, in the wrong one by about the whole range. -/// Compares the summed absolute differences of samples two apart over 64 rows from the middle of the frame. -fn lsb_is_smoother(src: &[u8], w: usize, h: usize) -> bool { - let stride = w / 2 * 3; - let (mut msb, mut lsb) = (0u64, 0u64); - let (mut a, mut b) = (vec![0u16; w], vec![0u16; w]); - for y in (h / 5..h * 4 / 5).step_by((h * 3 / 5 / 64).max(1)) { - let Some(row) = y.checked_mul(stride).and_then(|s| src.get(s..s + stride)) else { break }; - unpack_msb(row, 12, &mut a); - unpack_lsb(row, 12, &mut b); - let spread = |v: &[u16]| v.windows(3).map(|p| u64::from(p[0].abs_diff(p[2]))).sum::(); - msb += spread(&a); - lsb += spread(&b); - } - lsb < msb -} - -/// The default crop: the whole framing, or, when the Exif picture size is the framing cut in one direction only -/// (a 16:9 picture from a 4:3 sensor), the centred part of that size. -fn picture_crop(tiff: &Tiff, active: Rect) -> Rect { - let whole = Rect::new(0, 0, active.width, active.height); - let Some(exif) = tiff.exif() else { return whole }; - let (Some(pw), Some(ph)) = (exif.u32(t::PIXEL_X_DIMENSION), exif.u32(t::PIXEL_Y_DIMENSION)) else { return whole }; - let (pw, ph) = (pw as usize, ph as usize); - if pw == 0 || ph == 0 || pw > active.width || ph > active.height || (pw < active.width && ph < active.height) { - return whole; - } - Rect::new((active.width - pw) / 2, (active.height - ph) / 2, pw, ph) -} - -/// Every third row of the active area (the saturation statistics need no more). -fn active_rows(d: &[u16], w: usize, a: Rect) -> Vec { - (a.y..a.y + a.height).step_by(3).filter_map(|y| d.get(y * w + a.x..y * w + a.x + a.width)).flatten().copied().collect() -} - -/// Black level from rows or columns outside the active area that are dark (mean below 1.5% of `white`): the -/// longest run of dark lines on the right, else the left, below, above; at least four lines, the two outermost -/// rows and columns of the array left out. Uniform 0 when there is no such run. -fn masked_black(d: &[u16], w: usize, h: usize, a: Rect, white: f32) -> BlackLevel { - if d.is_empty() { - return BlackLevel::uniform(0.0); - } - let limit = f64::from(white) * 0.015; - let col_mean = |x: usize| { - (a.y..a.y + a.height).step_by(7).filter_map(|y| d.get(y * w + x)).map(|&v| f64::from(v)).sum::() / a.height.div_ceil(7) as f64 - }; - let row_mean = - |y: usize| (a.x..a.x + a.width).step_by(7).filter_map(|x| d.get(y * w + x)).map(|&v| f64::from(v)).sum::() / a.width.div_ceil(7) as f64; - // the longest run of consecutive dark lines within `lines` - let longest = |lines: std::ops::Range, mean: &dyn Fn(usize) -> f64| { - let (mut best, mut start) = (0..0, lines.start); - for i in lines.clone() { - if mean(i) >= limit { - start = i + 1; - } else if i + 1 - start > best.len() { - best = start..i + 1; - } - } - best - }; - let cols = a.y..a.y + a.height; - let rows = a.x..a.x + a.width; - let right = longest(a.x + a.width..w.saturating_sub(2), &col_mean); - let left = longest(2..a.x, &col_mean); - let below = longest(a.y + a.height..h.saturating_sub(2), &row_mean); - let above = longest(2..a.y, &row_mean); - if right.len() >= 4 { - black_from_columns(d, w, right, cols, a) - } else if left.len() >= 4 { - black_from_columns(d, w, left, cols, a) - } else if below.len() >= 4 { - black_from_columns(d, w, rows, below, a) - } else if above.len() >= 4 { - black_from_columns(d, w, rows, above, a) - } else { - BlackLevel::uniform(0.0) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{decode, probe, probe_info}; - use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; - - const KEY: [u32; 11] = [305, 72, 737, 456, 282, 307, 519, 724, 13, 505, 193]; - - /// A maker note in the Samsung layout: a big-endian IFD of LONG vectors, offsets relative to the note's start. - fn note(entries: &[(u16, Vec)]) -> Vec { - let typed: Vec<_> = entries.iter().map(|(tag, v)| (*tag, 4, v.len() as u32, v.iter().flat_map(|x| x.to_be_bytes()).collect())).collect(); - note_typed(&typed) - } - - /// [`note`] with any entry types: `(tag, type, count, big-endian value bytes)`. - fn note_typed(entries: &[(u16, u16, u32, Vec)]) -> Vec { - let mut head = Vec::new(); - let mut tail = Vec::new(); - head.extend_from_slice(&(entries.len() as u16).to_be_bytes()); - let values_at = 2 + 12 * entries.len() + 4; - for (tag, kind, count, v) in entries { - head.extend_from_slice(&tag.to_be_bytes()); - head.extend_from_slice(&kind.to_be_bytes()); - head.extend_from_slice(&count.to_be_bytes()); - if v.len() <= 4 { - head.extend(v.iter().copied().chain(std::iter::repeat(0)).take(4)); - } else { - head.extend_from_slice(&((values_at + tail.len()) as u32).to_be_bytes()); - tail.extend_from_slice(v); - } - } - head.extend_from_slice(&[0; 4]); - head.extend(tail); - head - } - - /// Stored form of a vector the way the file keeps it: `plain + key` (`sign` 1) or `plain - key` (`sign` -1). - fn stored(plain: &[i64], sign: i64) -> Vec { - plain.iter().enumerate().map(|(i, &p)| (p + sign * i64::from(KEY[i % 11])) as u32).collect() - } - - fn pack12(v: &[u16]) -> Vec { - v.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect() - } - - fn le_words(v: &[u16]) -> Vec { - v.iter().flat_map(|x| x.to_le_bytes()).collect() - } - - struct Spec { - w: u32, - h: u32, - compression: u16, - strip: Vec, - pattern: Option<[u8; 4]>, - note: Option>, - picture: Option<(u32, u32)>, - } - - fn srw(s: Spec) -> Vec { - let mut raw = IfdBuilder::new(); - raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - raw.set(t::IMAGE_WIDTH, Value::Long(vec![s.w])); - raw.set(t::IMAGE_LENGTH, Value::Long(vec![s.h])); - raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![12])); - raw.set(t::COMPRESSION, Value::Short(vec![s.compression])); - raw.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])); - if let Some(p) = s.pattern { - raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); - raw.set(t::CFA_PATTERN_EP, Value::Byte(p.to_vec())); - } - raw.set_image(ImageData::Strips { rows_per_strip: s.h, strips: vec![s.strip] }); - let mut ifd0 = IfdBuilder::new(); - ifd0.set(t::MAKE, Value::Ascii("SAMSUNG".into())); - ifd0.set(t::MODEL, Value::Ascii("NX0".into())); - let mut exif = IfdBuilder::new(); - if let Some(n) = s.note { - exif.set(t::MAKER_NOTE, Value::Undefined(n)); - } - if let Some((pw, ph)) = s.picture { - exif.set(t::PIXEL_X_DIMENSION, Value::Long(vec![pw])); - exif.set(t::PIXEL_Y_DIMENSION, Value::Long(vec![ph])); - } - ifd0.set_child(t::EXIF_IFD, exif); - ifd0.add_sub_ifd(raw); - TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap() - } - - /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. - #[test] - fn strip_byte_counts_past_u64_max_do_not_overflow() { - let file = crate::vendor::tests::huge_strip_counts(srw(Spec { - w: 4, - h: 2, - compression: 32769, - strip: vec![0; 16], - pattern: None, - note: None, - picture: None, - })); - for mode in [Mode::Header, Mode::Full] { - let _ = super::decode(&file, mode); - } - } - - /// The camera-stated description every test file carries: JPEG framing, white balance, levels. - fn full_note(area: [u32; 4], white: i64, black: i64) -> Vec { - let mut levels = vec![0i64; 4]; - levels.extend([white; 8]); - note(&[ - (SENSOR_AREAS, vec![0, 0, 64, 32, area[0], area[1], area[2], area[3]]), - (ENCRYPTION_KEY, KEY.to_vec()), - (WB_UNCORRECTED, stored(&[8192, 4096, 4096, 6144], 1)), - (WB_BLACK, stored(&[black; 4], 1)), - (RAW_DATA, stored(&levels, -1)), - ]) - } - - /// A smooth gradient with a little texture, `max` the first value that is not reached. - fn ramp(w: u32, h: u32, max: u32) -> Vec { - (0..w * h).map(|i| ((1000 + (i % w) * 7 + (i / w) * 5 + (i * 13) % 9) % max) as u16).collect() - } - - fn pack12_lsb(v: &[u16]) -> Vec { - v.chunks(2).flat_map(|p| [p[0] as u8, ((p[0] >> 8) as u8) | ((p[1] & 15) << 4) as u8, (p[1] >> 4) as u8]).collect() - } - - /// Known answer: the samples, layout, framing, levels and white balance all come from the file's own words. - #[test] - fn packed_12_bit_samples_decode_with_the_maker_note() { - let v = ramp(64, 32, 4096); - let bytes = srw(Spec { - w: 64, - h: 32, - compression: 32770, - strip: pack12(&v), - pattern: Some([2, 1, 1, 0]), - note: Some(full_note([6, 4, 58, 30], 4095, 3)), - picture: None, - }); - assert_eq!(probe(&bytes), Some(RawFormat::Srw)); - let r = decode(&bytes).unwrap(); - assert_eq!((r.format, r.width, r.height, r.bits), (RawFormat::Srw, 64, 32, 12)); - assert_eq!(r.data, RawData::U16(v)); - assert_eq!(r.cfa.as_ref().unwrap().name(), "BGGR"); - assert_eq!(r.active_area, Rect::new(6, 4, 52, 26)); - assert_eq!(r.crop, Rect::new(0, 0, 52, 26)); - assert_eq!((r.black.mean(), r.white.clone()), (3.0, vec![4095.0])); - assert_eq!(r.wb_multipliers, Some([2.0, 1.0, 1.5])); - // headers only: everything but the samples - let i = probe_info(&bytes).unwrap(); - assert_eq!((i.active_area, i.wb_multipliers, i.bits), (Rect::new(6, 4, 52, 26), Some([2.0, 1.0, 1.5]), 12)); - } - - /// The later bodies pack the same 12-bit samples LSB-first; which of the two orders a file uses is found from - /// the samples (the wrong order makes a noisy image), not from the model. - #[test] - fn lsb_first_packing_is_found_from_the_samples() { - let v = ramp(64, 32, 4096); - for (strip, name) in [(pack12(&v), "msb"), (pack12_lsb(&v), "lsb")] { - let bytes = srw(Spec { w: 64, h: 32, compression: 32770, strip, pattern: Some([1, 0, 2, 1]), note: None, picture: None }); - assert_eq!(decode(&bytes).unwrap().data, RawData::U16(v.clone()), "{name}"); - } - } - - /// A picture size narrower than the framing in one direction only (16:9 from a 4:3 sensor) is the framing's - /// centre; any other size is ignored. - #[test] - fn the_exif_picture_size_centres_a_one_direction_crop() { - let v = ramp(64, 32, 4096); - let file = |picture| { - srw(Spec { - w: 64, - h: 32, - compression: 32770, - strip: pack12(&v), - pattern: Some([2, 1, 1, 0]), - note: Some(full_note([6, 4, 58, 30], 4095, 0)), - picture, - }) - }; - // framing 52 x 26 - assert_eq!(decode(&file(Some((52, 18)))).unwrap().crop, Rect::new(0, 4, 52, 18)); - assert_eq!(decode(&file(Some((40, 26)))).unwrap().crop, Rect::new(6, 0, 40, 26)); - let r = decode(&file(Some((52, 18)))).unwrap(); - assert_eq!((r.metadata.width, r.metadata.height), (Some(52), Some(18))); - for other in [None, Some((52, 26)), Some((40, 18)), Some((60, 18)), Some((52, 30)), Some((0, 18))] { - assert_eq!(decode(&file(other)).unwrap().crop, Rect::new(0, 0, 52, 26), "{other:?}"); - } - } - - /// 16-bit words are little-endian although the file is big-endian; a saturation plateau below the stated - /// level wins; dark rows below the framing give the black level when the file states none. - #[test] - fn word_samples_decode_and_measure_what_the_file_does_not_say() { - let (w, h) = (64u32, 40u32); - let mut v: Vec = (0..w * h).map(|i| 3000 + (i * 91 % 5000) as u16).collect(); - // saturation: a plateau at 15882 inside the framing (rows 4..28), two rows of picture beyond it, dark rows 30..40 - for i in 0..150usize { - v[(4 + i % 24) * 64 + 8 + i / 24] = 15882; - } - for x in 0..64 * 10 { - v[30 * 64 + x] = 80; - } - let bytes = srw(Spec { - w, - h, - compression: 32769, - strip: le_words(&v), - pattern: Some([0, 1, 1, 2]), - note: Some(full_note([0, 4, 64, 28], 16383, 0)), - picture: None, - }); - let r = decode(&bytes).unwrap(); - assert_eq!(r.data, RawData::U16(v)); - assert_eq!(r.bits, 14); - assert!((15800.0..=15882.0).contains(&r.white[0]), "{:?}", r.white); - assert_eq!(r.black.mean(), 80.0); - assert_eq!(r.cfa.unwrap().name(), "RGGB"); - } - - /// Files whose strip is not exactly the uncompressed size (or that use another private value) are compressed - /// codings: reported as such, still recognised as SRW. - #[test] - fn compressed_codings_are_reported_not_misread() { - let plain = |compression, strip: Vec| { - srw(Spec { w: 64, h: 32, compression, strip, pattern: Some([2, 1, 1, 0]), note: Some(full_note([0, 0, 64, 32], 4095, 0)), picture: None }) - }; - for bytes in [ - plain(32770, vec![7; 64 * 32 * 12 / 8 - 3]), - plain(32772, vec![7; 4000]), - plain(32773, pack12(&ramp(64, 32, 4096))), - plain(32769, vec![0; 64 * 32]), - ] { - assert_eq!(probe(&bytes), Some(RawFormat::Srw)); - let Err(RawError::Unsupported(why)) = decode(&bytes) else { panic!("expected Unsupported") }; - assert!(why.contains("compressed"), "{why}"); - assert!(probe_info(&bytes).is_err()); - } - } - - /// Without a maker note the samples still decode: whole array, no white balance, depth from the TIFF tags. - #[test] - fn a_file_without_a_maker_note_decodes_with_defaults() { - let v = ramp(64, 32, 4096); - let bytes = srw(Spec { w: 64, h: 32, compression: 32770, strip: pack12(&v), pattern: Some([1, 0, 2, 1]), note: None, picture: None }); - let r = decode(&bytes).unwrap(); - assert_eq!(r.data, RawData::U16(v)); - assert_eq!((r.active_area, r.wb_multipliers, r.black.mean()), (Rect::new(0, 0, 64, 32), None, 0.0)); - assert_eq!(r.cfa.unwrap().name(), "GRBG"); - assert_eq!(r.bits, 12); - } - - /// A raw IFD that does not say how its mosaic is laid out is not guessed at. - #[test] - fn a_file_without_a_cfa_pattern_is_unsupported() { - let bytes = srw(Spec { w: 64, h: 32, compression: 32770, strip: pack12(&ramp(64, 32, 4096)), pattern: None, note: None, picture: None }); - assert!(matches!(decode(&bytes), Err(RawError::Unsupported(w)) if w.contains("CFAPattern"))); - } - - /// An encryption key value past i64::MAX (LONG8) overflowed `-1 * key` in debug builds. - #[test] - fn a_huge_encryption_key_does_not_panic() { - let key: Vec = std::iter::repeat_n((1u64 << 63).to_be_bytes(), 11).flatten().collect(); - let note = note_typed(&[(ENCRYPTION_KEY, 16, 11, key), (WB_UNCORRECTED, 4, 4, [0u8; 16].to_vec()), (WB_BLACK, 4, 4, [0u8; 16].to_vec())]); - let bytes = srw(Spec { - w: 64, - h: 32, - compression: 32770, - strip: pack12(&ramp(64, 32, 4096)), - pattern: Some([2, 1, 1, 0]), - note: Some(note), - picture: None, - }); - let mn = maker_note(&bytes, &Tiff::parse(&bytes).unwrap()).unwrap(); - assert_eq!(mn.u64s(ENCRYPTION_KEY).map(|k| k[0]), Some(1 << 63), "the key reaches keyed()"); - assert_eq!(keyed(&mn, WB_BLACK, -1), Some(vec![0; 4]), "(2^63 mod 2^32 is 0)"); - assert!(decode(&bytes).is_ok()); - assert!(probe_info(&bytes).is_ok()); - } - - /// A framing rectangle outside the array, or reversed, is ignored; truncated files fail without panicking. - #[test] - fn hostile_framing_and_truncation_do_not_panic() { - let v = ramp(64, 32, 4096); - for area in [[0, 0, 65, 32], [10, 0, 10, 32], [0, 40, 64, 20]] { - let bytes = srw(Spec { - w: 64, - h: 32, - compression: 32770, - strip: pack12(&v), - pattern: Some([2, 1, 1, 0]), - note: Some(full_note(area, 4095, 0)), - picture: None, - }); - assert_eq!(decode(&bytes).unwrap().active_area, Rect::new(0, 0, 64, 32)); - } - let bytes = srw(Spec { - w: 64, - h: 32, - compression: 32770, - strip: pack12(&v), - pattern: Some([2, 1, 1, 0]), - note: Some(full_note([0, 0, 64, 32], 4095, 0)), - picture: None, - }); - for cut in [10, bytes.len() / 2, bytes.len() - 20] { - let _ = decode(&bytes[..cut]); - let _ = probe_info(&bytes[..cut]); - } - } - - /// #2561: a small file whose strip declares a large frame is refused before the full decode allocates the frame. - #[test] - fn a_strip_cut_short_is_refused_before_allocating() { - let (w, h) = (3000u32, 2000u32); - for (compression, declared) in [(32769, w * h * 2), (32770, w * h / 2 * 3)] { - let mut f = srw(Spec { w, h, compression, strip: vec![0u8; 12], pattern: Some([0, 1, 1, 2]), note: None, picture: None }); - crate::vendor::declare_strip_len(&mut f, 12, declared); - assert_eq!(probe(&f), Some(crate::RawFormat::Srw)); - assert!(matches!(decode(&f), Err(RawError::Corrupt(_))), "compression {compression}"); - } - } -} diff --git a/crates/raw/src/wb_estimate.rs b/crates/raw/src/wb_estimate.rs index 13cb9f8daf..9ae488a6dd 100644 --- a/crates/raw/src/wb_estimate.rs +++ b/crates/raw/src/wb_estimate.rs @@ -144,7 +144,7 @@ mod tests { // RGGB, R at 400, G at 800, B at 200 above a black of 100 let (w, h) = (8, 8); let d: Vec = (0..w * h).map(|i| [500, 900, 900, 300][(i / w % 2) * 2 + i % 2]).collect(); - let cfa = Cfa::bayer_static("RGGB"); + let cfa = crate::bayer("RGGB"); let black = BlackLevel::uniform(100.0); let f = Frame { data: &d, width: w, crop: Rect::new(0, 0, w, h), cfa: &cfa, black: &black, white: 4095.0 }; assert_eq!(as_shot(b"not a raw", &f), Some([2.0, 1.0, 4.0])); From 264330d7e9eb3f5990b2cd9e7de799145b687ce5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 00:03:58 +0000 Subject: [PATCH 12/23] meta: migrate DateTime, gpx, and xmp_merge to craft-metadata --- Cargo.lock | 28 +- Cargo.toml | 2 + crates/meta/Cargo.toml | 1 + crates/meta/src/datetime.rs | 320 ---------------------- crates/meta/src/gpx.rs | 491 --------------------------------- crates/meta/src/lib.rs | 31 ++- crates/meta/src/xmp.rs | 24 +- crates/meta/src/xmp_merge.rs | 513 ----------------------------------- crates/raw/src/vendor/crw.rs | 1 + 9 files changed, 55 insertions(+), 1356 deletions(-) delete mode 100644 crates/meta/src/datetime.rs delete mode 100644 crates/meta/src/gpx.rs delete mode 100644 crates/meta/src/xmp_merge.rs diff --git a/Cargo.lock b/Cargo.lock index a715ac36cb..d9da7420ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1239,6 +1239,18 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=68b8171b0d2c133d4a99ed3ae621e9ebb74a703f#68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" +dependencies = [ + "brotli-decompressor 6.0.1", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=68b8171b0d2c133d4a99ed3ae621e9ebb74a703f)", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1248,6 +1260,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=68b8171b0d2c133d4a99ed3ae621e9ebb74a703f#68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -3773,7 +3794,7 @@ dependencies = [ "chrono", "craft-docpath", "craft-heif", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d)", "crc32fast", "fs4", "harfrust 0.13.3", @@ -3930,7 +3951,8 @@ version = "0.21.1" dependencies = [ "chrono", "craft-heif", - "craft-tiff", + "craft-metadata", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d)", "lightcraft-geom", "proptest", "quick-xml 0.41.0", @@ -3987,7 +4009,7 @@ version = "0.21.1" dependencies = [ "chrono", "craft-crw", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d)", "dhat", "jpeg-encoder", "jxl-oxide", diff --git a/Cargo.toml b/Cargo.toml index f7dd56589e..db2633f4dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,8 @@ craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9 craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } # Canon CRW decoder shared with the other Craft apps craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" } +# Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949) +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index 1b146c99da..c40c57cdda 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-tiff = { workspace = true } +craft-metadata = { workspace = true } lightcraft-geom = { workspace = true } serde = { workspace = true } quick-xml = { workspace = true } diff --git a/crates/meta/src/datetime.rs b/crates/meta/src/datetime.rs deleted file mode 100644 index 4141f4ae07..0000000000 --- a/crates/meta/src/datetime.rs +++ /dev/null @@ -1,320 +0,0 @@ -//! Capture date/time with optional UTC offset (Exif `DateTimeOriginal` + `OffsetTimeOriginal`, ISO 8601 in XMP). - -use serde::{Deserialize, Serialize}; - -/// A civil date-time as recorded by the camera; `offset_minutes` is the UTC offset when known. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct DateTime { - pub year: u16, - pub month: u8, - pub day: u8, - pub hour: u8, - pub minute: u8, - pub second: u8, - /// Sub-second part in milliseconds. - pub millis: u16, - pub offset_minutes: Option, -} - -fn num(s: &str) -> Option { - if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - s.parse().ok() -} - -impl DateTime { - fn valid(self) -> Option { - // A timestamp must represent a real Gregorian calendar day, not just - // numbers in the range 1..=31. Invalid dates would otherwise be - // accepted from EXIF/XMP and silently normalized during time arithmetic. - // chrono rejects impossible days (leap years and all); the time is checked - // by hand so a leap second (`second == 60`) stays acceptable. - let day_ok = self.year > 0 && chrono::NaiveDate::from_ymd_opt(i32::from(self.year), u32::from(self.month), u32::from(self.day)).is_some(); - let ok = day_ok && self.hour < 24 && self.minute < 60 && self.second < 61 && self.offset_minutes.is_none_or(|o| o.unsigned_abs() <= 18 * 60); - ok.then_some(self) - } - - /// Exif form `YYYY:MM:DD HH:MM:SS` (also tolerates `-` date separators and a missing time). - pub fn parse_exif(s: &str) -> Option { - let s = s.trim().trim_end_matches('\0'); - let (d, t) = s.split_once([' ', 'T']).unwrap_or((s, "")); - let dp: Vec<&str> = d.split([':', '-']).collect(); - if dp.len() != 3 { - return None; - } - let (hour, minute, second) = if t.is_empty() { - (0, 0, 0) - } else { - let mut parts = t.split(':'); - let hour = num(parts.next()?.trim())?; - let minute = parts.next().map(|part| num(part.trim())).unwrap_or(Some(0))?; - let second = parts.next().map(|part| num(part.trim())).unwrap_or(Some(0))?; - // A fourth value cannot be represented; accepting only the prefix could turn a - // malformed DateTimeOriginal into a plausible capture time and block fallbacks. - if parts.next().is_some() { - return None; - } - (hour, minute, second) - }; - DateTime { - year: num(dp[0])?.try_into().ok()?, - month: num(dp[1])?.try_into().ok()?, - day: num(dp[2])?.try_into().ok()?, - hour: hour.try_into().ok()?, - minute: minute.try_into().ok()?, - second: second.try_into().ok()?, - millis: 0, - offset_minutes: None, - } - .valid() - } - - /// Exif `OffsetTime*` form `+HH:MM` / `-HH:MM` (or `Z`). - pub fn parse_offset(s: &str) -> Option { - let s = s.trim().trim_end_matches('\0'); - if s == "Z" { - return Some(0); - } - let (sign, rest) = match s.as_bytes().first()? { - b'+' => (1, &s[1..]), - b'-' => (-1, &s[1..]), - _ => return None, - }; - let (h, m) = match rest.split_once(':') { - Some((h, m)) => (num(h)?, num(m)?), - None if rest.len() == 4 => (num(rest.get(..2)?)?, num(rest.get(2..)?)?), - None => (num(rest)?, 0), - }; - if h > 18 || m > 59 || (h == 18 && m > 0) { - return None; - } - Some(sign * (h * 60 + m) as i16) - } - - /// Set the sub-second part from an Exif `SubSecTime*` string (digits are a decimal fraction). - pub fn with_subsec(mut self, s: &str) -> DateTime { - let digits: String = s.trim().chars().take_while(|c| c.is_ascii_digit()).take(3).collect(); - if !digits.is_empty() { - let v: u16 = digits.parse().unwrap_or(0); - self.millis = v * 10u16.pow(3 - digits.len() as u32); - } - self - } - - /// ISO 8601 (XMP date): `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDThh:mm[:ss[.s+]][TZD]`. - pub fn parse_iso(s: &str) -> Option { - let s = s.trim(); - let (d, t) = match s.split_once('T') { - Some((d, t)) if !t.is_empty() => (d, t), - Some(_) => return None, - None => (s, ""), - }; - let dp: Vec<&str> = d.split('-').collect(); - let year = num(dp.first()?)?.try_into().ok()?; - let month = dp.get(1).map(|m| num(m)).unwrap_or(Some(1))?.try_into().ok()?; - let day = dp.get(2).map(|m| num(m)).unwrap_or(Some(1))?.try_into().ok()?; - if dp.len() > 3 { - return None; - } - let mut dt = DateTime { year, month, day, ..Default::default() }; - if !t.is_empty() { - let (clock, off) = match t.find(['Z', '+', '-']) { - Some(i) => (&t[..i], Some(&t[i..])), - None => (t, None), - }; - let mut cp = clock.split(':'); - dt.hour = num(cp.next()?)?.try_into().ok()?; - dt.minute = num(cp.next()?)?.try_into().ok()?; - if let Some(sec) = cp.next() { - let (whole, fraction) = match sec.split_once('.') { - Some((whole, fraction)) => { - if fraction.is_empty() || !fraction.bytes().all(|b| b.is_ascii_digit()) { - return None; - } - (whole, Some(fraction)) - } - None => (sec, None), - }; - dt.second = num(whole)?.try_into().ok()?; - if let Some(fraction) = fraction { - dt = dt.with_subsec(fraction); - } - } - if cp.next().is_some() { - return None; - } - if let Some(o) = off { - dt.offset_minutes = Some(Self::parse_offset(o)?); - } - } - dt.valid() - } - - /// Exif form `YYYY:MM:DD HH:MM:SS`. - pub fn to_exif(&self) -> String { - format!("{:04}:{:02}:{:02} {:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second) - } - - /// ISO 8601 with milliseconds when non-zero and the offset when known. - pub fn to_iso(&self) -> String { - let mut s = format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second); - if self.millis != 0 { - s += &format!(".{:03}", self.millis); - } - if let Some(o) = self.offset_minutes { - let sign = if o < 0 { '-' } else { '+' }; - let o = o.unsigned_abs(); - s += &format!("{sign}{:02}:{:02}", o / 60, o % 60); - } - s - } - - /// Seconds since 1970-01-01T00:00:00 of the civil time (UTC when the offset is known, else "local" seconds). - pub fn unix_seconds(&self) -> i64 { - // Every `DateTime` reaching here is a real calendar day (`valid()` ran in the parsers); - // an out-of-range one (built by hand) reads as the epoch rather than panicking. - let days = chrono::NaiveDate::from_ymd_opt(i32::from(self.year), u32::from(self.month), u32::from(self.day)) - .zip(chrono::NaiveDate::from_ymd_opt(1970, 1, 1)) - .map(|(d, epoch)| (d - epoch).num_days()) - .unwrap_or(0); - days * 86400 + self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64 - self.offset_minutes.unwrap_or(0) as i64 * 60 - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn exif_forms() { - let d = DateTime::parse_exif("2024:06:01 13:45:59").unwrap(); - assert_eq!((d.year, d.month, d.day, d.hour, d.minute, d.second), (2024, 6, 1, 13, 45, 59)); - assert_eq!(d.to_exif(), "2024:06:01 13:45:59"); - assert!(DateTime::parse_exif("0000:00:00 00:00:00").is_none()); - assert!(DateTime::parse_exif(" : : : : ").is_none()); - assert!(DateTime::parse_exif("2024:13:01 00:00:00").is_none()); - // Invalid calendar days must never enter persisted capture metadata. - for value in ["2023:02:29", "2024:02:30", "2024:04:31", "1900:02:29", "2024:01:00"] { - assert!(DateTime::parse_exif(value).is_none(), "{value}"); - } - assert!(DateTime::parse_exif("2024:02:29").is_some()); - assert!(DateTime::parse_exif("2000:02:29").is_some()); - for value in ["2023-02-29", "2024-02-30", "1900-02-29", "2024-06-31T10:00:00Z"] { - assert!(DateTime::parse_iso(value).is_none(), "{value}"); - } - assert!(DateTime::parse_iso("2000-02-29T23:59:59Z").is_some()); - assert_eq!(DateTime::parse_exif("2024-06-01").unwrap().hour, 0); - assert_eq!(DateTime::parse_exif("2024:06:01 13:45:59").unwrap().with_subsec("5").millis, 500); - assert_eq!(DateTime::parse_exif("2024:06:01 13:45:59").unwrap().with_subsec("0123").millis, 12); - } - - #[test] - fn exif_clock_rejects_extra_components() { - for value in - ["2026:01:01 12:34:56:99", "2026:01:01 12:34:56:junk", "2026:01:01 12:34:56:", "2026:01:01 12:34:56::", "2026:01:01 12:34:56:99:junk"] - { - assert!(DateTime::parse_exif(value).is_none(), "accepted malformed EXIF clock {value:?}"); - } - } - - #[test] - fn exif_clock_supported_forms_keep_their_meaning() { - for (value, expected) in [ - ("2026:01:01", "2026-01-01T00:00:00"), - ("2026:01:01 12", "2026-01-01T12:00:00"), - ("2026:01:01 12:34", "2026-01-01T12:34:00"), - ("2026:01:01 12:34:56", "2026-01-01T12:34:56"), - ("2026-01-01T12:34:56", "2026-01-01T12:34:56"), - (" 2026:01:01 12:34:56\0", "2026-01-01T12:34:56"), - ("2026:01:01T12:34:60", "2026-01-01T12:34:60"), - ] { - assert_eq!(DateTime::parse_exif(value).map(|date| date.to_iso()), Some(expected.to_string()), "{value:?}"); - } - } - - #[test] - fn offsets() { - assert_eq!(DateTime::parse_offset("+02:00"), Some(120)); - assert_eq!(DateTime::parse_offset("-05:30"), Some(-330)); - assert_eq!(DateTime::parse_offset("Z"), Some(0)); - assert_eq!(DateTime::parse_offset("+0930"), Some(570)); - assert_eq!(DateTime::parse_offset("+18:00"), Some(1080)); - assert_eq!(DateTime::parse_offset("-18:00"), Some(-1080)); - assert_eq!(DateTime::parse_offset("+18:01"), None); - assert_eq!(DateTime::parse_offset("-18:01"), None); - assert_eq!(DateTime::parse_offset(" : "), None); - assert_eq!(DateTime::parse_offset("+99:00"), None); - } - - #[test] - fn extreme_offsets_do_not_overflow() { - // `DateTime` deserializes with public fields, so an offset can arrive without passing `valid()` - let d = DateTime { offset_minutes: Some(i16::MIN), ..DateTime::parse_iso("2024-06-01T13:45:59").unwrap() }; - assert_eq!(d.to_iso(), "2024-06-01T13:45:59-546:08"); - assert_eq!(d.valid(), None); - } - - #[test] - fn unicode_offsets_are_rejected_without_panicking() { - for offset in ["+1€", "-1€", "+€1", "-€1"] { - assert_eq!(DateTime::parse_offset(offset), None); - let date = format!("2024-06-01T13:45:59{offset}"); - let metadata = crate::Metadata { capture_time: DateTime::parse_iso("2024-06-01T13:45:59Z"), ..Default::default() }; - let xmp = crate::write_xmp(&metadata, None).replace("2024-06-01T13:45:59+00:00", &date); - assert!(crate::parse_xmp(&xmp).unwrap().metadata.capture_time.is_none()); - } - } - - #[test] - fn iso_roundtrip() { - for s in ["2024-06-01T13:45:59", "2024-06-01T13:45:59.250+02:00", "1999-12-31T23:59:00-05:30", "2024-02-29T00:00:00Z"] { - let d = DateTime::parse_iso(s).unwrap(); - let again = DateTime::parse_iso(&d.to_iso()).unwrap(); - assert_eq!(d, again, "{s}"); - } - assert_eq!(DateTime::parse_iso("2024-02-29T00:00:00Z").unwrap().to_iso(), "2024-02-29T00:00:00+00:00"); - let d = DateTime::parse_iso("2019").unwrap(); - assert_eq!((d.year, d.month, d.day), (2019, 1, 1)); - assert_eq!(DateTime::parse_iso("2019-07-04T10:11").unwrap().minute, 11); - assert!(DateTime::parse_iso("nonsense").is_none()); - assert!(DateTime::parse_iso("2019-07-04Tab:cd").is_none()); - } - - #[test] - fn iso_rejects_incomplete_or_unconsumed_clock_text() { - for value in [ - "2026-01-01T", - "2026-01-01T12:34:56:99Z", - "2026-01-01T12:34:56.Z", - "2026-01-01T12:34:56.123junkZ", - "2026-01-01T12:34:56.1.2Z", - "2026-01-01T12:34:56.12 3Z", - "2026-01-01T12:34:56:99Z", - "2026-01-01T12::34Z", - ] { - assert!(DateTime::parse_iso(value).is_none(), "accepted malformed timestamp {value:?}"); - } - } - - #[test] - fn iso_validates_clock_while_preserving_supported_forms() { - assert_eq!(DateTime::parse_iso("2019").unwrap().to_iso(), "2019-01-01T00:00:00"); - assert_eq!(DateTime::parse_iso("2019-07").unwrap().to_iso(), "2019-07-01T00:00:00"); - assert_eq!(DateTime::parse_iso("2019-07-04").unwrap().to_iso(), "2019-07-04T00:00:00"); - assert_eq!(DateTime::parse_iso("2019-07-04T10:11").unwrap().to_iso(), "2019-07-04T10:11:00"); - assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12").unwrap().to_iso(), "2019-07-04T10:11:12"); - assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12Z").unwrap().offset_minutes, Some(0)); - assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12-05:30").unwrap().offset_minutes, Some(-330)); - assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12.123456Z").unwrap().millis, 123); - assert_eq!(DateTime::parse_iso(" 2019-07-04T10:11:12.5Z ").unwrap().millis, 500); - assert_eq!(DateTime::parse_iso("2019-07-04T10:11:60Z").unwrap().second, 60); - } - - #[test] - fn unix() { - assert_eq!(DateTime::parse_iso("1970-01-01T00:00:00Z").unwrap().unix_seconds(), 0); - assert_eq!(DateTime::parse_iso("2000-03-01T00:00:00Z").unwrap().unix_seconds(), 951868800); - assert_eq!(DateTime::parse_iso("2000-03-01T02:00:00+02:00").unwrap().unix_seconds(), 951868800); - } -} diff --git a/crates/meta/src/gpx.rs b/crates/meta/src/gpx.rs deleted file mode 100644 index 691a2b7e19..0000000000 --- a/crates/meta/src/gpx.rs +++ /dev/null @@ -1,491 +0,0 @@ -//! GPS track logs in GPX 1.0 / 1.1 (the open GPS Exchange Format, ): -//! the timed track points of every ``, and the position at any moment for geotagging photos. -//! -//! What we use from the format: `` → `` → `` with optional `` -//! (metres) and `"#; - assert!(matches!(parse_gpx(wrong_close), Err(GpxError::Xml(_)))); - assert!( - parse_gpx("") - .unwrap() - .points - .is_empty() - ); - let deep = "".to_string() + &"".repeat(100); - assert_eq!(parse_gpx(&deep), Err(GpxError::TooComplex)); - } -} diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 4844168119..4bc0bb2660 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -16,29 +16,48 @@ mod container; pub mod cr3; -mod datetime; mod exif; pub mod focus; mod focus_read; -mod gpx; pub mod heif; mod iptc; pub mod mrw; mod psd; pub mod tags; mod xmp; -mod xmp_merge; pub use container::{Embedded, embedded, jpeg_segments, png_chunks, webp_chunks}; -pub use datetime::DateTime; +pub use craft_metadata::DateTime; +pub use craft_metadata::{GpxError, Match, TrackPoint, Tracklog, parse_gpx}; pub use exif::{from_tiff, read_exif, strip_exif_header, try_read_exif, try_read_exif_with, write_exif}; pub use focus::FocusPoint; -pub use gpx::{GpxError, Match, TrackPoint, Tracklog, parse_gpx}; pub use iptc::parse_iptc; pub use lightcraft_geom::{Orientation, Rect}; pub use tags::{TagRow, file_tag_rows, tag_rows}; pub use xmp::{CRS_NS, LC_NS, XmpData, XmpError, XmpValue, parse_xmp, write_xmp, write_xmp_lc}; -pub use xmp_merge::{MergeRules, merge_xmp}; + +/// Which properties [`merge_xmp`] takes from the fresh packet. +#[derive(Clone, Copy, Debug, Default)] +pub struct MergeRules<'a> { + /// Always replaced: removed from the existing packet, written from the fresh one if stated. + pub owned: &'a [&'a str], + /// Replaced only when the fresh packet states them; otherwise the existing value stays. + pub owned_if_present: &'a [&'a str], +} + +/// Merge `fresh` into `existing` following `rules`. +pub fn merge_xmp(existing: &str, fresh: &str, rules: MergeRules) -> Result { + let namespaces = [craft_metadata::XmpNamespace { prefix: "lc", uri: LC_NS }]; + craft_metadata::merge_xmp( + existing, + fresh, + craft_metadata::MergeRules { + owned: rules.owned, + owned_if_present: rules.owned_if_present, + namespaces: &namespaces, + }, + ) +} use serde::{Deserialize, Serialize}; diff --git a/crates/meta/src/xmp.rs b/crates/meta/src/xmp.rs index 2326b0f722..627d17d300 100644 --- a/crates/meta/src/xmp.rs +++ b/crates/meta/src/xmp.rs @@ -43,24 +43,7 @@ const NAMESPACES: &[(&str, &str)] = &[ /// The camera-raw-settings namespace URI (prefix `crs`), read for interchange only. pub const CRS_NS: &str = "http://ns.adobe.com/camera-raw-settings/1.0/"; -/// XMP read failure. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum XmpError { - Xml(String), - /// Nesting / size limits exceeded. - TooComplex, -} - -impl std::fmt::Display for XmpError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - XmpError::Xml(e) => write!(f, "XMP is not well-formed XML: {e}"), - XmpError::TooComplex => write!(f, "XMP packet too deeply nested or too large"), - } - } -} - -impl std::error::Error for XmpError {} +pub use craft_metadata::XmpError; /// Result of [`parse_xmp`]. #[derive(Clone, Debug, Default, PartialEq)] @@ -182,11 +165,6 @@ pub(crate) fn check_scopes(scopes: &[Vec<(String, String)>]) -> Result<(), XmpEr Ok(()) } -/// Names canonicalised by namespace URI (see [`NAMESPACES`]); conflicting foreign prefixes are opaque. -pub(crate) fn canonical_name(qname: &str, scopes: &[Vec<(String, String)>], opaque_budget: &mut usize) -> Result { - canonical(qname, scopes, opaque_budget) -} - fn canonical(qname: &str, scopes: &[Vec<(String, String)>], opaque_budget: &mut usize) -> Result { let (prefix, local) = qname.split_once(':').unwrap_or(("", qname)); if prefix == "xml" || prefix == "xmlns" { diff --git a/crates/meta/src/xmp_merge.rs b/crates/meta/src/xmp_merge.rs deleted file mode 100644 index f9c0efcf4c..0000000000 --- a/crates/meta/src/xmp_merge.rs +++ /dev/null @@ -1,513 +0,0 @@ -//! Merging a freshly written XMP packet into an existing one (a sidecar another application -//! wrote, e.g. with its develop settings and edit history), keeping everything the writer does not -//! own byte for byte. -//! -//! The existing packet is scanned once (namespace-resolved, with byte positions). Only top-level -//! properties of the `rdf:Description` elements directly under `rdf:RDF` are considered, in -//! attribute form (`xmp:Rating="3"`) and element form (`…`): -//! - properties the writer owns ([`MergeRules::owned`]) are removed, and written from the fresh -//! packet when it has them (so a cleared field is cleared in the file too); -//! - properties owned only when stated ([`MergeRules::owned_if_present`]) are replaced when the -//! fresh packet has them and kept otherwise; -//! - any other property of the fresh packet (e.g. `xmp:CreatorTool`) is not written: the file -//! keeps describing itself as its creator left it; -//! - everything else — other namespaces (e.g. `crs:`), `xmpMM:History`, unknown properties, -//! comments, the packet wrapper and padding — is copied unchanged. -//! -//! The written properties go into one new `rdf:Description` (declaring its own namespaces, so -//! the existing prefix bindings never matter) just before ``. A description left empty -//! by the removals is dropped, so repeated saves don't accumulate. The result is checked by -//! parsing it again: every written property must read back as in the fresh packet. - -use std::collections::{BTreeSet, HashSet}; - -use quick_xml::events::Event; - -use crate::xmp::{MAX_OPAQUE_NAME_BYTES, XmpError, canonical_name, check_scopes, parse_xmp, unescape_attr}; - -/// Which properties [`merge_xmp`] takes from the fresh packet. Names are canonical -/// `prefix:name` (prefixes as [`crate::parse_xmp`] reports them); `prefix:*` is a whole namespace. -#[derive(Clone, Copy, Debug, Default)] -pub struct MergeRules<'a> { - /// Always replaced: removed from the existing packet, written from the fresh one if stated. - pub owned: &'a [&'a str], - /// Replaced only when the fresh packet states them; otherwise the existing value stays. - pub owned_if_present: &'a [&'a str], -} - -fn listed(list: &[&str], name: &str) -> bool { - list.iter().any(|p| match p.strip_suffix('*') { - Some(ns) => name.starts_with(ns), - None => *p == name, - }) -} - -#[derive(Debug)] -struct Attr { - raw: String, - name: String, - /// The value as written (still escaped). - value: String, -} - -#[derive(Debug)] -struct Prop { - name: String, - start: usize, - end: usize, -} - -#[derive(Debug, Default)] -struct Desc { - tag_start: usize, - tag_end: usize, - /// The element name as written (`rdf:Description`, or another prefix for the RDF namespace). - raw_name: String, - empty: bool, - attrs: Vec, - props: Vec, - /// The end of `` (`tag_end` when self-closing). - end: usize, -} - -#[derive(Debug, Default)] -struct Scan { - descs: Vec, - /// Where the first `` starts. - rdf_close: Option, - /// The span of a self-closing `` (used only when there is no ``). - rdf_empty: Option<(usize, usize)>, -} - -enum Kind { - Other, - Rdf, - Desc(usize), - Prop { desc: usize, start: usize, name: String }, -} - -fn is_meta_attr(name: &str) -> bool { - name.starts_with("xmlns") - || matches!(name, "rdf:about" | "rdf:ID" | "rdf:nodeID" | "xml:lang" | "rdf:parseType" | "rdf:resource" | "rdf:datatype") -} - -fn pos(r: &quick_xml::Reader<&[u8]>) -> usize { - usize::try_from(r.buffer_position()).unwrap_or(usize::MAX) -} - -/// Locate the descriptions, their top-level properties and `` in a packet. -fn scan(s: &str) -> Result { - let mut reader = quick_xml::Reader::from_reader(s.as_bytes()); - reader.config_mut().check_end_names = true; - let mut out = Scan::default(); - let mut stack: Vec = Vec::new(); - let mut scopes: Vec> = vec![vec![("xml".into(), "http://www.w3.org/XML/1998/namespace".into())]]; - let mut count = 0usize; - let mut opaque_budget = MAX_OPAQUE_NAME_BYTES; - loop { - let before = pos(&reader); - let ev = reader.read_event().map_err(|e| XmpError::Xml(e.to_string()))?; - let after = pos(&reader); - match ev { - Event::Start(ref e) | Event::Empty(ref e) => { - count += 1; - if count > 200_000 || stack.len() > 64 { - return Err(XmpError::TooComplex); - } - let empty = matches!(ev, Event::Empty(_)); - let mut scope = Vec::new(); - let mut raw_attrs = Vec::new(); - // repeated names are refused with a set, in linear time (quick-xml's own check is quadratic) - let mut seen = HashSet::new(); - for a in e.attributes().with_checks(false) { - let a = a.map_err(|e| XmpError::Xml(e.to_string()))?; - let k = String::from_utf8_lossy(a.key.as_ref()).into_owned(); - if !seen.insert(k.clone()) { - return Err(XmpError::Xml(format!("repeated attribute {k}"))); - } - let v = String::from_utf8_lossy(&a.value).into_owned(); - if k == "xmlns" { - scope.push((String::new(), unescape_attr(&v))); - } else if let Some(p) = k.strip_prefix("xmlns:") { - scope.push((p.to_string(), unescape_attr(&v))); - } - raw_attrs.push((k, v)); - } - scopes.push(scope); - check_scopes(&scopes)?; - let raw_name = String::from_utf8_lossy(e.name().as_ref()).into_owned(); - let name = canonical_name(&raw_name, &scopes, &mut opaque_budget)?; - let kind = match stack.last() { - Some(Kind::Rdf) if name == "rdf:Description" => { - let attrs = raw_attrs - .into_iter() - .map(|(raw, value)| Ok(Attr { name: canonical_name(&raw, &scopes, &mut opaque_budget)?, raw, value })) - .collect::>()?; - out.descs.push(Desc { tag_start: before, tag_end: after, raw_name, empty, attrs, props: Vec::new(), end: after }); - Kind::Desc(out.descs.len() - 1) - } - Some(Kind::Desc(i)) => Kind::Prop { desc: *i, start: before, name }, - _ if name == "rdf:RDF" && out.rdf_close.is_none() => Kind::Rdf, - _ => Kind::Other, - }; - if empty { - if matches!(kind, Kind::Rdf) { - out.rdf_empty = out.rdf_empty.or(Some((before, after))); - } - scopes.pop(); - if let Kind::Prop { desc, start, name } = kind - && let Some(d) = out.descs.get_mut(desc) - { - d.props.push(Prop { name, start, end: after }); - } - } else { - stack.push(kind); - } - } - Event::End(_) => { - scopes.pop(); - match stack.pop() { - Some(Kind::Prop { desc, start, name }) => { - if let Some(d) = out.descs.get_mut(desc) { - d.props.push(Prop { name, start, end: after }); - } - } - Some(Kind::Desc(i)) => { - if let Some(d) = out.descs.get_mut(i) { - d.end = after; - } - } - Some(Kind::Rdf) => out.rdf_close = out.rdf_close.or(Some(before)), - Some(Kind::Other) => {} - None => return Err(XmpError::Xml("unbalanced end tag".into())), - } - } - Event::Eof => break, - _ => {} - } - } - if !stack.is_empty() { - return Err(XmpError::Xml("unclosed element".into())); - } - Ok(out) -} - -/// `start` moved back over the indentation and line break before it (so a removed property -/// takes its line with it). -fn line_start(s: &str, start: usize) -> usize { - let b = s.as_bytes(); - let mut i = start; - while i > 0 && matches!(b.get(i - 1), Some(b' ' | b'\t')) { - i -= 1; - } - if i > 0 && b.get(i - 1) == Some(&b'\n') { - i -= 1; - if i > 0 && b.get(i - 1) == Some(&b'\r') { - i -= 1; - } - } - i -} - -/// Merge `fresh` (a packet as [`crate::write_xmp_lc`] writes it) into `existing` following -/// `rules` (see the module docs). Fails — and the caller must not overwrite `existing` blindly — -/// when `existing` isn't a well-formed XMP packet. -pub fn merge_xmp(existing: &str, fresh: &str, rules: MergeRules) -> Result { - let (bom, old) = match existing.strip_prefix('\u{feff}') { - Some(rest) => ("\u{feff}", rest), - None => ("", existing), - }; - parse_xmp(old)?; - let ex = scan(old)?; - if ex.rdf_close.is_none() && ex.rdf_empty.is_none() { - return Err(XmpError::Xml("no rdf:RDF element".into())); - } - let new = scan(fresh)?; - let fresh_desc = new.descs.first().ok_or_else(|| XmpError::Xml("the new packet has no rdf:Description".into()))?; - let fresh_names: BTreeSet<&str> = fresh_desc.props.iter().map(|p| p.name.as_str()).collect(); - let remove = |name: &str| listed(rules.owned, name) || (listed(rules.owned_if_present, name) && fresh_names.contains(name)); - let write = |name: &str| listed(rules.owned, name) || listed(rules.owned_if_present, name); - - // edits on `old`: (start, end, replacement), applied back to front - let mut edits: Vec<(usize, usize, String)> = Vec::new(); - for d in &ex.descs { - let gone_attrs: Vec<&Attr> = d.attrs.iter().filter(|a| !is_meta_attr(&a.name) && remove(&a.name)).collect(); - let gone_props: Vec<&Prop> = d.props.iter().filter(|p| remove(&p.name)).collect(); - if gone_attrs.is_empty() && gone_props.is_empty() { - continue; - } - let attrs_left = d.attrs.iter().any(|a| !is_meta_attr(&a.name) && !remove(&a.name)); - if !attrs_left && gone_props.len() == d.props.len() { - // nothing of its own left: drop the whole description - edits.push((line_start(old, d.tag_start), d.end, String::new())); - continue; - } - if !gone_attrs.is_empty() { - let mut tag = format!("<{}", d.raw_name); - for a in d.attrs.iter().filter(|a| is_meta_attr(&a.name) || !remove(&a.name)) { - tag.push_str(&format!("\n {}=\"{}\"", a.raw, a.value.replace('"', """))); - } - tag.push_str(if d.empty { "/>" } else { ">" }); - edits.push((d.tag_start, d.tag_end, tag)); - } - for p in gone_props { - edits.push((line_start(old, p.start), p.end, String::new())); - } - } - // the new description: its own namespace declarations, the properties to write - let mut block = String::from("\n '); - let mut written = 0; - for p in fresh_desc.props.iter().filter(|p| write(&p.name)) { - let text = fresh.get(p.start..p.end).ok_or_else(|| XmpError::Xml("bad property span".into()))?; - block.push_str("\n "); - block.push_str(text); - written += 1; - } - block.push_str("\n "); - if written > 0 { - if let Some(rdf_close) = ex.rdf_close { - let at = old.get(..rdf_close).map_or(rdf_close, |h| h.trim_end().len()); - edits.push((at, at, block)); - } else if let Some((s, e)) = ex.rdf_empty { - // a self-closing `` is opened up around the new description - let tag = old.get(s..e).ok_or_else(|| XmpError::Xml("bad span".into()))?; - let open = tag.trim_end().strip_suffix("/>").ok_or_else(|| XmpError::Xml("bad rdf:RDF tag".into()))?; - let name = tag.get(1..).and_then(|t| t.split(|c: char| c.is_whitespace() || c == '/' || c == '>').next()).unwrap_or("rdf:RDF"); - edits.push((s, e, format!("{open}>{block}\n"))); - } - } - edits.sort_by_key(|e| (e.0, e.1)); - // overlapping edits can't happen (properties sit inside their description, which is either - // dropped whole or edited piecewise), but never splice blindly - let mut out = String::with_capacity(old.len() + 4096); - out.push_str(bom); - let mut at = 0; - for (s, e, r) in &edits { - if *s < at { - return Err(XmpError::Xml("overlapping edits".into())); - } - out.push_str(old.get(at..*s).ok_or_else(|| XmpError::Xml("bad span".into()))?); - out.push_str(r); - at = *e; - } - out.push_str(old.get(at..).ok_or_else(|| XmpError::Xml("bad span".into()))?); - - // read back: everything written must come out as written - let merged = parse_xmp(&out)?; - let want = parse_xmp(fresh)?; - for (k, v) in &want.properties { - let top = k.split('/').next().unwrap_or(k); - if write(top) && merged.properties.get(k) != Some(v) { - return Err(XmpError::Xml(format!("{k} did not survive the merge"))); - } - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - const RULES: MergeRules = - MergeRules { owned: &["xmp:Rating", "xmp:Label", "dc:subject", "dc:title", "lc:*"], owned_if_present: &["exif:DateTimeOriginal"] }; - - /// A sidecar as another raw developer writes it: attribute-form simple properties, develop - /// settings, a structured history, an unknown namespace. - const FOREIGN: &str = " - - - - - - - - - - - 0, 0 - 255, 255 - - - - - old - - - - - -"; - - /// With the packet's whitespace padding and trailer. - fn foreign() -> String { - format!("{FOREIGN}{}\n", " ".repeat(100)) - } - - fn fresh(rating: i8, keywords: &[&str]) -> String { - let m = crate::Metadata { - software: Some("LightCraft".into()), - rating: Some(rating), - keywords: keywords.iter().map(|k| k.to_string()).collect(), - ..Default::default() - }; - crate::write_xmp_lc(&m, &[("settings", "{\"a\":1}"), ("flag", "pick")]) - } - - #[test] - fn keeps_foreign_properties_and_replaces_owned_ones() { - let out = merge_xmp(&foreign(), &fresh(4, &["new", "two"]), RULES).unwrap(); - let d = parse_xmp(&out).unwrap(); - let p = |k: &str| d.properties.get(k).cloned().unwrap_or_default(); - assert_eq!(p("xmp:Rating"), vec!["4"]); - assert_eq!(p("dc:subject"), vec!["new", "two"]); - assert_eq!(p("lc:settings"), vec!["{\"a\":1}"]); - assert_eq!(p("lc:flag"), vec!["pick"]); - assert_eq!(p("xmp:CreatorTool"), vec!["Other App"], "not ours: kept"); - assert_eq!(p("crs:Exposure2012"), vec!["+0.50"]); - assert_eq!(p("foo:Thing").len(), 1); - // untouched parts are byte for byte the same - for part in [ - " \n \n \n \n ", - " \n \n 0, 0", - "crs:Contrast2012=\"-12\"", - "foo:Thing=\"a & b\"", - "\n", - &format!("\n{}\n", " ".repeat(100)), - ] { - assert!(out.contains(part), "lost {part:?} in\n{out}"); - } - assert!(!out.contains("xmp:Rating=\"2\"")); - assert!(!out.contains("old")); - // saving again changes only our part, and doesn't pile up descriptions - let again = merge_xmp(&out, &fresh(1, &[]), RULES).unwrap(); - let d = parse_xmp(&again).unwrap(); - assert_eq!(d.properties.get("xmp:Rating"), Some(&vec!["1".to_string()])); - assert!(!d.properties.contains_key("dc:subject"), "a cleared field is cleared"); - assert_eq!(again.matches(""; - let out = merge_xmp(ex, &fresh(3, &[]), RULES).unwrap(); - assert!(out.starts_with(""), "{out}"); - assert_eq!(parse_xmp(&out).unwrap().properties.get("xmp:Rating"), Some(&vec!["3".to_string()])); - assert!(merge_xmp("", &fresh(3, &[]), RULES).is_err(), "no RDF element at all"); - } - - #[test] - fn owned_if_present_and_prefix_independence() { - // the existing packet binds the namespaces to other prefixes, and has a capture time - let ex = "\ - "; - let out = merge_xmp(ex, &fresh(3, &[]), RULES).unwrap(); - let d = parse_xmp(&out).unwrap(); - assert_eq!(d.properties.get("xmp:Rating"), Some(&vec!["3".to_string()])); - assert_eq!(d.properties.get("exif:DateTimeOriginal"), Some(&vec!["2020-01-01T00:00:00".to_string()]), "fresh has none: kept"); - let mut m = crate::Metadata { rating: Some(3), ..Default::default() }; - m.capture_time = crate::DateTime::parse_iso("2024-05-06T07:08:09"); - let out = merge_xmp(ex, &crate::write_xmp_lc(&m, &[]), RULES).unwrap(); - let d = parse_xmp(&out).unwrap(); - assert_eq!(d.properties.get("exif:DateTimeOriginal"), Some(&vec!["2024-05-06T07:08:09".to_string()])); - } - - #[test] - fn preserves_foreign_properties_using_known_prefixes() { - for property in [r#"lc:Secret="keep-me"/>"#, r#">keep-me"#] { - let desc = format!(r#"{desc}"#); - let out = merge_xmp(&old, &fresh(4, &[]), RULES).unwrap(); - assert!(out.contains(&desc), "lost foreign description: {out}"); - assert_eq!(parse_xmp(&out).unwrap().metadata.rating, Some(4)); - assert_eq!(merge_xmp(&out, &fresh(4, &[]), RULES).unwrap(), out); - } - } - - #[test] - fn namespace_aliases_remain_distinct_during_merge() { - // The alias URI includes a character reference: scanning and parsing must resolve it identically. - let foreign = r#""#; - let old = format!( - r#"{foreign} - - "# - ); - let out = merge_xmp(&old, &fresh(5, &[]), RULES).unwrap(); - assert!(out.contains(foreign), "lost foreign rating: {out}"); - assert!(!out.contains("a:Rating="), "genuine alias must be replaced: {out}"); - assert_eq!(parse_xmp(&out).unwrap().metadata.rating, Some(5)); - assert_eq!(merge_xmp(&out, &fresh(5, &[]), RULES).unwrap(), out); - } - - #[test] - fn opaque_namespace_expansion_is_bounded() { - // A roughly 40 KiB packet must not expand the same long URI into every property name indefinitely. - let packet = format!( - r#"{}"#, - "a".repeat(1024), - "".repeat(5000) - ); - assert_eq!(parse_xmp(&packet).unwrap_err(), XmpError::TooComplex); - assert!(matches!(scan(&packet), Err(XmpError::TooComplex))); - } - - #[test] - fn many_attributes_scan_in_linear_time() { - // quick-xml's duplicate-name check compares each attribute with all earlier ones: 200 000 attributes on - // one description took over 20 s to scan, about 30 ms with the set - let n = 200_000; - let mut s = String::from( - "\ - "); - let t = std::time::Instant::now(); - let found = scan(&s).unwrap(); - let took = t.elapsed(); - assert_eq!(found.descs[0].attrs.len(), n + 2, "every attribute is read"); - assert!(took < std::time::Duration::from_secs(5), "{n} attributes took {took:?}"); - } - - #[test] - fn refuses_what_it_cannot_read() { - for bad in ["", "not xml at all", "", ""] { - assert!(merge_xmp(bad, &fresh(1, &[]), RULES).is_err(), "{bad:?}"); - } - } - - #[test] - fn refuses_a_repeated_attribute() { - // not well-formed XML (strict readers such as expat refuse it): no merge, so the caller keeps a backup. - // An owned name, a foreign one and one on a nested element (a merge would keep both copies of the last two). - for (once, twice) in [ - ("xmp:Rating=\"2\"", "xmp:Rating=\"2\" xmp:Rating=\"3\""), - ("foo:Thing=\"a & b\"", "foo:Thing=\"a & b\" foo:Thing=\"c\""), - ("stEvt:action=\"saved\"", "stEvt:action=\"saved\" stEvt:action=\"saved\""), - ] { - let ex = foreign().replace(once, twice); - assert!(merge_xmp(&ex, &fresh(1, &[]), RULES).is_err(), "{twice}"); - } - } -} diff --git a/crates/raw/src/vendor/crw.rs b/crates/raw/src/vendor/crw.rs index d48e1f229b..257f09e864 100644 --- a/crates/raw/src/vendor/crw.rs +++ b/crates/raw/src/vendor/crw.rs @@ -94,6 +94,7 @@ fn datetime_from_unix(t: i64) -> Option { second: u8::try_from(c.second()).ok()?, millis: 0, offset_minutes: None, + ..Default::default() }; ((1970..=2200).contains(&dt.year)).then_some(dt) } From 9cd6817c3bc903dfc4e72c0ac09871069168f98e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 00:09:58 +0000 Subject: [PATCH 13/23] codecs, meta: read PSD header and image resources with craft-psd (#4167) --- Cargo.lock | 33 ++++++++ Cargo.toml | 2 + crates/codecs/Cargo.toml | 1 + crates/codecs/src/psd.rs | 144 ++++++++++++++++------------------- crates/engine/src/sidecar.rs | 4 +- crates/meta/Cargo.toml | 1 + crates/meta/src/psd.rs | 63 ++------------- 7 files changed, 114 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d9da7420ba..18135fe084 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1251,6 +1251,17 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=68b8171b0d2c133d4a99ed3ae621e9ebb74a703f#68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1817,6 +1828,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -3708,6 +3733,7 @@ dependencies = [ "bytemuck", "craft-gainmap", "craft-heif", + "craft-psd", "dhat", "image", "image-webp", @@ -3952,6 +3978,7 @@ dependencies = [ "chrono", "craft-heif", "craft-metadata", + "craft-psd", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d)", "lightcraft-geom", "proptest", @@ -4331,6 +4358,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" diff --git a/Cargo.toml b/Cargo.toml index db2633f4dc..ea71942002 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,8 @@ craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0. craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } # HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" } +# PSD/PSB: the header, colour mode data and image resources (craft-libs#885). +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } lightcraft-denoise = { path = "crates/denoise", default-features = false } diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 019009d7c1..15b7fb0557 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -13,6 +13,7 @@ lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } craft-gainmap = { workspace = true } +craft-psd = { workspace = true } craft-heif = { workspace = true, optional = true } serde = { workspace = true } bytemuck = { workspace = true } diff --git a/crates/codecs/src/psd.rs b/crates/codecs/src/psd.rs index 7cccec0f8f..4eeaeec3d2 100644 --- a/crates/codecs/src/psd.rs +++ b/crates/codecs/src/psd.rs @@ -40,36 +40,51 @@ impl<'a> Rd<'a> { } } -pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { - let mut r = Rd { b: bytes, p: 0 }; - if r.take(4)? != b"8BPS" { - return Err(err("bad signature")); - } - let version = r.u16()?; - let psb = match version { - 1 => false, - 2 => true, - _ => return Err(err("bad version")), - }; - r.take(6)?; - let channels = r.u16()? as usize; - let height = r.u32()? as usize; - let width = r.u32()? as usize; - let depth = r.u16()?; - let mode = r.u16()?; - check_size(F, width as u64, height as u64, opts)?; - if channels == 0 || channels > 56 { - return Err(err("bad channel count")); - } +/// The header (`craft-psd`), colour mode data and image resources, with a reader at the layer and mask section. +struct Start<'a> { + psb: bool, + channels: usize, + width: usize, + height: usize, + depth: u16, + mode: u16, + color_mode_data: &'a [u8], + resources: Vec, + r: Rd<'a>, +} - // Colour mode data (palette for indexed). +fn start<'a>(bytes: &'a [u8], opts: &DecodeOptions) -> Result> { + // the size limit first, from the header's fixed fields, so an oversized file is `TooLarge` as for other formats + if let (Some(&[h0, h1, h2, h3]), Some(&[w0, w1, w2, w3])) = (bytes.get(14..18), bytes.get(18..22)) { + check_size(F, u64::from(u32::from_be_bytes([w0, w1, w2, w3])), u64::from(u32::from_be_bytes([h0, h1, h2, h3])), opts)?; + } + let h = craft_psd::Header::from_bytes(bytes).map_err(|e| match e { + craft_psd::PsdError::UnexpectedEof { .. } => err("truncated"), + e => err(&e.to_string()), + })?; + let mut r = Rd { b: bytes, p: 26 }; let cm_len = r.u32()? as usize; let color_mode_data = r.take(cm_len)?; - - // Image resources. let res_len = r.u32()? as usize; - let res = r.take(res_len)?; - let (icc, exif, xmp) = resources(res); + r.take(res_len)?; + // a resource section that doesn't parse is left out: the picture still decodes, without its profile and metadata + let resources = craft_psd::Head::from_bytes(bytes).map(|head| head.resources).unwrap_or_default(); + Ok(Start { + psb: h.version.is_psb(), + channels: usize::from(h.channels), + width: h.width as usize, + height: h.height as usize, + depth: h.depth, + mode: h.color_mode.as_u16(), + color_mode_data, + resources, + r, + }) +} + +pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { + let Start { psb, channels, width, height, depth, mode, color_mode_data, resources: res, mut r } = start(bytes, opts)?; + let (icc, exif, xmp) = resources(&res); // Layer and mask information: only the layer count sign matters (merged transparency). let lm_len = if psb { r.u64()? } else { u64::from(r.u32()?) }; @@ -342,29 +357,8 @@ fn packbits(src: &[u8], out: &mut Vec) { /// depth, colour mode or compression, or merged image data that runs past the end of the file /// (truncated). The run-length data itself is not unpacked. pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { - let mut r = Rd { b: bytes, p: 0 }; - if r.take(4)? != b"8BPS" { - return Err(err("bad signature")); - } - let psb = match r.u16()? { - 1 => false, - 2 => true, - _ => return Err(err("bad version")), - }; - r.take(6)?; - let channels = r.u16()? as usize; - let height = r.u32()? as usize; - let width = r.u32()? as usize; - let depth = r.u16()?; - let mode = r.u16()?; - check_size(F, width as u64, height as u64, &DecodeOptions::default())?; - if channels == 0 || channels > 56 { - return Err(err("bad channel count")); - } - let cm_len = r.u32()? as usize; - let color_mode_data = r.take(cm_len)?; - let res_len = r.u32()? as usize; - let (_, exif, _) = resources(r.take(res_len)?); + let Start { psb, channels, width, height, depth, mode, color_mode_data, resources: res, mut r } = start(bytes, &DecodeOptions::default())?; + let (_, exif, _) = resources(&res); let lm_len = if psb { r.u64()? as usize } else { r.u32()? as usize }; r.take(lm_len)?; let compression = r.u16()?; @@ -444,28 +438,12 @@ fn unpackbits(mut src: &[u8], row: &mut [u8]) -> Result<()> { Ok(()) } -fn resources(mut b: &[u8]) -> (Option>, Option>, Option) { - let (mut icc, mut exif, mut xmp) = (None, None, None); - while b.len() >= 12 && &b[0..4] == b"8BIM" { - let id = u16::from_be_bytes([b[4], b[5]]); - let name_len = b[6] as usize; - let name_total = (1 + name_len + 1) & !1; - let p = 6 + name_total; - if p + 4 > b.len() { - break; - } - let size = u32::from_be_bytes([b[p], b[p + 1], b[p + 2], b[p + 3]]) as usize; - let start = p + 4; - let Some(data) = start.checked_add(size).and_then(|end| b.get(start..end)) else { break }; - match id { - 1039 => icc = Some(data.to_vec()), - 1058 => exif = Some(if data.starts_with(b"Exif\0\0") { data[6..].to_vec() } else { data.to_vec() }), - 1060 => xmp = Some(String::from_utf8_lossy(data).trim_end_matches('\0').to_string()), - _ => {} - } - let next = start + ((size + 1) & !1); - b = b.get(next..).unwrap_or(&[]); - } +/// ICC (1039), EXIF (1058, without its optional `Exif\0\0` prefix) and XMP (1060) resources; the last of each id. +fn resources(res: &[craft_psd::ImageResource]) -> (Option>, Option>, Option) { + let last = |id: u16| res.iter().rev().find(|r| r.id == id).map(|r| r.data.as_slice()); + let icc = last(1039).map(<[u8]>::to_vec); + let exif = last(1058).map(|d| d.strip_prefix(b"Exif\0\0").unwrap_or(d).to_vec()); + let xmp = last(1060).map(|d| String::from_utf8_lossy(d).trim_end_matches('\0').to_string()); (icc, exif, xmp) } @@ -514,8 +492,8 @@ mod tests { #[test] fn huge_rle_with_truncated_count_table_is_rejected_before_allocating() { - // 1 × 2^30 px, 56 channels: the row table alone would be 56 Gi entries; the file has 4 bytes. - let mut b = header(56, 1, 1 << 30, 32, 3, 1); + // 1 × 300 000 px, 56 channels: the row table alone would be 16.8 M entries; the file has 4 bytes. + let mut b = header(56, 1, 300_000, 32, 3, 1); b.extend_from_slice(&[0, 0, 0, 0]); let e = decode(&b, &DecodeOptions::default()).unwrap_err(); assert!(matches!(e, Error::Malformed(_, ref m) if m == "truncated"), "{e:?}"); @@ -523,18 +501,30 @@ mod tests { #[test] fn huge_rle_of_empty_rows_is_rejected_before_allocating() { - // 2^30 × 1 px RGB at 32 bits: every row count is 0, which used to zero-pad 3 × 4 GiB. - let mut b = header(3, 1 << 30, 1, 32, 3, 1); + // 300 000 × 1 px RGB at 32 bits: every row count is 0, which used to zero-pad 3 × 1.2 MB. + let mut b = header(3, 300_000, 1, 32, 3, 1); b.extend_from_slice(&[0; 6]); let e = decode(&b, &DecodeOptions::default()).unwrap_err(); assert!(matches!(e, Error::Malformed(_, ref m) if m.contains("too short")), "{e:?}"); - // 1 Gpx RGB 8-bit whose (plausible) row counts claim more data than the file holds. - let mut b = header(3, 1 << 20, 1 << 10, 8, 3, 1); + // 0.27 Gpx RGB 8-bit whose (plausible) row counts claim more data than the file holds. + let mut b = header(3, 1 << 18, 1 << 10, 8, 3, 1); b.extend_from_slice(&[0xFF; 3 * 1024 * 2]); let e = decode(&b, &DecodeOptions::default()).unwrap_err(); assert!(matches!(e, Error::Malformed(_, ref m) if m == "truncated"), "{e:?}"); } + #[test] + fn a_damaged_resource_section_is_left_out() { + // a resource section of 4 bytes that is not an `8BIM` record: the picture decodes without it + let mut b = header(3, 1, 1, 8, 3, 0); + b[30..34].copy_from_slice(&4u32.to_be_bytes()); + b.splice(34..34, *b"JUNK"); + b.extend_from_slice(&[1, 2, 3]); + let d = decode(&b, &DecodeOptions::default()).unwrap(); + assert_eq!((d.width, d.height, d.icc.is_none()), (1, 1, true)); + assert_eq!(super::header(&b).unwrap(), (1, 1, 1)); + } + #[test] fn rle_repeat_run_past_row_width_is_an_error() { // 4 × 1 gray 8-bit; the single row is a 128-byte repeat run. diff --git a/crates/engine/src/sidecar.rs b/crates/engine/src/sidecar.rs index fdc72522f7..5a6b39a955 100644 --- a/crates/engine/src/sidecar.rs +++ b/crates/engine/src/sidecar.rs @@ -1495,8 +1495,10 @@ mod tests { section.push(0); } } + // a valid header: one RGB pixel, 8 bits let mut p = b"8BPS\0\x01".to_vec(); - p.resize(26, 0); + p.resize(12, 0); + p.extend_from_slice(&[0, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 8, 0, 3]); p.extend_from_slice(&(colour as u32).to_be_bytes()); p.resize(p.len() + colour, 0); p.extend_from_slice(&(section.len() as u32).to_be_bytes()); diff --git a/crates/meta/Cargo.toml b/crates/meta/Cargo.toml index c40c57cdda..084ea5927c 100644 --- a/crates/meta/Cargo.toml +++ b/crates/meta/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] craft-tiff = { workspace = true } craft-metadata = { workspace = true } +craft-psd = { workspace = true } lightcraft-geom = { workspace = true } serde = { workspace = true } quick-xml = { workspace = true } diff --git a/crates/meta/src/psd.rs b/crates/meta/src/psd.rs index ebdbdaf723..8fbe448d55 100644 --- a/crates/meta/src/psd.rs +++ b/crates/meta/src/psd.rs @@ -2,73 +2,24 @@ use crate::container::Embedded; -struct Reader<'a> { - bytes: &'a [u8], - offset: usize, -} - -impl<'a> Reader<'a> { - fn take(&mut self, length: usize) -> Option<&'a [u8]> { - let end = self.offset.checked_add(length)?; - let bytes = self.bytes.get(self.offset..end)?; - self.offset = end; - Some(bytes) - } - - fn u16(&mut self) -> Option { - let bytes = self.take(2)?; - Some(u16::from_be_bytes([*bytes.first()?, *bytes.get(1)?])) - } - - fn u32(&mut self) -> Option { - let bytes = self.take(4)?; - Some(u32::from_be_bytes([*bytes.first()?, *bytes.get(1)?, *bytes.get(2)?, *bytes.get(3)?])) - } -} - pub(crate) fn embedded(bytes: &[u8]) -> Embedded { parse(bytes).unwrap_or_default() } +/// The EXIF (1058) and XMP (1060) resources of the head `craft-psd` reads (header, colour mode data, image +/// resources). `None` for a head that does not parse, a second EXIF or XMP resource, or XMP that is not UTF-8. pub(crate) fn parse(bytes: &[u8]) -> Option { - let mut reader = Reader { bytes, offset: 0 }; - if reader.take(4)? != b"8BPS" || !matches!(reader.u16()?, 1 | 2) { - return None; - } - // The fixed header after the version is reserved bytes, channels, dimensions, depth and colour mode. - reader.take(6 + 2 + 4 + 4 + 2 + 2)?; - let colour_mode_length = usize::try_from(reader.u32()?).ok()?; - reader.take(colour_mode_length)?; - let resource_length = usize::try_from(reader.u32()?).ok()?; - let resources = reader.take(resource_length)?; - parse_resources(resources) -} - -fn parse_resources(bytes: &[u8]) -> Option { - let mut reader = Reader { bytes, offset: 0 }; + let head = craft_psd::Head::from_bytes(bytes).ok()?; let (mut exif, mut xmp) = (None, None); - while reader.offset < bytes.len() { - if reader.take(4)? != b"8BIM" { - return None; - } - let id = reader.u16()?; - let name_length = usize::from(*reader.take(1)?.first()?); - let pascal_length = 1usize.checked_add(name_length)?.checked_add(1)? & !1; - reader.take(pascal_length.checked_sub(1)?)?; - let data_length = usize::try_from(reader.u32()?).ok()?; - let data = reader.take(data_length)?; - if !data_length.is_multiple_of(2) { - reader.take(1)?; - } - match id { + for r in &head.resources { + match r.id { 1058 if exif.is_some() => return None, - 1058 => exif = Some(data), + 1058 => exif = Some(r.data.as_slice()), 1060 if xmp.is_some() => return None, - 1060 => xmp = Some(std::str::from_utf8(data).ok()?), + 1060 => xmp = Some(std::str::from_utf8(&r.data).ok()?), _ => {} } } - Some(Embedded { exif: exif.map(crate::strip_exif_header).map(<[u8]>::to_vec), xmp: xmp.map(|text| text.trim_end_matches('\0').to_string()), From 27791850a06e4b3d614142a4c1ed7e3c5ec17135 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 00:12:10 +0000 Subject: [PATCH 14/23] codecs: migrate GIF decoding and bounds to craft-gif (#4222) --- Cargo.lock | 9 ++ Cargo.toml | 1 + crates/codecs/Cargo.toml | 1 + crates/codecs/src/other.rs | 284 +++++++++++++------------------------ 4 files changed, 113 insertions(+), 182 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 18135fe084..ed7e5f1a3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1207,6 +1207,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=68b8171b0d2c133d4a99ed3ae621e9ebb74a703f#68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" +dependencies = [ + "image", +] + [[package]] name = "craft-heif" version = "0.1.0" @@ -3732,6 +3740,7 @@ dependencies = [ "avif-serialize", "bytemuck", "craft-gainmap", + "craft-gif", "craft-heif", "craft-psd", "dhat", diff --git a/Cargo.toml b/Cargo.toml index ea71942002..49cfa8163d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9 craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } # Canon CRW decoder shared with the other Craft apps craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "68b8171b0d2c133d4a99ed3ae621e9ebb74a703f", features = ["frames"] } # Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949) craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" } # craft-update: app-specific pretend versions apply to startup and manual checks. diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 15b7fb0557..3917e31ae9 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -13,6 +13,7 @@ lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } craft-gainmap = { workspace = true } +craft-gif = { workspace = true } craft-psd = { workspace = true } craft-heif = { workspace = true, optional = true } serde = { workspace = true } diff --git a/crates/codecs/src/other.rs b/crates/codecs/src/other.rs index 021cb08c82..b521f1aa52 100644 --- a/crates/codecs/src/other.rs +++ b/crates/codecs/src/other.rs @@ -1,4 +1,4 @@ -//! GIF (first frame) and BMP via the `image` crate's pure-Rust decoders. +//! GIF through `craft-gif` and BMP through the `image` crate's pure-Rust decoder. use crate::convert::{Buf, Meta, Model, Raw, check_size, finish}; use crate::{DecodeOptions, Decoded, Error, Format, Result}; @@ -13,10 +13,23 @@ const HEADER_DECODE_MAX_PIXELS: u64 = 4_000_000; /// header and must be one the file's bytes can fill; only a canvas small enough to be cheap is /// decoded (to catch truncation). Orientation is always 1: neither format carries EXIF here. pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> { + if format == Format::Gif { + let info = craft_gif::scan(bytes, 1).ok_or_else(|| Error::Malformed(format, "invalid GIF header".into()))?; + let (w, h) = (u32::from(info.width), u32::from(info.height)); + check_size(format, u64::from(w), u64::from(h), &DecodeOptions::default())?; + check_fillable(format, bytes, w, h)?; + if craft_gif::palette(bytes).is_none() { + return Err(Error::Malformed(format, "GIF has no readable colour table".into())); + } + if u64::from(w).saturating_mul(u64::from(h)) <= HEADER_DECODE_MAX_PIXELS { + let decoded = decode(bytes, format, &DecodeOptions::fit(64, 64))?; + return Ok((decoded.source_width, decoded.source_height, decoded.orientation)); + } + return Ok((w, h, 1)); + } let err = |e: image::ImageError| Error::Malformed(format, e.to_string()); let cursor = std::io::Cursor::new(bytes); let (w, h) = match format { - Format::Gif => image::codecs::gif::GifDecoder::new(cursor).map_err(err)?.dimensions(), Format::Bmp => image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?.dimensions(), _ => return Err(Error::Unsupported(format, "not handled by this decoder")), }; @@ -55,10 +68,9 @@ const SPARSE_MAX_PIXELS: u64 = 4_000_000; /// allocated, and is refused here instead. /// - An RLE BMP covers the pixels its runs and absolute blocks draw, as the decoder paints them; an /// end-of-row, end-of-bitmap or delta code leaves the rest blank. -/// - A GIF covers the pixels its first frame's LZW codes draw up to the end code. A code expands to -/// at most 4096 pixels and takes 12 bits once the table holds that many (fewer bits only while its -/// strings are shorter), so a frame larger than 2731 pixels per byte of LZW data is refused -/// outright. The screen around the frame may be larger, and is blank there. +/// - A GIF covers the pixels its first frame's LZW codes draw up to the end code. The shared GIF +/// reader counts code-string lengths without allocating decoded pixels; the screen around the +/// frame may be larger, and is blank there. /// /// Canvases the data leaves mostly blank are limited to [`SPARSE_MAX_PIXELS`]. fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> { @@ -67,15 +79,23 @@ fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> { // the pixels the file's data can cover let covered = match format { Format::Gif => { - // without a frame there is nothing to decode, and nothing to bound the canvas by - let Some(frame) = gif_first_frame(bytes) else { + // A frame's compressed data must cover its declared raster before it can justify the + // logical screen. This retains the old "can hold" refusal for truncated/empty frames. + let info = craft_gif::scan(bytes, 1).ok_or_else(|| Error::Malformed(format, "no readable first frame".into()))?; + let Some(frame) = info.frames.first() else { return Err(Error::Malformed(format, "no readable first frame".into())); }; - let (fw, fh, len) = (frame.width, frame.height, frame.data_len); - if area(fw, fh) > (len as u64).saturating_mul(2_731) { - return Err(Error::Malformed(format, format!("a {fw} × {fh} frame is far larger than its {len} bytes of pixel data can hold"))); + let frame_width = u32::from(frame.width); + let frame_height = u32::from(frame.height); + let compressed_bytes = + craft_gif::first_frame_compressed_bytes(bytes).ok_or_else(|| Error::Malformed(format, "no readable first frame".into()))?; + if area(frame_width, frame_height) > (compressed_bytes as u64).saturating_mul(2_731) { + return Err(Error::Malformed( + format, + format!("a {frame_width} × {frame_height} frame is far larger than its {compressed_bytes} bytes of pixel data can hold"), + )); } - gif_frame_pixels(bytes, frame.codes, area(fw, fh)) + craft_gif::first_frame_decoded_pixels(bytes).unwrap_or(0) } _ => match bmp_layout(bytes) { BmpLayout::Rle { offset, rle4 } => bmp_rle_pixels(bytes, offset, rle4, w, h), @@ -177,134 +197,13 @@ fn bmp_rle_pixels(bytes: &[u8], offset: usize, rle4: bool, w: u32, h: u32) -> u6 covered } -/// A GIF's first frame, from its image descriptor. -struct GifFrame { - width: u32, - height: u32, - /// Bytes of LZW data present (its palettes, comments and other extensions describe no pixels). - data_len: usize, - /// Position of its LZW minimum code size, which its data sub-blocks follow. - codes: usize, -} - -/// A GIF's first frame. `None` when the blocks before the frame can't be walked. -fn gif_first_frame(bytes: &[u8]) -> Option { - let u16_at = |i: usize| bytes.get(i..i.checked_add(2)?).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); - let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 }; - let mut pos = 13 + table(*bytes.get(10)?); - loop { - match *bytes.get(pos)? { - // extension: introducer, label, sub-blocks - 0x21 => pos = sub_blocks(bytes, pos.saturating_add(2)).1, - // image descriptor (separator, left, top, width, height, flags), local colour table, - // LZW minimum code size, data sub-blocks - 0x2C => { - let (fw, fh) = (u16_at(pos.saturating_add(5))?, u16_at(pos.saturating_add(7))?); - let codes = pos.saturating_add(10).saturating_add(table(*bytes.get(pos.saturating_add(9))?)); - let data_len = sub_blocks(bytes, codes.saturating_add(1)).0; - return Some(GifFrame { width: u32::from(fw), height: u32::from(fh), data_len, codes }); - } - _ => return None, - } - } -} - -/// The pixels a GIF frame's LZW codes draw, at most `max` (the frame's size): the codes are walked -/// up to the end code, an invalid code or the end of the data, keeping only the length of each -/// table string, never the pixels. Data after the end code draws nothing. Codes are packed -/// least-significant bit first across the data sub-blocks and start one bit wider than the minimum -/// code size; a code is one bit wider each time the table fills its width, up to 12 bits, and a -/// clear code starts the table again (GIF89a, appendix F). -fn gif_frame_pixels(bytes: &[u8], codes: usize, max: u64) -> u64 { - // the `gif` decoder accepts minimum code sizes of 1 to 11 - let Some(min_size) = bytes.get(codes).copied().filter(|s| (1..=11).contains(s)) else { - return 0; - }; - let clear = 1usize << min_size; - let end = clear + 1; - let mut lens = [1u16; 4096]; // string length of each code; literals (below `clear`) are 1 - let (mut width, mut next, mut prev) = (u32::from(min_size) + 1, end + 1, None::); - let (mut bits, mut held, mut covered) = (0u32, 0u32, 0u64); - let mut pos = codes.saturating_add(1); - while let Some(&n) = bytes.get(pos) { - let start = pos.saturating_add(1); - pos = start.saturating_add(usize::from(n)); - if n == 0 { - break; - } - for &byte in bytes.get(start..pos.min(bytes.len())).unwrap_or_default() { - bits |= u32::from(byte) << held; - held += 8; - while held >= width { - let code = (bits & ((1 << width) - 1)) as usize; - bits >>= width; - held -= width; - if code == clear { - (width, next, prev) = (u32::from(min_size) + 1, end + 1, None); - continue; - } - let len_of = |c: usize| lens.get(c).copied().unwrap_or(1); - let len = match prev { - _ if code == end => return covered, - None if code < clear => 1, - Some(_) if code < next => len_of(code), - // the string just being defined: the previous one and its first pixel - Some(p) if code == next => len_of(p).saturating_add(1), - _ => return covered, - }; - // each code after the first defines the next string: the previous one and a pixel - let defined = prev.map(|p| len_of(p).saturating_add(1)); - if let Some(defined) = defined - && let Some(slot) = lens.get_mut(next) - { - *slot = defined; - next += 1; - if next == 1 << width && width < 12 { - width += 1; - } - } - prev = Some(code); - covered = covered.saturating_add(u64::from(len)); - if covered >= max { - return max; - } - } - } - } - covered -} - -/// The GIF sub-blocks starting at `pos`: the data bytes present, and the position after them. -fn sub_blocks(bytes: &[u8], mut pos: usize) -> (usize, usize) { - let mut data = 0usize; - while let Some(&n) = bytes.get(pos) { - let start = pos.saturating_add(1); - if n == 0 { - return (data, start); - } - let end = start.saturating_add(usize::from(n)); - data = data.saturating_add(end.min(bytes.len()).saturating_sub(start)); - pos = end; - } - (data, pos) -} - pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Result { if format == Format::Gif { - gated_first_frame(bytes, opts)?; + return decode_gif(bytes, opts); } let err = |e: image::ImageError| Error::Malformed(format, e.to_string()); let cursor = std::io::Cursor::new(bytes); let (img, icc) = match format { - Format::Gif => { - let mut d = image::codecs::gif::GifDecoder::new(cursor).map_err(err)?; - let (w, h) = d.dimensions(); - check_size(format, w as u64, h as u64, opts)?; - check_fillable(format, bytes, w, h)?; - d.set_limits(limits(opts)).map_err(err)?; - let icc = d.icc_profile().ok().flatten(); - (DynamicImage::from_decoder(d).map_err(err)?, icc) - } Format::Bmp => { let mut d = image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?; let (w, h) = d.dimensions(); @@ -329,50 +228,39 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu finish(format, raw, Meta { icc, ..Default::default() }, (w, h), opts) } -/// Bounds a GIF's first image descriptor: the decoder composites frames into the logical screen -/// (bounded by [`check_size`] on the canvas) but allocates its own frame buffers at the frame's -/// declared size, which a small file can inflate far past the canvas. The canvas check cannot -/// see that size, so it is read from the block headers here. -fn gated_first_frame(bytes: &[u8], opts: &DecodeOptions) -> Result<()> { - // The constants of the header grammar: signature, logical screen descriptor (with its global - // colour table), extension blocks (0x21, skipped by their sub-block chains) and image - // descriptors (0x2C). - const SCREEN: usize = 13; - if bytes.len() < SCREEN { - return Ok(()); // too broken for a frame; the decoder reports the damage itself - } - let gct_entries = 1usize << (u32::from(bytes[10] & 0x07) + 1); // at most 256 - let gct_bytes = if (bytes[10] & 0x80) != 0 { gct_entries * 3 } else { 0 }; - let mut p = SCREEN.saturating_add(gct_bytes); - while let Some(&kind) = bytes.get(p) { - match kind { - 0x2C => { - // Image descriptor: two LE coordinates then two LE edges, after the separator. - let end = p.checked_add(10).filter(|&e| e <= bytes.len()); - let Some(d) = end.and_then(|e| bytes.get(p + 1..e)) else { - break; // cut short mid-descriptor: the decoder reports that - }; - let (w, h) = (u16::from_le_bytes([d[4], d[5]]) as u64, u16::from_le_bytes([d[6], d[7]]) as u64); - return check_size(Format::Gif, w, h, opts); - } - 0x21 => { - // Extension: a label byte, then sub-blocks ended by a zero length. - p = p.saturating_add(2); - loop { - let Some(&len) = bytes.get(p) else { - return Ok(()); // ran past the data: decode reports the truncation - }; - p = p.saturating_add(1); - if len == 0 { - break; - } - p = p.saturating_add(len as usize); - } - } - _ => p = p.saturating_add(1), - } - } - Ok(()) +fn decode_gif(bytes: &[u8], opts: &DecodeOptions) -> Result { + let format = Format::Gif; + let Some(info) = craft_gif::scan(bytes, 1) else { + return Err(Error::Malformed(format, "invalid GIF header".into())); + }; + let (width, height) = (u32::from(info.width), u32::from(info.height)); + check_size(format, u64::from(width), u64::from(height), opts)?; + let Some(frame) = info.frames.first() else { + return Err(Error::Malformed(format, "no readable first frame".into())); + }; + check_size(format, u64::from(frame.width), u64::from(frame.height), opts)?; + check_fillable(format, bytes, width, height)?; + let max_bytes = opts.max_pixels.saturating_mul(4); + let mut limits = craft_gif::frames::FrameLimits::default(); + limits.max_frames = 1; + limits.max_bytes = max_bytes; + limits.max_canvas_bytes = max_bytes; + limits.max_decode_bytes = Some(max_bytes); + let animation = craft_gif::frames::read_frames(bytes, &limits).map_err(|e| Error::Malformed(format, e.to_string()))?; + let Some(decoded) = animation.frames.into_iter().next() else { + return Err(Error::Malformed(format, "no decoded frame".into())); + }; + let raw = Raw { + width: animation.width as usize, + height: animation.height as usize, + model: Model::Rgb, + alpha: true, + premultiplied: false, + buf: Buf::U8(decoded.rgba), + bit_depth: 8, + }; + let icc = craft_gif::frames::icc_profile(bytes); + finish(format, raw, Meta { icc, ..Default::default() }, (animation.width, animation.height), opts) } #[cfg(test)] @@ -387,7 +275,7 @@ mod tests { b } - /// `image`'s GIF decoder allocates its frame buffer at the image descriptor's declared + /// A GIF decoder allocates its frame buffer at the image descriptor's declared /// size, which the canvas bound ([`crate::decode`]'s `max_pixels` on the logical screen) /// does not cover. A 20-byte file used to buy a 4 GB allocation before the gate. #[test] @@ -445,9 +333,41 @@ mod tests { for (name, frame) in frames { let mut gif = Vec::new(); image::codecs::gif::GifEncoder::new_with_speed(&mut gif, 30).encode_frame(image::Frame::new(frame)).unwrap(); - let first = gif_first_frame(&gif).unwrap(); - assert_eq!((first.width, first.height), (w, h), "{name}"); - assert_eq!(gif_frame_pixels(&gif, first.codes, u64::MAX), u64::from(w * h), "{name}"); + let first = craft_gif::scan(&gif, 1).unwrap().frames.remove(0); + assert_eq!((u32::from(first.width), u32::from(first.height)), (w, h), "{name}"); + assert_eq!(craft_gif::first_frame_decoded_pixels(&gif), Some(u64::from(w * h)), "{name}"); } } + + #[test] + fn gif_icc_profile_is_preserved_by_the_codec_adapter() { + let mut bytes = Vec::new(); + image::codecs::gif::GifEncoder::new_with_speed(&mut bytes, 30) + .encode_frame(image::Frame::new(image::RgbaImage::from_pixel(2, 2, image::Rgba([80, 120, 160, 255])))) + .unwrap(); + let frame = craft_gif::scan(&bytes, 1).unwrap().frames[0]; + let profile = [1, 2, 3, 4, 5]; + let mut extension = vec![0x21, 0xff, 0x0b]; + extension.extend_from_slice(b"ICCRGBG1012"); + extension.push(profile.len() as u8); + extension.extend_from_slice(&profile); + extension.push(0); + bytes.splice(frame.offset..frame.offset, extension); + + let decoded = crate::decode(&bytes, DecodeOptions::default()).unwrap(); + assert_eq!(decoded.icc.as_deref(), Some(profile.as_slice())); + } + + #[test] + fn gif_first_frame_pixels_match_the_previous_image_decoder() { + let mut bytes = Vec::new(); + let pixels = + image::RgbaImage::from_fn(16, 12, |x, y| image::Rgba([(x * 13) as u8, (y * 17) as u8, 91, if (x + y) % 3 == 0 { 127 } else { 255 }])); + image::codecs::gif::GifEncoder::new_with_speed(&mut bytes, 30).encode_frame(image::Frame::new(pixels)).unwrap(); + + let decoder = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes)).unwrap(); + let legacy = DynamicImage::from_decoder(decoder).unwrap().into_rgba8().into_raw(); + let shared = craft_gif::frames::read_frames(&bytes, &craft_gif::frames::FrameLimits::default()).unwrap(); + assert_eq!(shared.frames[0].rgba, legacy); + } } From 08aefe52d7ebd29e400e6c1cbedb8eec27999d74 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 00:14:06 +0000 Subject: [PATCH 15/23] codecs: use shared craft-jxl codec in LightCraft (craft-libs#1229) --- Cargo.lock | 12 +- Cargo.toml | 2 +- crates/codecs/Cargo.toml | 8 +- crates/codecs/README.md | 6 +- crates/codecs/src/jxl.rs | 167 +++++++--------------------- crates/codecs/src/jxl_encode.rs | 189 +++++++++----------------------- docs/parity-checklist.md | 2 +- docs/web.md | 2 +- 8 files changed, 112 insertions(+), 276 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ed7e5f1a3b..63c2b44990 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1247,6 +1247,16 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-jxl" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d61671b6ded40929dcaacaaa658512d9f7981fc4#d61671b6ded40929dcaacaaa658512d9f7981fc4" +dependencies = [ + "jixel", + "jxl-oxide", + "thiserror 2.0.21", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -3742,11 +3752,11 @@ dependencies = [ "craft-gainmap", "craft-gif", "craft-heif", + "craft-jxl", "craft-psd", "dhat", "image", "image-webp", - "jixel", "jpeg-decoder", "jpeg-encoder", "jxl-oxide", diff --git a/Cargo.toml b/Cargo.toml index 49cfa8163d..47cf53ec66 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l # Canon CRW decoder shared with the other Craft apps craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "68b8171b0d2c133d4a99ed3ae621e9ebb74a703f", features = ["frames"] } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d61671b6ded40929dcaacaaa658512d9f7981fc4", default-features = false, features = ["decode", "encode"] } # Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949) craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "68b8171b0d2c133d4a99ed3ae621e9ebb74a703f" } # craft-update: app-specific pretend versions apply to startup and manual checks. @@ -95,7 +96,6 @@ tiff = "0.11" image-webp = "0.2" moxcms = { version = "0.9", default-features = false, features = ["lut"] } jxl-oxide = { version = "0.12", default-features = false } -jixel = "=0.3.4" # BSD-3-Clause OR Apache-2.0, pure-Rust JPEG XL encoder (export; port of libjxl-tiny) zune-jpegxl = { version = "0.5", default-features = false, features = ["std"] } # MIT/Apache-2.0/Zlib lossless JXL encoder (test fixtures only) ravif = { version = "0.13", default-features = false, features = ["threading"] } # no "asm": it needs nasm (non-Rust) # HDR AVIF (PQ): ravif fixes the sRGB transfer curve, so HDR files drive its rav1e + avif-serialize directly diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 3917e31ae9..ab8b20817a 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -29,20 +29,18 @@ png = { workspace = true } tiff = { workspace = true } image-webp = { workspace = true } moxcms = { workspace = true } -jxl-oxide = { workspace = true, optional = true } +craft-jxl = { workspace = true, optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] ravif = { workspace = true, optional = true } rav1e = { workspace = true, optional = true } avif-serialize = { workspace = true, optional = true } -# spawns threads of its own (std::thread), which wasm32 has not got -jixel = { workspace = true, optional = true } [features] default = ["parallel", "jxl", "avif"] parallel = ["dep:rayon", "lightcraft-raster/parallel", "jpeg-decoder/rayon"] -## JPEG XL decode (jxl-oxide) and, on native targets, encode (jixel); both pure Rust. -jxl = ["dep:jxl-oxide", "dep:jixel"] +## JPEG XL decoding and encoding via the shared craft-jxl codec. +jxl = ["dep:craft-jxl"] # HEIC/HEIF decode via the optional craft-heif crate (heic-rs, pure Rust). Off by default so # distributors choose it at build time (HEVC patents are a distributor's call, same policy as # PhotoCraft); `cargo xtask ci` clippies and tests it (`--features heif`), releases don't ship it yet. diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 51b07eb66d..e48e57d8eb 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -52,7 +52,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d | WebP | lossy + lossless, alpha, first frame of animations | lossless only | ICCP/EXIF/XMP chunks | | GIF / BMP | yes (first GIF frame) | — | via `image` | | PSD / PSB | merged composite: 8/16/32-bit gray, RGB, CMYK, indexed, duotone (as gray); raw/RLE | — | ICC (1039), EXIF (1058), XMP (1060); ZIP-compressed composite, Lab and 1-bit unsupported | -| JPEG XL | yes (jxl-oxide, feature `jxl`, default on) | yes (jixel, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes | +| JPEG XL | yes (`craft-jxl`, feature `jxl`, default on) | yes (`craft-jxl`, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the shared decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes | | AVIF | **no** | yes (ravif/rav1e, native only, feature `avif`) | 8/10-bit sRGB, EXIF; no ICC in the muxer. HDR: `encode_avif_hdr` writes 10-bit BT.2020 PQ (SDR white at 203 cd/m², CICP `nclx` + `clli`) or HLG (`hlg_signal`, SDR white at 0.75) | | HEIC/HEIF | yes with feature `heif` (craft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported | | Gain map JPEG (HDR) | gain map found and decoded (`gainmap::read_jpeg`): ISO 21496-1 metadata, else Adobe `hdrgm` XMP | yes (`gainmap::encode_jpeg`) | CIPA DC-007 MPF index (gain map typed `0x050000`), ISO 21496-1 APP2 on both images, `hdrgm` + Container XMP for Android/Chrome, Apple `HDRGainMap`/`HDRToneMap` XMP; gain maps are never used as thumbnails | @@ -91,8 +91,8 @@ All pure Rust, verified with `cargo info` / `cargo tree`: | image-webp | MIT OR Apache-2.0 | WebP | | image (gif, bmp only) | MIT OR Apache-2.0 | GIF/BMP | | moxcms | BSD-3-Clause OR Apache-2.0 | ICC parse/write, CMS | -| jxl-oxide | MIT OR Apache-2.0 | JPEG XL decode | -| jixel | BSD-3-Clause OR Apache-2.0 | JPEG XL encode (native only) | +| craft-jxl | MIT OR Apache-2.0 | JPEG XL decode/encode (shared craft-libs) | +| jxl-oxide | MIT OR Apache-2.0 | JPEG XL test oracle only | | ravif (+ rav1e, avif-serialize) | BSD-3-Clause / BSD-2-Clause | AVIF encode (native only; heavy to compile) | Deliberately **not** used: anything AGPL from imazen (heic, zenjpeg, jxl-encoder, rav1d-safe), diff --git a/crates/codecs/src/jxl.rs b/crates/codecs/src/jxl.rs index adf59c0aa4..c68ad39284 100644 --- a/crates/codecs/src/jxl.rs +++ b/crates/codecs/src/jxl.rs @@ -1,138 +1,55 @@ -//! JPEG XL decode via `jxl-oxide` (pure Rust). Enum-encoded images are rendered straight into linear -//! Rec.2020; ICC-tagged ones are rendered in their own space and interpreted with our ICC path. -//! XYB (lossy) images are rendered to linear sRGB primaries and converted to Rec.2020 here: -//! jxl-oxide 0.12 desaturates colours outside sRGB when it renders XYB to wider primaries. -//! jxl-oxide applies the codestream orientation itself, so `orientation` is reported as 1. +//! JPEG XL adapter to the shared `craft-jxl` codec. -use crate::convert::{Buf, Meta, Model, Raw, check_size, finish}; +use crate::convert::{Buf, Meta, Model, Raw, finish}; use crate::space::{NamedSpace, SourceSpace, SpaceOrigin, Trc}; use crate::{DecodeOptions, Decoded, Error, Format, Result}; -use jxl_oxide::color::{ColourSpace, EnumColourEncoding, Primaries, RenderingIntent, TransferFunction, WhitePoint}; -use jxl_oxide::{AllocTracker, AuxBoxData, InitializeResult, JxlImage}; const F: Format = Format::Jxl; -fn err(e: impl std::fmt::Display) -> Error { - Error::Malformed(F, e.to_string()) -} - -/// Tracked allocation budget per allowed pixel for frames, extra channels and modular trees. -/// This bounds allocations covered by `AllocTracker`, not every allocation made by the decoder (#1517). -const TRACKED_BYTES_PER_PIXEL: u64 = 4 * 4 * 8; - -/// The allocation budget never drops below this, so small images keep the decoder's fixed -/// overhead (group buffers, entropy tables) whatever `max_pixels` is. -const MIN_TRACKED_BYTES: u64 = 64 << 20; - -/// Bytes handed to the decoder at a time (the size `JxlImageBuilder::read` reads in). -const INPUT_CHUNK: usize = 4096; - -/// Initializes from bounded input, checks dimensions before rendering, then loads remaining frames -/// within a tracked allocation budget. -fn open(bytes: &[u8], opts: &DecodeOptions) -> Result { - let budget = opts.max_pixels.saturating_mul(TRACKED_BYTES_PER_PIXEL).max(MIN_TRACKED_BYTES); - let tracker = AllocTracker::with_limit(usize::try_from(budget).unwrap_or(usize::MAX)); - let mut uninit = JxlImage::builder().alloc_tracker(tracker).build_uninit(); - // Initialization can load already-buffered frame data, so small feeds limit work before - // dimension checking. - let mut rest = bytes; - let mut window = INPUT_CHUNK; - let mut img = loop { - let consumed = uninit.feed_bytes(rest.get(..window).unwrap_or(rest)).map_err(err)?; - rest = rest.get(consumed..).unwrap_or_default(); - match uninit.try_init().map_err(err)? { - InitializeResult::Initialized(img) => break img, - InitializeResult::NeedMoreData(more) => uninit = more, - } - if consumed == 0 { - // the parser wants more than the window holds at once - if window >= rest.len() { - return Err(err("truncated JPEG XL header")); - } - window = window.saturating_mul(2); - } - }; - check_size(F, img.width() as u64, img.height() as u64, opts)?; - // Match `JxlImageBuilder::read`: bounded feeds until the final frame, not merely the first - // keyframe. `feed_bytes` copies codestream data into an untracked Vec, including any tail - // after the last frame; feeding the remaining file at once bypasses the allocation budget. - while !img.is_loading_done() && !rest.is_empty() { - let consumed = img.feed_bytes(rest.get(..INPUT_CHUNK).unwrap_or(rest)).map_err(err)?; - if consumed == 0 { - break; - } - rest = rest.get(consumed..).unwrap_or_default(); - } - img.finalize().map_err(err)?; - Ok(img) -} - pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { - let mut img = open(bytes, opts)?; - let (w, h) = (img.width(), img.height()); - let header = img.image_header(); - let bits = header.metadata.bit_depth.bits_per_sample() as u8; - let float = matches!(header.metadata.bit_depth, jxl_oxide::image::BitDepth::FloatSample { .. }); - let gray = header.metadata.grayscale(); - let icc = img.original_icc().map(|v| v.to_vec()); - let mut meta = Meta { orientation: Some(1), ..Default::default() }; - // linear sRGB primaries, unclamped, then our own matrix to Rec.2020 (see the module docs) - let via_srgb = icc.is_none() && !gray && header.metadata.xyb_encoded; - if icc.is_none() { - img.request_color_encoding(EnumColourEncoding { - colour_space: if gray { ColourSpace::Grey } else { ColourSpace::Rgb }, - white_point: WhitePoint::D65, - primaries: if via_srgb { Primaries::Srgb } else { Primaries::Bt2100 }, - tf: TransferFunction::Linear, - rendering_intent: RenderingIntent::Relative, - }); - let mut s = SourceSpace::named(NamedSpace::Rec2020, SpaceOrigin::Container); - s.trc = Some([Trc::Linear, Trc::Linear, Trc::Linear]); - meta.already_linear = Some(s); + let limits = craft_jxl::DecodeLimits { max_pixels: opts.max_pixels, ..Default::default() }; + let decoded = craft_jxl::decode_with_color(bytes, limits, craft_jxl::OutputColor::LinearRec2020).map_err(|e| match e { + craft_jxl::Error::PixelLimitExceeded { width, height, .. } => Error::TooLarge(u64::from(width), u64::from(height)), + craft_jxl::Error::Malformed(message) | craft_jxl::Error::LimitExceeded(message) | craft_jxl::Error::InvalidImage(message) => { + Error::Malformed(F, message) + } + craft_jxl::Error::Unsupported(message) | craft_jxl::Error::Encode(message) => Error::Malformed(F, message), + })?; + + let gray = matches!(decoded.layout, craft_jxl::Layout::Gray | craft_jxl::Layout::GrayAlpha); + let alpha = decoded.layout.has_alpha(); + let pixels_linear_rec2020 = decoded.pixels_linear_rec2020; + let rendered_icc = if !pixels_linear_rec2020 && decoded.metadata.icc.is_none() && !decoded.rendered_icc.is_empty() { + Some(decoded.rendered_icc.clone()) } else { - meta.icc = icc; - } - if let Ok(AuxBoxData::Data(ex)) = img.aux_boxes().first_exif() { - meta.exif = Some(ex.payload().to_vec()); - } - if let AuxBoxData::Data(x) = img.aux_boxes().first_xml() { - meta.xmp = Some(String::from_utf8_lossy(x).trim_end_matches('\0').to_string()); - } - let render = img.render_frame(0).map_err(err)?; - let fb = render.image_all_channels(); - let (fw, fh, ch) = (fb.width(), fb.height(), fb.channels()); - let n_color = if gray { 1 } else { 3 }; - let has_alpha = img.pixel_format().has_alpha(); - if ch < n_color { - return Err(err("too few channels")); - } - let keep = n_color + has_alpha as usize; - let src = fb.buf(); - let mut v = Vec::with_capacity(fw * fh * keep); - let to_2020 = lightcraft_color::SRGB.to_space(&lightcraft_color::REC2020).to_f32(); - for px in src.chunks_exact(ch) { - let start = v.len(); - v.extend_from_slice(&px[..keep.min(ch)]); - if keep > ch { - v.push(1.0); - } - if via_srgb && let Some(rgb) = v.get_mut(start..start + 3) { - let [r, g, b] = [rgb[0], rgb[1], rgb[2]]; - for (o, m) in rgb.iter_mut().zip(&to_2020) { - *o = m[0] * r + m[1] * g + m[2] * b; - } - } + None + }; + let mut meta = Meta { + orientation: Some(1), + icc: decoded.metadata.icc.or(rendered_icc), + exif: decoded.metadata.exif, + xmp: decoded.metadata.xmp.map(|packet| String::from_utf8_lossy(&packet).trim_end_matches('\0').to_owned()), + ..Default::default() + }; + if pixels_linear_rec2020 { + let mut space = SourceSpace::named(NamedSpace::Rec2020, SpaceOrigin::Container); + space.trc = Some([Trc::Linear, Trc::Linear, Trc::Linear]); + meta.already_linear = Some(space); + } else if meta.icc.is_none() { + return Err(Error::Malformed(F, "shared decoder did not report the rendered JPEG XL color profile".into())); } let raw = Raw { - width: fw, - height: fh, + width: decoded.width as usize, + height: decoded.height as usize, model: if gray { Model::Gray } else { Model::Rgb }, - alpha: has_alpha, - premultiplied: false, - buf: Buf::F32(v), - bit_depth: bits, + alpha, + premultiplied: decoded.pixels_premultiplied, + buf: Buf::F32(decoded.pixels), + bit_depth: decoded.bit_depth, }; - let mut d = finish(F, raw, meta, (w, h), opts)?; - d.float = float; - Ok(d) + let (source_width, source_height) = + if (5..=8).contains(&decoded.source_orientation) { (decoded.height, decoded.width) } else { (decoded.width, decoded.height) }; + let mut result = finish(F, raw, meta, (source_width, source_height), opts)?; + result.float = decoded.float_samples; + Ok(result) } diff --git a/crates/codecs/src/jxl_encode.rs b/crates/codecs/src/jxl_encode.rs index e76c5b144f..e4dd0264df 100644 --- a/crates/codecs/src/jxl_encode.rs +++ b/crates/codecs/src/jxl_encode.rs @@ -1,21 +1,16 @@ -//! JPEG XL encode via `jixel` (pure Rust, BSD-3-Clause OR Apache-2.0; native targets with the `jxl` -//! feature: it spawns threads of its own). Lossy files are VarDCT in XYB, tagged with an enum colour -//! encoding the decoder renders back to; lossless files are Modular and keep their samples as they -//! are, tagged with the ICC profile when one is given. EXIF and XMP go in `Exif` / `xml ` boxes. +//! JPEG XL encoder adapter to the shared `craft-jxl` codec. -use crate::encode::{EncodeImage, EncodeMeta, HDR_REFERENCE_WHITE_NITS, Samples, pq_encode}; +use crate::encode::{EncodeImage, EncodeMeta, Samples}; use crate::{Error, Result}; use serde::{Deserialize, Serialize}; -/// Encoder effort: time spent searching for a smaller file at the same quality. jixel's slowest -/// search (about 20 % smaller again, five times slower) is not offered: its files are valid, but -/// jxl-oxide, our decoder, renders blocks of them wrongly, so LightCraft could not read back its own -/// exports. +/// Encoder effort exposed by LightCraft's export settings. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum JxlEffort { - /// Plain 8×8 transforms only: quickest, largest (about a third larger than `Normal`). + /// Quick search, producing larger files. Fast, + /// Balanced search. #[default] Normal, } @@ -30,32 +25,31 @@ impl JxlEffort { } } -/// The colour encoding a JPEG XL file declares. Integer samples are display-encoded with its curve. +/// The color encoding declared by the JPEG XL file. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum JxlColour { #[default] Srgb, - /// P3 primaries, D65, sRGB curve. + /// P3 primaries, D65, and the sRGB curve. DisplayP3, - /// Rec. 2020 primaries with the BT.709 curve. + /// Rec. 2020 primaries and the BT.709 curve. Rec2020, - /// HDR: Rec. 2020 primaries with the PQ curve (SMPTE ST 2084). Float samples are linear light - /// with SDR white at 1.0 (written with SDR white at [`HDR_REFERENCE_WHITE_NITS`]); 16-bit - /// samples are already PQ-encoded. + /// HDR Rec. 2020 using the PQ curve. Rec2020Pq, } -/// JPEG XL encoder settings. +/// JPEG XL export settings. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct JxlOptions { - /// 1..=100 on a libjpeg-like scale (90 ≈ visually lossless). Ignored when `lossless`. + /// Lossy quality on a 1..=100 scale; ignored when lossless. pub quality: u8, - /// Mathematically lossless (Modular) instead of lossy (VarDCT). + /// Use mathematically lossless coding. pub lossless: bool, + /// Encoder search effort. pub effort: JxlEffort, - /// Lossy: two passes, a coarse image first; lossless: the Squeeze transform (a low-resolution - /// preview that refines to the exact image). + /// Write a progressive image. pub progressive: bool, + /// Color encoding to declare. pub colour: JxlColour, } @@ -65,124 +59,41 @@ impl Default for JxlOptions { } } -/// Encode JPEG XL from 8- or 16-bit samples (float samples only with [`JxlColour::Rec2020Pq`]). -/// Gray is widened to RGB; alpha is kept only when some pixel is not opaque. The ICC profile in -/// `meta` is embedded in lossless files (lossy ones carry the enum encoding of `o.colour`); `ppi` -/// has no place in the format. Returns [`Error::Encode`] on wasm32 or without the `jxl` feature. -pub fn encode_jxl(img: &EncodeImage, o: &JxlOptions, meta: &EncodeMeta) -> Result> { - img.validate()?; - #[cfg(all(feature = "jxl", not(target_arch = "wasm32")))] - { - let pixels = Pixels::from(img, o.colour)?; - // jixel asserts internally; a panic there is an export error, not a crash - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&pixels, img.width as usize, img.height as usize, o, meta))) - .unwrap_or_else(|_| Err(Error::Encode("JPEG XL encoder panicked".into()))) - } - #[cfg(not(all(feature = "jxl", not(target_arch = "wasm32"))))] - { - let _ = (o, meta); - Err(Error::Encode("JPEG XL encoding is not available in this build".into())) - } -} - -/// Interleaved RGB or RGBA samples for jixel. -#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))] -enum Pixels { - U8 { data: Vec, alpha: bool }, - U16 { data: Vec, alpha: bool }, -} - -#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))] -impl Pixels { - fn from(img: &EncodeImage, colour: JxlColour) -> Result { - let n = (img.width as usize).checked_mul(img.height as usize).ok_or_else(|| Error::Encode("image too large".into()))?; - let ch = img.channels as usize; - // keep alpha only when it says something - fn rgba(s: &[T], ch: usize, n: usize, opaque: impl Fn(T) -> bool) -> (Vec, bool) { - let px = s.chunks_exact(ch).take(n); - let alpha = (ch == 2 || ch == 4) && s.chunks_exact(ch).take(n).any(|c| c.last().is_some_and(|a| !opaque(*a))); - let out_ch = if alpha { 4 } else { 3 }; - let mut v = Vec::with_capacity(n * out_ch); - for c in px { - match c { - [g] => v.extend_from_slice(&[*g, *g, *g]), - [g, a] => v.extend_from_slice(&[*g, *g, *g, *a][..out_ch]), - [r, g, b] => v.extend_from_slice(&[*r, *g, *b]), - [r, g, b, a, ..] => v.extend_from_slice(&[*r, *g, *b, *a][..out_ch]), - [] => {} - } - } - (v, alpha) - } - Ok(match img.samples { - Samples::U8(s) => { - let (data, alpha) = rgba(s, ch, n, |a| a == u8::MAX); - Pixels::U8 { data, alpha } - } - Samples::U16(s) => { - let (data, alpha) = rgba(s, ch, n, |a| a == u16::MAX); - Pixels::U16 { data, alpha } - } - Samples::F32(s) if colour == JxlColour::Rec2020Pq => { - let pq = |v: f32| (pq_encode(if v.is_finite() { v.max(0.0) } else { 0.0 } * HDR_REFERENCE_WHITE_NITS) * 65535.0).round() as u16; - let alpha = |a: f32| (if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 } * 65535.0).round() as u16; - let s: Vec = s - .chunks_exact(ch) - .take(n) - .flat_map(|c| match c { - [g] => [pq(*g), pq(*g), pq(*g), u16::MAX], - [g, a] => [pq(*g), pq(*g), pq(*g), alpha(*a)], - [r, g, b] => [pq(*r), pq(*g), pq(*b), u16::MAX], - [r, g, b, a, ..] => [pq(*r), pq(*g), pq(*b), alpha(*a)], - [] => [0; 4], - }) - .collect(); - let (data, alpha) = rgba(&s, 4, n, |a| a == u16::MAX); - Pixels::U16 { data, alpha } - } - Samples::F32(_) => return Err(Error::Encode("JPEG XL float samples are written as HDR (Rec. 2020 PQ) only".into())), - }) - } -} - -#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))] -fn run(px: &Pixels, w: usize, h: usize, o: &JxlOptions, meta: &EncodeMeta) -> Result> { - use jixel::{ColorEncoding, EncodeConfig, Primaries, Speed, TransferFunction}; - let colour = match o.colour { - JxlColour::Srgb => ColorEncoding::srgb(), - JxlColour::DisplayP3 => ColorEncoding::display_p3(), - JxlColour::Rec2020 => ColorEncoding { primaries: Primaries::Bt2020, transfer: TransferFunction::Bt709, ..ColorEncoding::srgb() }, - JxlColour::Rec2020Pq => ColorEncoding::bt2020_pq(), +/// Encode JPEG XL while preserving LightCraft's public option and metadata types. +pub fn encode_jxl(image: &EncodeImage, options: &JxlOptions, metadata: &EncodeMeta) -> Result> { + image.validate()?; + let layout = match image.channels { + 1 => craft_jxl::Layout::Gray, + 2 => craft_jxl::Layout::GrayAlpha, + 3 => craft_jxl::Layout::Rgb, + 4 => craft_jxl::Layout::Rgba, + _ => return Err(Error::Encode(format!("unsupported channel count {}", image.channels))), }; - let mut c = EncodeConfig::default() - .with_quality(f32::from(o.quality.clamp(1, 100))) - .with_color_encoding(colour) - .with_lossless(o.lossless) - .with_progressive(o.progressive) - .with_speed(match o.effort { - JxlEffort::Fast => Speed::Fastest, - JxlEffort::Normal => Speed::Fast, - }); - if o.colour == JxlColour::Rec2020Pq { - // PQ code values are absolute: 1.0 = 10 000 cd/m² - c = c.with_intensity_target(10_000.0); - } - if o.lossless - && let Some(icc) = meta.icc - { - c = c.with_icc_profile(icc.to_vec()); - } - if let Some(exif) = meta.exif { - c = c.with_exif(exif.to_vec()); - } - if let Some(xmp) = meta.xmp { - c = c.with_xmp(xmp.as_bytes().to_vec()); - } - let r = match px { - Pixels::U8 { data, alpha: false } => jixel::encode_image(data, w, h, &c), - Pixels::U8 { data, alpha: true } => jixel::encode_image_with_alpha(data, w, h, &c), - Pixels::U16 { data, alpha: false } => jixel::encode_image_16bit(data, w, h, &c), - Pixels::U16 { data, alpha: true } => jixel::encode_image_with_alpha_16bit(data, w, h, &c), + let samples = match image.samples { + Samples::U8(samples) => craft_jxl::Samples::U8(samples), + Samples::U16(samples) => craft_jxl::Samples::U16(samples), + Samples::F32(samples) => craft_jxl::Samples::F32(samples), }; - r.map_err(|e| Error::Encode(format!("JPEG XL: {e}"))) + let image = craft_jxl::ImageRef { width: image.width, height: image.height, layout, samples }; + let options = craft_jxl::EncodeOptions { + quality: options.quality, + lossless: options.lossless, + effort: match options.effort { + JxlEffort::Fast => craft_jxl::Effort::Fast, + JxlEffort::Normal => craft_jxl::Effort::Normal, + }, + progressive: options.progressive, + colour: match options.colour { + JxlColour::Srgb => craft_jxl::JxlColour::Srgb, + JxlColour::DisplayP3 => craft_jxl::JxlColour::DisplayP3, + JxlColour::Rec2020 => craft_jxl::JxlColour::Rec2020, + JxlColour::Rec2020Pq => craft_jxl::JxlColour::Rec2020Pq, + }, + }; + let metadata = craft_jxl::Metadata { + icc: metadata.icc.map(<[u8]>::to_vec), + exif: metadata.exif.map(<[u8]>::to_vec), + xmp: metadata.xmp.map(|packet| packet.as_bytes().to_vec()), + }; + craft_jxl::encode(&image, options, &metadata).map_err(|error| Error::Encode(error.to_string())) } diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 4b1f45ca05..e8dfe5525a 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -392,7 +392,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | Id | Feature | Tier | Status | Evidence | Missing / notes | |---|---|---|---|---|---| | LR-EXP-DIALOG | Export dialog | P0 | ✅ | `cmd:dialog.export`, `cmd:app.export` (`preset`), `cmd:export.presets`, `cmd:export.savePreset`, `cmd:export.deletePreset`, `crates/ui-egui/src/dialogs.rs`, `crates/engine/src/export.rs` | batch export; built-in presets (JPEG Small 2048 px / Large full size, Original + Settings, DNG, Instagram Feed 1080 px, Instagram Story / Reel 1920 px long edge with no crop to 9:16, Web / Portfolio 2048 px copyright and creator metadata, Full Resolution Master full size P3) and saved user presets (library prefs) load into the dialog; deleting a user preset is command-only; on a short window the options scroll and Cancel / Export stay visible (LR-BEHAV-DIALOGS, issue #781) | -| LR-EXP-TYPE | File types | P0 | ✅ | `cmd:app.export` (`format`), `crates/engine/src/export.rs` (`ExportFormat`), `crates/engine/src/tests/export.rs` | JPEG, PNG, TIFF, PSD (flat, 8/16-bit, no layers: `crates/codecs/src/psd.rs`), WebP, AVIF, JPEG XL (issue #247: `jixel`, native only; lossy with quality or lossless, 8/16-bit, effort fast/normal (jixel's slowest search left out: jxl-oxide misdecodes its files), progressive, EXIF/XMP boxes; lossy files in Adobe RGB / ProPhoto are written as Rec. 2020, lossless keep any space via ICC; `crates/codecs/src/jxl_encode.rs`), DNG (raw photos: lossless re-encode with the edits in the embedded XMP; a raw without colour matrices of its own, as a NEF, gets the colour it opens with as `ColorMatrix1` / `ForwardMatrix1` / `AsShotNeutral`, also in Convert / Copy as DNG, so other raw converters open it, issue #1745), Original (+ XMP sidecar). Non-raw → DNG not supported; no JPEG XL export in the web build. Opaque 8-bit PNG/TIFF/WebP exports omit the redundant alpha channel; real transparency is retained (#1670). | +| LR-EXP-TYPE | File types | P0 | ✅ | `cmd:app.export` (`format`), `crates/engine/src/export.rs` (`ExportFormat`), `crates/engine/src/tests/export.rs` | JPEG, PNG, TIFF, PSD (flat, 8/16-bit, no layers: `crates/codecs/src/psd.rs`), WebP, AVIF, JPEG XL (shared `craft-jxl`, native-only encoder; lossy with quality or lossless, 8/16-bit, effort fast/normal, progressive, EXIF/XMP boxes; lossy files in Adobe RGB / ProPhoto are written as Rec. 2020, lossless keep any space via ICC; app adapter is `crates/codecs/src/jxl_encode.rs`), DNG (raw photos: lossless re-encode with the edits in the embedded XMP; a raw without colour matrices of its own, as a NEF, gets the colour it opens with as `ColorMatrix1` / `ForwardMatrix1` / `AsShotNeutral`, also in Convert / Copy as DNG, so other raw converters open it, issue #1745), Original (+ XMP sidecar). Non-raw → DNG not supported; no JPEG XL export in the web build. Opaque 8-bit PNG/TIFF/WebP exports omit the redundant alpha channel; real transparency is retained (#1670). | | LR-EXP-DIM | Output size | P0 | ✅ | `cmd:app.export` (`longEdge`, `shortEdge`, `width`, `height`, `fit`, `megapixels`, `percent`, `dontEnlarge`, `ppi`), `crates/engine/src/export.rs` (`Resize`), `crates/ui-egui/src/dialogs.rs` | full size = the cropped native size (no longer upscaled); both of Lightroom's boxes: Dimensions (W × H fits either orientation) and Width & Height (`fit: widthHeight`, each edge bound to its own number, #1620); ppi written to JFIF / pHYs / TIFF tags; at most 65,535 px an edge, and an export enlarged past the photo's size stops at 512 megapixels (Lightroom's ceiling too) and is refused, with the size it would need, when it needs more memory than the computer has (it aborted the process before) | | LR-EXP-QUALITY | JPEG quality | P0 | ✅ | `cmd:app.export` (`quality`, `limitKb`), `crates/codecs/src/jpeg_par.rs` | 4:4:4 chroma (4:2:0 when a file-size limit is set); Huffman tables made for each image from its own symbol counts (T.81 Annex K.2) instead of the example tables: the same pixels, 12–14 % smaller files at quality 80–100 on a 24 MP photo-like image, still interleaved baseline (issue #1373); ordinary and HDR gain map JPEGs search quality up to the requested maximum to fit `limitKb`, including gain map and metadata, or return an error. Tested by `size_limit_respected` and `hdr_jpeg_size_limit_respected`. | | LR-EXP-BITDEPTH | Bit depth | P1 | ✅ | `cmd:app.export` (`bitDepth`), `crates/pipeline/src/output.rs` (`OutputDepth`), `crates/engine/src/export.rs` | 16-bit PNG/TIFF/JPEG XL rendered at 16 bits (TIFF defaults to 16), 32-bit float linear TIFF with a linear profile, 10-bit AVIF; high-bit-depth renders run on the CPU | diff --git a/docs/web.md b/docs/web.md index d5ab1c04e7..1860a5a151 100644 --- a/docs/web.md +++ b/docs/web.md @@ -209,7 +209,7 @@ are the same in every version, so serve them with `Cache-Control: no-cache` (not - **Preset files** (import/export `.json`) aren't wired to browser pickers yet. - **Control channel / MCP.** These are desktop-only, because they need a TCP socket. - **AVIF export** is untested in the browser; it's the one encoder that may not be wasm-safe. -- **JPEG XL export** is native only: the encoder (`jixel`) starts threads of its own, which wasm32 has not got; the +- **JPEG XL export** is native only: the shared `craft-jxl` encoder is not available on wasm32; the web build reports "not available in this build". JPEG XL import works. ## Measuring From be2cb6e72718da9a62acb0687643c7c8592bcf49 Mon Sep 17 00:00:00 2001 From: Bruno-Alumn <171815746+Bruno-Alumn@users.noreply.github.com> Date: Sat, 14 Nov 2026 04:34:50 +0100 Subject: [PATCH 16/23] meta: cargo fmt the MergeRules call so CI's fmt step passes --- crates/meta/src/lib.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/meta/src/lib.rs b/crates/meta/src/lib.rs index 4bc0bb2660..944b16b342 100644 --- a/crates/meta/src/lib.rs +++ b/crates/meta/src/lib.rs @@ -51,11 +51,7 @@ pub fn merge_xmp(existing: &str, fresh: &str, rules: MergeRules) -> Result Date: Sat, 14 Nov 2026 05:15:48 +0000 Subject: [PATCH 17/23] codecs: use DeflateLevel::Balanced for TIFF ZIP compression --- crates/codecs/src/encode.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/codecs/src/encode.rs b/crates/codecs/src/encode.rs index 18e8be64aa..bdbe4e5362 100644 --- a/crates/codecs/src/encode.rs +++ b/crates/codecs/src/encode.rs @@ -239,7 +239,7 @@ pub fn encode_tiff(img: &EncodeImage, compression: TiffCompression, meta: &Encod let comp = match compression { TiffCompression::None => Compression::Uncompressed, TiffCompression::Lzw => Compression::Lzw, - TiffCompression::Deflate => Compression::Deflate(DeflateLevel::Fast), + TiffCompression::Deflate => Compression::Deflate(DeflateLevel::Balanced), TiffCompression::PackBits => Compression::Packbits, }; let float = matches!(img.samples, Samples::F32(_)); From 6f012c10b7b1732d476531a7dd61f1aa1c6da7bc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 05:38:31 +0000 Subject: [PATCH 18/23] chore: finish craft-raw/craft-libs cutover after merge with main --- Cargo.lock | 144 ++++++++++++----- crates/engine/src/camera_preview/colour.rs | 1 + crates/engine/src/camera_preview/hue_sat.rs | 1 + crates/engine/src/camera_preview/tests.rs | 1 + crates/engine/src/files/load.rs | 2 + crates/pipeline/src/local_tone.rs | 2 +- crates/raw/src/convert.rs | 1 + crates/raw/src/gaintable.rs | 169 +------------------- crates/raw/src/hotpixel.rs | 2 +- crates/raw/src/lib.rs | 9 +- crates/raw/src/opcodes/tests.rs | 16 +- crates/raw/src/profile.rs | 9 -- crates/raw/src/semantic.rs | 37 +++++ crates/raw/src/tests.rs | 15 +- crates/raw/src/vendor/arw.rs | 4 +- crates/raw/src/vendor/huffman.rs | 5 - crates/raw/src/vendor/raf.rs | 4 +- crates/raw/tests/it/dng.rs | 3 +- 18 files changed, 163 insertions(+), 262 deletions(-) create mode 100644 crates/raw/src/semantic.rs diff --git a/Cargo.lock b/Cargo.lock index 47a44f1def..3b072f3408 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1184,7 +1184,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f3b62ec61f45534392376492fc5ad33047375205#f3b62ec61f45534392376492fc5ad33047375205" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" dependencies = [ "thiserror 2.0.21", ] @@ -1202,15 +1202,24 @@ source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955 [[package]] name = "craft-gainmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=119415f46f601e20b9bc6b1b4d6979ceda86d88e#119415f46f601e20b9bc6b1b4d6979ceda86d88e" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-gif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" +dependencies = [ + "gif", + "image", +] + [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e21c5b0b1358f7d5505e7ea395948fe21f4d872#6e21c5b0b1358f7d5505e7ea395948fe21f4d872" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" dependencies = [ "heic-rs", "rayon", @@ -1239,20 +1248,61 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-jxl" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" +dependencies = [ + "jixel", + "jxl-oxide", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" +dependencies = [ + "brotli-decompressor 6.0.1", + "chrono", + "craft-tiff", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=119415f46f601e20b9bc6b1b4d6979ceda86d88e#119415f46f601e20b9bc6b1b4d6979ceda86d88e" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" dependencies = [ "encoding_rs", "flate2", + "rayon", "thiserror 2.0.21", ] +[[package]] +name = "craft-raw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" +dependencies = [ + "chrono", + "craft-crw", + "craft-metadata", + "craft-tiff", + "jxl-oxide", + "miniz_oxide 0.9.1", + "rayon", + "serde", + "thiserror 2.0.21", + "zune-core", + "zune-jpeg", +] + [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3b3104981bb3093904a12e44d6a3b41c6c4c39c8#3b3104981bb3093904a12e44d6a3b41c6c4c39c8" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" dependencies = [ "serde", "thiserror 2.0.21", @@ -1317,6 +1367,15 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -3638,7 +3697,7 @@ dependencies = [ [[package]] name = "lightcraft" -version = "0.21.0" +version = "0.21.1" dependencies = [ "chrono", "craft-update", @@ -3667,7 +3726,7 @@ dependencies = [ [[package]] name = "lightcraft-catalog" -version = "0.21.0" +version = "0.21.1" dependencies = [ "chrono", "crc32fast", @@ -3688,7 +3747,7 @@ dependencies = [ [[package]] name = "lightcraft-cli" -version = "0.21.0" +version = "0.21.1" dependencies = [ "dhat", "lightcraft-codecs", @@ -3705,17 +3764,18 @@ dependencies = [ [[package]] name = "lightcraft-codecs" -version = "0.21.0" +version = "0.21.1" dependencies = [ "avif-serialize", "bytemuck", "craft-gainmap", + "craft-gif", "craft-heif", + "craft-jxl", "craft-psd", "dhat", "image", "image-webp", - "jixel", "jpeg-decoder", "jpeg-encoder", "jxl-oxide", @@ -3738,7 +3798,7 @@ dependencies = [ [[package]] name = "lightcraft-color" -version = "0.21.0" +version = "0.21.1" dependencies = [ "lightcraft-geom", "proptest", @@ -3747,7 +3807,7 @@ dependencies = [ [[package]] name = "lightcraft-denoise" -version = "0.21.0" +version = "0.21.1" dependencies = [ "faer-core", "lightcraft-denoise-core", @@ -3764,7 +3824,7 @@ dependencies = [ [[package]] name = "lightcraft-denoise-core" -version = "0.21.0" +version = "0.21.1" dependencies = [ "dhat", "lightcraft-raster", @@ -3780,7 +3840,7 @@ dependencies = [ [[package]] name = "lightcraft-develop" -version = "0.21.0" +version = "0.21.1" dependencies = [ "lightcraft-color", "lightcraft-geom", @@ -3792,7 +3852,7 @@ dependencies = [ [[package]] name = "lightcraft-engine" -version = "0.21.0" +version = "0.21.1" dependencies = [ "ab_glyph", "chrono", @@ -3839,7 +3899,7 @@ dependencies = [ [[package]] name = "lightcraft-faces" -version = "0.21.0" +version = "0.21.1" dependencies = [ "lightcraft-testkit", "matrixmultiply", @@ -3854,7 +3914,7 @@ dependencies = [ [[package]] name = "lightcraft-fetch" -version = "0.21.0" +version = "0.21.1" dependencies = [ "log", "rustls", @@ -3865,14 +3925,14 @@ dependencies = [ [[package]] name = "lightcraft-film" -version = "0.21.0" +version = "0.21.1" dependencies = [ "libm", ] [[package]] name = "lightcraft-geocode" -version = "0.21.0" +version = "0.21.1" dependencies = [ "miniz_oxide 0.9.1", "serde", @@ -3880,7 +3940,7 @@ dependencies = [ [[package]] name = "lightcraft-geom" -version = "0.21.0" +version = "0.21.1" dependencies = [ "proptest", "serde", @@ -3888,7 +3948,7 @@ dependencies = [ [[package]] name = "lightcraft-gpu" -version = "0.21.0" +version = "0.21.1" dependencies = [ "bytemuck", "lightcraft-color", @@ -3908,23 +3968,23 @@ dependencies = [ [[package]] name = "lightcraft-inpaint" -version = "0.21.0" +version = "0.21.1" dependencies = [ "rayon", ] [[package]] name = "lightcraft-lensdb" -version = "0.21.0" +version = "0.21.1" dependencies = [ + "craft-xml", "lightcraft-develop", "lightcraft-geom", - "quick-xml 0.41.0", ] [[package]] name = "lightcraft-mcp" -version = "0.21.0" +version = "0.21.1" dependencies = [ "lightcraft-codecs", "lightcraft-engine", @@ -3935,7 +3995,7 @@ dependencies = [ [[package]] name = "lightcraft-merge" -version = "0.21.0" +version = "0.21.1" dependencies = [ "lightcraft-codecs", "lightcraft-color", @@ -3951,10 +4011,11 @@ dependencies = [ [[package]] name = "lightcraft-meta" -version = "0.21.0" +version = "0.21.1" dependencies = [ "chrono", "craft-heif", + "craft-metadata", "craft-psd", "craft-tiff", "lightcraft-geom", @@ -3966,7 +4027,7 @@ dependencies = [ [[package]] name = "lightcraft-pipeline" -version = "0.21.0" +version = "0.21.1" dependencies = [ "dhat", "image", @@ -3985,7 +4046,7 @@ dependencies = [ [[package]] name = "lightcraft-preview" -version = "0.21.0" +version = "0.21.1" dependencies = [ "jpeg-encoder", "lightcraft-raster", @@ -3997,7 +4058,7 @@ dependencies = [ [[package]] name = "lightcraft-raster" -version = "0.21.0" +version = "0.21.1" dependencies = [ "libc", "lightcraft-color", @@ -4009,14 +4070,13 @@ dependencies = [ [[package]] name = "lightcraft-raw" -version = "0.21.0" +version = "0.21.1" dependencies = [ "chrono", - "craft-crw", + "craft-raw", "craft-tiff", "dhat", "jpeg-encoder", - "jxl-oxide", "lightcraft-color", "lightcraft-geom", "lightcraft-meta", @@ -4035,7 +4095,7 @@ dependencies = [ [[package]] name = "lightcraft-scenes" -version = "0.21.0" +version = "0.21.1" dependencies = [ "image", "lightcraft-color", @@ -4046,7 +4106,7 @@ dependencies = [ [[package]] name = "lightcraft-segment" -version = "0.21.0" +version = "0.21.1" dependencies = [ "candle-core", "candle-nn", @@ -4060,7 +4120,7 @@ dependencies = [ [[package]] name = "lightcraft-slideshow" -version = "0.21.0" +version = "0.21.1" dependencies = [ "lightcraft-raster", "serde", @@ -4069,15 +4129,15 @@ dependencies = [ [[package]] name = "lightcraft-sysmem" -version = "0.21.0" +version = "0.21.1" [[package]] name = "lightcraft-testkit" -version = "0.21.0" +version = "0.21.1" [[package]] name = "lightcraft-ui-egui" -version = "0.21.0" +version = "0.21.1" dependencies = [ "craft-ui", "craft-update", @@ -4110,7 +4170,7 @@ dependencies = [ [[package]] name = "lightcraft-web" -version = "0.21.0" +version = "0.21.1" dependencies = [ "crc32fast", "eframe", @@ -4133,7 +4193,7 @@ dependencies = [ [[package]] name = "lightcraft-wincolor" -version = "0.21.0" +version = "0.21.1" dependencies = [ "lightcraft-testkit", "windows-sys 0.61.2", @@ -7958,7 +8018,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.21.0" +version = "0.21.1" dependencies = [ "brotli", "flate2", diff --git a/crates/engine/src/camera_preview/colour.rs b/crates/engine/src/camera_preview/colour.rs index 742b37c48b..6ac9346301 100644 --- a/crates/engine/src/camera_preview/colour.rs +++ b/crates/engine/src/camera_preview/colour.rs @@ -2,6 +2,7 @@ use super::look_fit::{fit_dng_tone, fit_preview, look_proxies}; use super::mono::{fit_dark_tone, monochrome_look}; use super::proxy::LensGeometry; use super::{CameraLook, CameraTone, CameraTransform, ColorData, D50, D65, Mat3, ProfileLook, REC2020, RawFormat, RawImage, ToneCurve, Xy, bradford}; +use lightcraft_raw::profile::ToneCurveEval; /// Long edge of the sensor/JPEG proxy a single photo's look is fitted on (the acceptance gates /// below were set at this size). diff --git a/crates/engine/src/camera_preview/hue_sat.rs b/crates/engine/src/camera_preview/hue_sat.rs index b3692dc4fc..7dce29c6f6 100644 --- a/crates/engine/src/camera_preview/hue_sat.rs +++ b/crates/engine/src/camera_preview/hue_sat.rs @@ -1,6 +1,7 @@ use super::mono::to_prophoto; use super::pairs::{displayed, luma}; use super::{CameraLook, CameraTone, HsvTable, Mat3, ToneMap, luminance_2020}; +use lightcraft_raw::profile::HsvTableApply; /// [`HueSat::apply`] restores the luminance in full only if the table kept at least this share of it. A colour /// the table darkens to [`NO_LUMINANCE_KEPT`] or less (only near-black noise, whose channels go negative) keeps diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 733b576f6f..c2e0ad1e01 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1,5 +1,6 @@ use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity}; use super::*; +use lightcraft_raw::profile::{HsvTableApply, ProfileLookHueSat}; fn steep_toe_scene() -> (Rgb32f, Rgb32f) { let mut sensor = Rgb32f::new(96, 64); diff --git a/crates/engine/src/files/load.rs b/crates/engine/src/files/load.rs index 0e396dd815..9b3afb7929 100644 --- a/crates/engine/src/files/load.rs +++ b/crates/engine/src/files/load.rs @@ -375,6 +375,7 @@ fn local_tone(raw: &lightcraft_raw::RawImage) -> Option Option> { use lightcraft_pipeline::masks::{MatteKind, Mattes}; + use lightcraft_raw::semantic::SemanticMaskExt; if raw.format != lightcraft_raw::RawFormat::Dng { return None; } @@ -410,6 +411,7 @@ fn matte_kind(name: &str) -> Option { /// finish stage's camera tone curve: 32 knots, log-spaced over 12 stops below white; above white /// the camera tone's shoulder continues it. pub(crate) fn dng_tone_curve(curve: &lightcraft_raw::profile::ToneCurve) -> Option { + use lightcraft_raw::profile::ToneCurveEval; let knots: [[f32; 2]; 32] = std::array::from_fn(|i| { let x = 2f32.powf(-12.0 + 12.0 * i as f32 / 31.0); [x, curve.eval(x).min(0.9995)] diff --git a/crates/pipeline/src/local_tone.rs b/crates/pipeline/src/local_tone.rs index bb7adfe51d..cb2d7d3c29 100644 --- a/crates/pipeline/src/local_tone.rs +++ b/crates/pipeline/src/local_tone.rs @@ -13,7 +13,7 @@ use lightcraft_color::{D50, D65, PROPHOTO, REC2020, bradford}; use lightcraft_geom::Point; use lightcraft_raster::Rgb32f; -use lightcraft_raw::gaintable::{GainTableMap, SourcePlacement}; +use lightcraft_raw::gaintable::{GainTableMap, GainTableMapApply, SourcePlacement}; use crate::{Plan, SourceInfo}; use lightcraft_develop::DevelopSettings; diff --git a/crates/raw/src/convert.rs b/crates/raw/src/convert.rs index ed1a63a44d..537929a4d2 100644 --- a/crates/raw/src/convert.rs +++ b/crates/raw/src/convert.rs @@ -101,6 +101,7 @@ fn datetime_from_unix(t: i64) -> Option { second: u8::try_from(c.second()).ok()?, millis: 0, offset_minutes: None, + precision: Default::default(), }; ((1970..=2200).contains(&dt.year)).then_some(dt) } diff --git a/crates/raw/src/gaintable.rs b/crates/raw/src/gaintable.rs index 284f3f1586..1050577d67 100644 --- a/crates/raw/src/gaintable.rs +++ b/crates/raw/src/gaintable.rs @@ -43,8 +43,6 @@ pub use craft_raw::gaintable::GainTableMap; use serde::{Deserialize, Serialize}; - - /// Applying a gain table map (the map, and reading and writing its tag, is `craft-raw`'s). pub trait GainTableMapApply { /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) @@ -188,172 +186,6 @@ impl SourcePlacement { mod tests { use super::*; - /// Tag bytes: the header fields (`v2`: data type, gamma, gain min, gain max), then `data`. - fn tag( - order: ByteOrder, - dims: [u32; 3], - spacing: [f64; 2], - origin: [f64; 2], - weights: [f32; 5], - v2: Option<(u32, f32, f32, f32)>, - data: &[u8], - ) -> Vec { - let be = order == ByteOrder::Big; - let u = |v: u32| if be { v.to_be_bytes() } else { v.to_le_bytes() }; - let d = |v: f64| if be { v.to_be_bytes() } else { v.to_le_bytes() }; - let mut b = Vec::new(); - b.extend_from_slice(&u(dims[0])); - b.extend_from_slice(&u(dims[1])); - for v in [spacing[0], spacing[1], origin[0], origin[1]] { - b.extend_from_slice(&d(v)); - } - b.extend_from_slice(&u(dims[2])); - for w in weights { - b.extend_from_slice(&u(w.to_bits())); - } - if let Some((dt, gamma, min, max)) = v2 { - for v in [dt, gamma.to_bits(), min.to_bits(), max.to_bits()] { - b.extend_from_slice(&u(v)); - } - } - b.extend_from_slice(data); - b - } - - fn floats(order: ByteOrder, g: &[f32]) -> Vec { - g.iter().flat_map(|v| if order == ByteOrder::Big { v.to_be_bytes() } else { v.to_le_bytes() }).collect() - } - - const GREEN: [f32; 5] = [0.0, 1.0, 0.0, 0.0, 0.0]; - - /// 2 × 2 tables of N = 4 points: table (r, c) = base · [1, 2, 3, 4] with base 1, 2, 3, 4. - fn grid() -> Vec { - (0..4).flat_map(|t| (1..=4).map(move |i| (t + 1) as f32 * i as f32)).collect() - } - - #[test] - fn version_2_storage_types_and_gamma() { - let order = ByteOrder::Little; - let v2 = |dt: u32, gamma: f32, data: &[u8]| { - GainTableMap::parse(&tag(order, [1, 1, 4], [1.0, 1.0], [0.0, 0.0], GREEN, Some((dt, gamma, 0.5, 2.5)), data), order, true) - }; - // u8: 0 → GainMin, 255 → GainMax - let m = v2(0, 1.0, &[0, 51, 255, 255]).unwrap(); - let want = [0.5, 0.9, 2.5, 2.5]; - assert!(m.gains.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{:?}", m.gains); - // u16 - let m = v2(1, 1.0, &[0, 0, 0xff, 0xff, 0, 0, 0xff, 0xff]).unwrap(); - assert_eq!(m.gains, vec![0.5, 2.5, 0.5, 2.5]); - // f16 ignores GainMin/GainMax: 1.0, 2.0, 0.5, 0 - let m = v2(2, 1.0, &[0x00, 0x3c, 0x00, 0x40, 0x00, 0x38, 0, 0]).unwrap(); - assert_eq!(m.gains, vec![1.0, 2.0, 0.5, 0.0]); - // f32 with gamma 2 - let m = v2(3, 2.0, &floats(order, &[1.0, 2.0, 3.0, 4.0])).unwrap(); - assert_eq!((m.gains.clone(), m.gamma), (vec![1.0, 2.0, 3.0, 4.0], 2.0)); - // unknown data type, gamma out of range, size for another type: ignored - assert!(v2(4, 1.0, &[0; 4]).is_none()); - assert!(v2(0, 0.1, &[0; 4]).is_none()); - assert!(v2(0, 5.0, &[0; 4]).is_none()); - assert!(v2(1, 1.0, &[0; 4]).is_none()); - // negative integer range - let neg = tag(order, [1, 1, 4], [1.0, 1.0], [0.0, 0.0], GREEN, Some((0, 1.0, -1.0, 1.0)), &[0; 4]); - assert!(GainTableMap::parse(&neg, order, true).is_none()); - } - - #[test] - fn malformed_tags_are_rejected() { - let order = ByteOrder::Big; - let good = tag(order, [2, 2, 4], [0.5, 0.5], [0.25, 0.25], GREEN, None, &floats(order, &grid())); - assert!(GainTableMap::parse(&good, order, false).is_some()); - // every truncation (and an extra byte) - for n in 0..good.len() { - assert!(GainTableMap::parse(&good[..n], order, false).is_none(), "{n} bytes"); - } - let mut long = good.clone(); - long.push(0); - assert!(GainTableMap::parse(&long, order, false).is_none()); - // the wrong byte order reads absurd dimensions - assert!(GainTableMap::parse_in(&good, ByteOrder::Little, false).is_none()); - // read as version 2 the header is too short for the data - assert!(GainTableMap::parse(&good, order, true).is_none()); - let bad = |dims: [u32; 3], spacing: [f64; 2], origin: [f64; 2], gains: &[f32]| { - GainTableMap::parse(&tag(order, dims, spacing, origin, GREEN, None, &floats(order, gains)), order, false) - }; - let mut g = grid(); - g[5] = f32::NAN; - assert!(bad([2, 2, 4], [0.5, 0.5], [0.0, 0.0], &g).is_none(), "NaN gain"); - g[5] = -1.0; - assert!(bad([2, 2, 4], [0.5, 0.5], [0.0, 0.0], &g).is_none(), "negative gain"); - g[5] = f32::INFINITY; - assert!(bad([2, 2, 4], [0.5, 0.5], [0.0, 0.0], &g).is_none(), "infinite gain"); - assert!(bad([2, 2, 4], [0.0, 0.5], [0.0, 0.0], &grid()).is_none(), "zero spacing"); - assert!(bad([2, 2, 4], [0.5, f64::NAN], [0.0, 0.0], &grid()).is_none(), "NaN spacing"); - assert!(bad([2, 2, 4], [0.5, 0.5], [f64::INFINITY, 0.0], &grid()).is_none(), "infinite origin"); - assert!(bad([0, 2, 4], [0.5, 0.5], [0.0, 0.0], &[]).is_none(), "no rows"); - assert!(bad([1, 1, 0], [0.5, 0.5], [0.0, 0.0], &[]).is_none(), "no points"); - // huge dimensions (whose product overflows or exceeds the cap) are rejected before allocating - assert!(bad([u32::MAX, u32::MAX, u32::MAX], [0.5, 0.5], [0.0, 0.0], &grid()).is_none()); - assert!(bad([4096, 4096, 1], [0.5, 0.5], [0.0, 0.0], &grid()).is_none()); - assert!(bad([1, 1, u32::MAX], [0.5, 0.5], [0.0, 0.0], &grid()).is_none()); - // a single table needs no spacing - assert!(bad([1, 1, 2], [0.0, 0.0], [0.0, 0.0], &[1.0, 2.0]).is_some()); - let mut w = GREEN; - w[3] = f32::NAN; - assert!(GainTableMap::parse(&tag(order, [1, 1, 1], [1.0, 1.0], [0.0, 0.0], w, None, &floats(order, &[1.0])), order, false).is_none()); - } - - /// The payload is read in the file's byte order, else big-endian; a little-endian payload in - /// a big-endian file is malformed. - #[test] - fn byte_order_is_the_files_with_a_big_endian_fallback() { - use ByteOrder::{Big, Little}; - let v1 = |o: ByteOrder| tag(o, [2, 2, 4], [0.5, 0.5], [0.25, 0.25], GREEN, None, &floats(o, &grid())); - let v2 = |o: ByteOrder| { - let mut gains = Vec::new(); - for q in [0u16, 0x1234, 0xffff, 0x8000] { - gains.extend_from_slice(&if o == Big { q.to_be_bytes() } else { q.to_le_bytes() }); - } - tag(o, [1, 1, 4], [1.0, 1.0], [0.0, 0.0], GREEN, Some((1, 2.0, 0.5, 2.5)), &gains) - }; - let (want1, want2) = (GainTableMap::parse_in(&v1(Big), Big, false).unwrap(), GainTableMap::parse_in(&v2(Big), Big, true).unwrap()); - assert_eq!(want1.gains, grid()); - assert_eq!((want2.gains[0], want2.gains[2], want2.gamma), (0.5, 2.5, 2.0)); - // in the file's order - assert_eq!(GainTableMap::parse(&v1(Little), Little, false).as_ref(), Some(&want1)); - assert_eq!(GainTableMap::parse(&v2(Little), Little, true).as_ref(), Some(&want2)); - assert_eq!(GainTableMap::parse(&v1(Big), Big, false).as_ref(), Some(&want1)); - // a big-endian payload in a little-endian file: the fallback - assert_eq!(GainTableMap::parse(&v1(Big), Little, false).as_ref(), Some(&want1)); - assert_eq!(GainTableMap::parse(&v2(Big), Little, true).as_ref(), Some(&want2)); - // no little-endian fallback in a big-endian file - assert!(GainTableMap::parse(&v1(Little), Big, false).is_none()); - assert!(GainTableMap::parse(&v2(Little), Big, true).is_none()); - // whatever the grid, a read in the wrong order fails the size checks - for dims in [[1, 1, 1], [6, 8, 257], [48, 64, 2], [255, 16, 1], [256, 16, 1], [1, 4096, 1]] { - for (o, wrong) in [(Big, Little), (Little, Big)] { - let g = vec![1.0; dims.iter().product::() as usize]; - let b = tag(o, dims, [0.5, 0.5], [0.0, 0.0], GREEN, None, &floats(o, &g)); - assert!(GainTableMap::parse_in(&b, o, false).is_some(), "{dims:?}"); - assert!(GainTableMap::parse_in(&b, wrong, false).is_none(), "{dims:?} read {wrong:?}"); - } - } - } - - #[test] - fn writes_what_it_reads() { - for order in [ByteOrder::Big, ByteOrder::Little] { - let m = - GainTableMap::parse(&tag(order, [2, 2, 4], [0.5, 0.5], [0.25, 0.25], GREEN, None, &floats(order, &grid())), order, false).unwrap(); - let (v2, b) = m.to_bytes(order); - assert!(!v2); - assert_eq!(GainTableMap::parse(&b, order, false).unwrap(), m); - let g = GainTableMap { gamma: 2.0, ..m }; - let (v2, b) = g.to_bytes(order); - assert!(v2); - assert_eq!(GainTableMap::parse(&b, order, true).unwrap(), g); - } - } - fn map(dims: [usize; 3], spacing: [f64; 2], origin: [f64; 2], weights: [f32; 5], gains: Vec) -> GainTableMap { let [points_v, points_h, points_n] = dims; let [spacing_v, spacing_h] = spacing; @@ -438,6 +270,7 @@ mod tests { /// the cost of [`GainEval::gain`] per pixel on a real file's map. #[cfg(test)] mod bench { + use super::GainTableMapApply; #[test] #[ignore] fn gain_throughput() { diff --git a/crates/raw/src/hotpixel.rs b/crates/raw/src/hotpixel.rs index e0768eec40..0d1d59bf10 100644 --- a/crates/raw/src/hotpixel.rs +++ b/crates/raw/src/hotpixel.rs @@ -140,7 +140,7 @@ impl RawImage { let black = self.black.mean(); let RawData::U16(d) = &mut self.data else { return 0 }; if self.cpp != 1 - || !crate::cfa_valid(cfa) + || !crate::cfa_valid(&cfa) || w.checked_mul(h) != Some(d.len()) || a.width < 4 * MARGIN || a.height < 4 * MARGIN diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 6c35cd1aa9..d0a16a5ddc 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -46,6 +46,7 @@ pub mod opcodes; mod preview; pub mod profile; mod saturation; +pub mod semantic; pub mod sparse; pub mod spectral; mod tiffraw; @@ -53,7 +54,9 @@ mod unpack; mod vendor; mod wb_estimate; -pub use craft_raw::{BlackLevel, Cfa, MAX_SAMPLES, RawData, RawError, RawFormat, Rect, Result, SemanticMask, ljpeg, probe, semantic_masks, stretched_height}; +pub use craft_raw::{ + BlackLevel, Cfa, MAX_SAMPLES, RawData, RawError, RawFormat, Rect, Result, SemanticMask, ljpeg, probe, semantic_masks, stretched_height, +}; pub use demosaic::{Method, demosaic}; pub use dngwrite::{DngCompression, DngWriteOptions, write_dng, write_rendered_dng}; pub use hotpixel::HOT_PIXEL_MAX_SHARE; @@ -89,7 +92,7 @@ pub fn is_supported(format: RawFormat) -> bool { /// A 2×2 Bayer layout named in code (`"RGGB"`, `"BGGR"`, `"GRBG"`, `"GBRG"`). Only for literal names (tested); /// anything else falls back to RGGB instead of failing. pub(crate) fn bayer(s: &'static str) -> Cfa { - Cfa::bayer(s).unwrap_or(Cfa { width: 2, height: 2, pattern: vec![0, 1, 1, 2] }) + Cfa::bayer(s).unwrap_or(Cfa { width: 2, height: 2, origin_x: 0, origin_y: 0, pattern: vec![0, 1, 1, 2] }) } /// A CFA pattern this crate can address: 1 to 16 sites a side, one colour index per site. @@ -97,7 +100,6 @@ pub(crate) fn cfa_valid(c: &Cfa) -> bool { c.width > 0 && c.height > 0 && c.width <= 16 && c.height <= 16 && c.pattern.len() == c.width * c.height } - /// Decode a raw file. pub fn decode(bytes: &[u8]) -> Result { decode_with(bytes, Mode::Full) @@ -148,7 +150,6 @@ fn decode_with(bytes: &[u8], mode: Mode) -> Result { } } - /// A raw file's description without its samples (see [`probe_info`]). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RawInfo { diff --git a/crates/raw/src/opcodes/tests.rs b/crates/raw/src/opcodes/tests.rs index 50cc9bb5fd..80a858ed00 100644 --- a/crates/raw/src/opcodes/tests.rs +++ b/crates/raw/src/opcodes/tests.rs @@ -1,19 +1,5 @@ use super::*; -#[test] -fn reject_opcode_counts_whose_bytes_exceed_the_remaining_data() { - let mut gain_map = Vec::new(); - for value in [u32::MAX, 1] { - gain_map.extend_from_slice(&value.to_be_bytes()); - } - gain_map.extend(be(&[1.0, 1.0, 0.0, 0.0])); - gain_map.extend_from_slice(&1u32.to_be_bytes()); - assert!(parse_gain_map(Area::default(), &mut Rd { d: &gain_map, p: 0 }).is_none()); - - let delta_count = u32::MAX.to_be_bytes(); - assert!(parse_delta_scale(10, Area::default(), &mut Rd { d: &delta_count, p: 0 }).is_none()); -} - pub(crate) struct ListWriter(pub Vec, pub u32); impl ListWriter { @@ -87,7 +73,7 @@ fn parse_and_apply_area_ops() { let list = parse_list(&blob); assert_eq!(list.len(), 4); assert!(matches!(list[3], Opcode::Unknown { id: 99, .. })); - assert!(list[..3].iter().all(|o| is_applied(o))); + assert!(list[..3].iter().all(is_applied)); let mut buf = vec![0.25f32; w * h]; apply_list(&list, &mut buf, w, h, 1, None, 1.0); // gain map: horizontal ramp 1 → 2 across relative x 0..1 (x / w) diff --git a/crates/raw/src/profile.rs b/crates/raw/src/profile.rs index 532dcf9aae..5b9170a211 100644 --- a/crates/raw/src/profile.rs +++ b/crates/raw/src/profile.rs @@ -26,7 +26,6 @@ pub use craft_raw::profile::{HsvTable, ProfileLook, ToneCurve}; use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear}; use lightcraft_color::{D50, D65, Mat3, PROPHOTO, REC2020, bradford}; - /// Applying a hue/saturation/value table (the table, and reading it from its tags, is `craft-raw`'s). pub trait HsvTableApply: Sized { /// The entry-wise blend `g · a + (1 − g) · b` of two tables of the same shape (`None` otherwise). @@ -40,7 +39,6 @@ pub trait HsvTableApply: Sized { } impl HsvTableApply for HsvTable { - /// The entry-wise blend `g · a + (1 − g) · b` of two tables of the same shape (`None` otherwise). fn blend(a: &HsvTable, b: &HsvTable, g: f64) -> Option { if (a.hue_divisions, a.sat_divisions, a.val_divisions) != (b.hue_divisions, b.sat_divisions, b.val_divisions) { @@ -51,7 +49,6 @@ impl HsvTableApply for HsvTable { Some(HsvTable { data, ..a.clone() }) } - /// Tri-linear lookup at hue `h` (degrees), saturation `s` and value `v` (table coordinates). fn lookup(&self, h: f32, s: f32, v: f32) -> [f32; 3] { let hf = (wrap(h, 360.0) / 360.0 * self.hue_divisions as f32).clamp(0.0, self.hue_divisions as f32); @@ -206,8 +203,6 @@ impl HsvTableApply for HsvTable { } out } - - } fn entry(table: &HsvTable, v: usize, h: usize, s: usize) -> [f32; 3] { @@ -362,7 +357,6 @@ fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { } } - /// Evaluating a profile tone curve. pub trait ToneCurveEval { /// The curve at `x` (0..=1): monotone cubic (Fritsch–Carlson) through the samples. @@ -370,7 +364,6 @@ pub trait ToneCurveEval { } impl ToneCurveEval for ToneCurve { - /// The curve at `x` (0..=1): monotone cubic (Fritsch–Carlson) through the samples. fn eval(&self, x: f32) -> f32 { let p = &self.points; @@ -400,7 +393,6 @@ impl ToneCurveEval for ToneCurve { } } - /// The hue/saturation map of a profile look for a white balance. pub trait ProfileLookHueSat { /// The hue/saturation map for calibration-1 weight `g` (one table: used for any white). @@ -408,7 +400,6 @@ pub trait ProfileLookHueSat { } impl ProfileLookHueSat for ProfileLook { - /// The hue/saturation map for calibration-1 weight `g` (one table: used for any white). fn hue_sat_for(&self, g: f64) -> Option { match &self.hue_sat_map { diff --git a/crates/raw/src/semantic.rs b/crates/raw/src/semantic.rs new file mode 100644 index 0000000000..781c470697 --- /dev/null +++ b/crates/raw/src/semantic.rs @@ -0,0 +1,37 @@ +//! Developed semantic mask conversion to `lightcraft_raster::Image`. + +pub use craft_raw::semantic::*; +use lightcraft_raster::Image; + +/// Extension trait to render a [`SemanticMask`] onto the developed image. +pub trait SemanticMaskExt { + /// The mask over the developed image (the default `crop` of the `active_area`, before + /// orientation), at the mask's own resolution, as 0..255 alpha. `None` for an empty crop. + fn developed(&self, active_area: craft_raw::Rect, crop: craft_raw::Rect) -> Option>; +} + +impl SemanticMaskExt for SemanticMask { + fn developed(&self, active_area: craft_raw::Rect, crop: craft_raw::Rect) -> Option> { + let c = crop.clipped(active_area.width, active_area.height); + if c.width == 0 || c.height == 0 || self.width == 0 || self.height == 0 { + return None; + } + let (fw, fh) = self.sub_area.map_or((self.width, self.height), |a| (a.full_width as usize, a.full_height as usize)); + let (sx, sy) = (fw as f64 / active_area.width as f64, fh as f64 / active_area.height as f64); + let ow = ((c.width as f64 * sx).round() as usize).clamp(1, self.width.max(fw)); + let oh = ((c.height as f64 * sy).round() as usize).clamp(1, self.height.max(fh)); + if ow.checked_mul(oh).is_none_or(|n| n > MAX_MASK_SAMPLES) { + return None; + } + let (kx, ky) = (c.width as f64 / ow as f64, c.height as f64 / oh as f64); + let mut out = Image::new(ow, oh); + lightcraft_raster::par_rows(&mut out.data, ow, |y, row| { + let ay = c.y as f64 + (y as f64 + 0.5) * ky; + for (x, v) in row.iter_mut().enumerate() { + let ax = c.x as f64 + (x as f64 + 0.5) * kx; + *v = (self.value_at(ax * sx, ay * sy) * 255.0).round() as u8; + } + }); + Some(out) + } +} diff --git a/crates/raw/src/tests.rs b/crates/raw/src/tests.rs index a65927312f..206a43b062 100644 --- a/crates/raw/src/tests.rs +++ b/crates/raw/src/tests.rs @@ -393,6 +393,7 @@ fn private_compression_99_is_a_raw() { /// without the block, or an RGB image carrying it, stays an ordinary image. #[test] fn uncompressed_leaf_mos_is_a_raw() { + const LEAF_DATA: u16 = 0x8606; let mosaic = |leaf_data: bool| { let mut ifd = IfdBuilder::new(); ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); @@ -542,20 +543,6 @@ fn lossless_jpeg_cfa_tiff_decodes() { assert_eq!(r.cfa.unwrap().name(), "RGGB"); } -/// Hasselblad's own lossless-JPEG coding (selection value 8, as in FFF and most compressed 3FR files) of the -/// same layout decodes: the file is read like the uncompressed one. -#[test] -fn selection_value_8_cfa_tiff_decodes() { - let strip = crate::ljpeg_fixtures::encode_hasselblad(&cfa_samples(), 8, 6); - let bytes = plain_cfa_tiff(7, strip, None); - assert_eq!(probe(&bytes), Some(RawFormat::CfaTiff)); - let r = decode(&bytes).unwrap(); - assert_eq!((r.format, r.width, r.height), (RawFormat::CfaTiff, 8, 6)); - assert_eq!(r.data, RawData::U16(cfa_samples())); - assert_eq!(r.cfa.unwrap().name(), "RGGB"); - assert_eq!(probe_info(&bytes).unwrap().format, RawFormat::CfaTiff); -} - /// A lossless-JPEG scan whose predictor selection value is neither 0 to 7 (T.81) nor 8 (Hasselblad) is not a /// coding the lossless decoder knows: the file stays an undecodable raw, with that as the reason, and keeps the /// stand-in preview an unsupported container gets. diff --git a/crates/raw/src/vendor/arw.rs b/crates/raw/src/vendor/arw.rs index dbe413392f..ba4fc8e828 100644 --- a/crates/raw/src/vendor/arw.rs +++ b/crates/raw/src/vendor/arw.rs @@ -714,7 +714,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result { }; let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { - (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => Cfa { width: 2, height: 2, pattern: p.to_vec() }, + (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => { + Cfa { width: 2, height: 2, origin_x: 0, origin_y: 0, pattern: p.to_vec() } + } _ => crate::bayer("RGGB"), }; let default_black = if scale_bits >= 14 { 512.0 } else { 128.0 }; diff --git a/crates/raw/src/vendor/huffman.rs b/crates/raw/src/vendor/huffman.rs index 56219ba5f3..e6a1da59fb 100644 --- a/crates/raw/src/vendor/huffman.rs +++ b/crates/raw/src/vendor/huffman.rs @@ -79,11 +79,6 @@ impl<'a> Bits<'a> { pub fn consumed_bits(&self) -> usize { self.pos * 8 - self.n as usize } - /// Whether more bits were handed out than the source holds (the zeros read past its end are lookahead padding, - /// not data; using them would fabricate samples). - pub fn overrun(&self) -> bool { - self.consumed_bits() > self.src.len() * 8 - } } /// Decode one difference: Huffman category then T.81 additional bits. diff --git a/crates/raw/src/vendor/raf.rs b/crates/raw/src/vendor/raf.rs index 9d4976617d..2fa99d2359 100644 --- a/crates/raw/src/vendor/raf.rs +++ b/crates/raw/src/vendor/raf.rs @@ -102,7 +102,9 @@ fn camera_name(b: &[u8]) -> String { /// The CFA: X-Trans from the (reversed) layout record, else RGGB. fn cfa(h: &Header) -> Cfa { match record(h, XTRANS_LAYOUT) { - Some(l) if l.len() == 36 && l.iter().all(|&c| c <= 2) => Cfa { width: 6, height: 6, pattern: l.iter().rev().copied().collect() }, + Some(l) if l.len() == 36 && l.iter().all(|&c| c <= 2) => { + Cfa { width: 6, height: 6, origin_x: 0, origin_y: 0, pattern: l.iter().rev().copied().collect() } + } _ => crate::bayer("RGGB"), } } diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index e8e5185374..79b1a15d40 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -946,7 +946,7 @@ fn mask_ifd(w: usize, h: usize, name: &str, px: Vec) -> IfdBuilder { /// developed image (default crop of the active area), and doesn't disturb the raw decode. #[test] fn semantic_masks_are_read_and_placed() { - use lightcraft_raw::semantic::MaskSubArea; + use lightcraft_raw::semantic::{MaskSubArea, SemanticMaskExt}; for order in [ByteOrder::Little, ByteOrder::Big] { let bytes = profile_dng(order, |ifd0| { // a 4 × 2 crop at (top 1, left 2) of an 8 × 4 mask over the 8 × 6 image @@ -985,6 +985,7 @@ fn semantic_masks_are_read_and_placed() { /// doesn't fit; the raw image still decodes. #[test] fn malformed_semantic_masks_are_skipped() { + use lightcraft_raw::semantic::SemanticMaskExt; let bytes = profile_dng(ByteOrder::Little, |ifd0| { ifd0.add_sub_ifd(mask_ifd(2, 2, "", vec![1, 2, 3, 4])); // no SemanticName let mut rgb = mask_ifd(2, 2, "rgb", vec![0; 12]); From 4e7c9d74afcd53c5eb7aecb0fcb7edcf9cd51afc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 06:06:00 +0000 Subject: [PATCH 19/23] fix(codecs): initialize craft_heif::Options with ..Default::default() --- crates/codecs/src/heif.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/codecs/src/heif.rs b/crates/codecs/src/heif.rs index 3e899bcdd7..d957ca9178 100644 --- a/crates/codecs/src/heif.rs +++ b/crates/codecs/src/heif.rs @@ -57,7 +57,7 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { if (info.width as u64).saturating_mul(info.height as u64) > opts.max_pixels { return Err(Error::TooLarge(info.width as u64, info.height as u64)); } - let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true }; + let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true, ..Default::default() }; // A small decode (a thumbnail or a cataloguing probe) uses the file's own thumbnail image when // it is at least as large as asked: iPhones store one of 320 × 240, and decoding it is a // hundredth of the work of the 12 MP photo. From c6f95d542dffb96beef00310bcda8fea51fd4897 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 06:28:57 +0000 Subject: [PATCH 20/23] docs: update metadata parity source paths --- docs/file-format-parity.md | 2 +- docs/parity-checklist.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7f82adf2e9..86df6c9549 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -55,7 +55,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/ | Lightroom (cloud) library `.lrlibrary` | native | ⬜ | cloud library format, local cache only | | Write back to `.lrcat` | native | ⬜ (one-way migration by design) | | | Keyword lists (text) | import / export | ✅ | | -| GPX track logs | ✅ | ✅ | `crates/meta/src/gpx.rs` | +| GPX track logs | ✅ | ✅ | `crates/meta/src/lib.rs` (re-exports shared `craft_metadata::parse_gpx`), `crates/engine/src/cmd/manage.rs` | | Export presets, metadata presets, filename templates | ✅ (`.lrtemplate`) | ✅ own JSON | not interchangeable | | Lightroom plug-ins (`.lrplugin`, `.lrdevplugin`) | ✅ | ⬜ | see ecosystem in [target-app-parity.md](target-app-parity.md) | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index e8dfe5525a..c03032d2f8 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -169,7 +169,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-META-COPYRIGHT-DEFAULT | Default copyright on import | P1 | ✅ | `cmd:library.preferences` (`import.copyright`, `import.creator`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import → Metadata; fills only photos without their own | | LR-META-LOCATION | Location editing | P2 | 🟡 | `cmd:photo.setMeta` (`location`, `city`, `state`, `country`, `gps`), `cmd:metadata.reverseGeocode` | place fields and GPS (decimal or degrees / minutes / seconds) edited in Info, read/written as IPTC Core / Photoshop / EXIF XMP; typed GPS consumes the full expression, accepts case-insensitive axis-appropriate hemisphere markers, and refuses malformed text or DMS minutes/seconds outside [0,60) before changing metadata; Show on Map opens OpenStreetMap; Fill Location fills empty City / State / Country from GPS offline (GeoNames, downloaded on request: `cmd:metadata.downloadPlaceNames`); no embedded map | | LR-META-COPYPASTE | Copy / paste metadata | P2 | ✅ | `cmd:photo.copyMetadata`, `cmd:photo.pasteMetadata` | title, caption, alt text, extended description, copyright (notice, status, usage terms, info URL), creator, place fields, keywords; `fields` picks a subset | -| LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | manual rereading also reads sidecar-free JPEG embedded XMP (first complete standard APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; no extended assembly or between-scan packets, not strict whole-JPEG validation; reader cases in `crates/engine/src/sidecar.rs`); a discovered unreadable sidecar fails without embedded fallback; procedural refresh/undo, non-UTF-8 sidecar and two explicit malformed fixtures in `crates/engine/src/tests/xmp.rs` (file-write checks use auto-write off); sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; keywords are saved as names in `dc:subject` and paths in `lr:hierarchicalSubject` (`keywords::to_file`; before, paths went into `dc:subject`); saving merges into an existing sidecar (`crates/meta/src/xmp_merge.rs`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte (ownership follows namespace URI: foreign namespaces using `lc:` or `xmp:` cannot supply native settings or ratings and survive saving), an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`.xmp` for all but the raw; an import ranks the files it is adding the same way, so a TIFF or JPEG arriving beside its raw reads its own `.xmp` and never the raw's `IMG_0001.xmp`, issue #1905); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); radial masks (`Mask/CircularGradient`) keep Lightroom's inside / outside: `crs:Flipped="true"` is the effect-inside flag of current masks and of the legacy Radial Filter, `crs:MaskInverted` the inversion, checked against Lightroom Classic's renders (issue #1815); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934); settings Lightroom writes only for itself (`CompatibleVersion`, the profile digests, the lens profile's name / file / setup, `CropConstrainToUnitSquare`, the lens profile's strength at 100 %) are not reported as unimported (`crates/engine/src/crs.rs`); malformed XMP capture-time values remain in the raw property map and are not projected, allowing the next valid field to supply the capture time | +| LR-META-XMP | XMP read/write | P0 | ✅ | `cmd:photo.saveMetadataToFile`, `cmd:photo.readMetadataFromFile`, `cmd:library.xmpPreferences`, `crates/engine/src/sidecar.rs`, `docs/xmp-interop.md` | manual rereading also reads sidecar-free JPEG embedded XMP (first complete standard APP1 before SOS/EOI, within 16 MiB of headers and 4096 marker/fill steps; no extended assembly or between-scan packets, not strict whole-JPEG validation; reader cases in `crates/engine/src/sidecar.rs`); a discovered unreadable sidecar fails without embedded fallback; procedural refresh/undo, non-UTF-8 sidecar and two explicit malformed fixtures in `crates/engine/src/tests/xmp.rs` (file-write checks use auto-write off); sidecar wins for metadata; a sidecar capture time (`exif:DateTimeOriginal` / `photoshop:DateCreated` / `xmp:CreateDate`) fills in only when the file has none; keywords are saved as names in `dc:subject` and paths in `lr:hierarchicalSubject` (`keywords::to_file`; before, paths went into `dc:subject`); saving merges into an existing sidecar (the `lightcraft_meta::merge_xmp` adapter in `crates/meta/src/lib.rs` delegates to shared `craft_metadata::merge_xmp`): another app's `crs:`, `xmpMM:History` and unknown namespaces are kept byte for byte (ownership follows namespace URI: foreign namespaces using `lc:` or `xmp:` cannot supply native settings or ratings and survive saving), an unreadable sidecar is backed up first; with stem naming, files sharing a stem (raw + JPEG) get separate sidecars (`.xmp` for all but the raw; an import ranks the files it is adding the same way, so a TIFF or JPEG arriving beside its raw reads its own `.xmp` and never the raw's `IMG_0001.xmp`, issue #1905); a `crs:` custom white balance on a relative-WB raw is shifted from `crs:AsShotTemperature` rather than read as Kelvin, or kept As Shot and reported when the packet has no as-shot white (issue #510); heal and clone spots (`crs:RetouchAreas`, legacy `crs:RetouchInfo`) are read into our spots (`crates/engine/src/crs_masks.rs`, see `docs/xmp-interop.md` → Spot removal); radial masks (`Mask/CircularGradient`) keep Lightroom's inside / outside: `crs:Flipped="true"` is the effect-inside flag of current masks and of the legacy Radial Filter, `crs:MaskInverted` the inversion, checked against Lightroom Classic's renders (issue #1815); Read Metadata from File never writes the sidecar back, even with auto-write on, so another app's later `crs:` edits are still read (issue #934); settings Lightroom writes only for itself (`CompatibleVersion`, the profile digests, the lens profile's name / file / setup, `CropConstrainToUnitSquare`, the lens profile's strength at 100 %) are not reported as unimported (`crates/engine/src/crs.rs`); malformed XMP capture-time values remain in the raw property map and are not projected, allowing the next valid field to supply the capture time | | LR-META-EXIF-FULL | Full EXIF/IPTC [Classic] | P1 | ✅ | `cmd:photo.allMetadata`, `cmd:dialog.allMetadata`, `crates/meta/src/tags.rs`, `crates/meta/src/exif.rs`, `crates/meta/src/iptc.rs` | `photo.allMetadata` reuses loaded original bytes for embedded XMP and keeps sidecar precedence (`crates/engine/src/tests/xmp.rs`); read and written on export; Info ▸ All Metadata…: every TIFF / EXIF / GPS / interop tag (named, common values spelled out) and the XMP fields, searchable; PSD/PSB EXIF resource 1058 and XMP resource 1060 feed the same metadata rows and preserve sidecar precedence; metadata presets; malformed EXIF clocks with extra components are rejected so valid DateTimeDigitized, IFD0 DateTime or XMP fallbacks apply, while raw values stay visible in All Metadata (`crates/meta/src/exif.rs`, `crates/engine/src/tests/import.rs`) | ## F. Edit panel — global adjustments (EDIT) @@ -740,7 +740,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-MAP-VIEW | Map view | P2 | ⬜ | | | | LRC-MAP-GEOTAG | Drag photos onto the map | P2 | ⬜ | | | | LRC-MAP-LOCATIONS | Saved locations | P2 | ⬜ | | | -| LRC-MAP-TRACKLOG | GPS track logs | P2 | ✅ | `cmd:photo.autoTagTracklog`, `cmd:photo.tagFromTracklog`, `crates/meta/src/gpx.rs` | Photo ▸ Auto-Tag from Tracklog…: a GPX 1.0 / 1.1 track log sets the GPS of the selected photos by capture time — interpolated between the points of a track segment, else the nearest point within `maxGap` (10 min); never across segment breaks. XML character references in coordinate attributes and point text decode before parsing; malformed or unknown references return an error; CDATA stays literal. The camera's time zone comes from the photo (Exif offset) or is asked for; photos that already have a location keep it unless `replace`; `dryRun` previews; one undo step. No track drawn on a map (no Map module); incomplete or malformed ISO point times are untimed and cannot match a photo | +| LRC-MAP-TRACKLOG | GPS track logs | P2 | ✅ | `cmd:photo.autoTagTracklog`, `cmd:photo.tagFromTracklog`, `crates/meta/src/lib.rs` (re-exports shared `craft_metadata::parse_gpx`), `crates/engine/src/cmd/manage.rs` | Photo ▸ Auto-Tag from Tracklog…: a GPX 1.0 / 1.1 track log sets the GPS of the selected photos by capture time — interpolated between the points of a track segment, else the nearest point within `maxGap` (10 min); never across segment breaks. XML character references in coordinate attributes and point text decode before parsing; malformed or unknown references return an error; CDATA stays literal. The camera's time zone comes from the photo (Exif offset) or is asked for; photos that already have a location keep it unless `replace`; `dryRun` previews; one undo step. No track drawn on a map (no Map module); incomplete or malformed ISO point times are untimed and cannot match a photo | | LRC-MAP-FILTER | Location filter bar | P2 | ⬜ | | | | LRC-MAP-REVGEO | Reverse geocoding | P2 | 🟡 | `cmd:metadata.reverseGeocode` | offline from GeoNames (City / State / Country, no sublocation); the list holds towns of 15 000 people or more, so a smaller town gets the nearest larger one (the tooltip and command help say so); `maxDistance` leaves City empty past a distance and names the town as `nearestCity` (issue #2242); no online provider | | LRC-BOOK-SETTINGS | Book settings | P2 | ⬜ | | | From de565ff902011e3a160bf85f92bfc8747e83888a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 06:43:43 +0000 Subject: [PATCH 21/23] docs: refresh shared metadata and raw parity paths --- docs/parity-checklist.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index c03032d2f8..4cde34e939 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -81,8 +81,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/jxl.rs` | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/vendor/crw.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/vendor/nefc.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/vendor/kodak.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/vendor/hasselblad.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/vendor/mrw.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/vendor/srw.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `craft-heif` from craft-libs, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | -| LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/dng.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/convert.rs` (adapter for shared `craft-raw`) | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/convert.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/convert.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/convert.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/convert.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/convert.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/convert.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `craft-heif` from craft-libs, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | +| LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/convert.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | | LR-IMP-MOVE | Move on import [Classic] | P1 | ✅ | `cmd:library.import` (`mode` move), `crates/engine/src/import_move.rs`, `crates/engine/src/tests/import_move.rs`, `crates/ui-egui/src/dialogs/import.rs` | Transfer ▸ Move with Copy's destination, folders (day / month / one folder / custom template), rename template and example destination; XMP sidecars (both namings) move along; each source is removed only after its destination is written (hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate, unchecked files keep their sources, taken names get -1, -2…, never overwritten; if the rename sequence runs out, later files are reported as failed and earlier completed moves remain catalogued; files already in the destination/library are added in place; sources that can't be removed (read-only card) are kept and reported (`kept`). Undo removes the photos from the library but leaves the moved files at the destination. No Copy as DNG while moving | @@ -214,7 +214,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-DETAIL-AISHARPEN | AI sharpen | OOS | 🚫 | | | | LR-EDIT-DETAIL-HOTPIXELS | Hot pixel removal | P1 | ✅ | `check:detail.nrOutliers`, `crates/raw/src/hotpixel.rs`, `crates/engine/src/files/load.rs` (`load_bytes_now`), `cmd:app.hotPixelLimit` | Lightroom has no control for this. Here a box under Noise Reduction (raws only), on for newly imported raws and off for edits saved before it existed (issue #1345): single photosites far above all their same-colour neighbours are replaced in the mosaic before demosaicing; a point lit across neighbouring photosites (a star, a spark) is kept. A raw with more than 0.2 % of its photosites to replace (real light kept doesn't count) is left unchanged; Settings ▸ Performance ▸ Hot pixel limit sets the share (test `the_hot_pixel_limit_renders_afresh_only_the_photos_that_remove_hot_pixels`). Switching it decodes the raw again (tests `hot_pixel_box_is_on_for_new_raws_only`, `hot_pixel_box_decodes_the_raw_again`) | | LR-EDIT-OPTICS-CA | Remove chromatic aberration | P1 | ✅ | `crates/ui-egui/src/panels/edit.rs` (checkbox), `ctl:optics.caRed`, `ctl:optics.caBlue` | | -| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/vendor/nef_lens.rs`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | +| LR-EDIT-OPTICS-PROFILE | Lens profile corrections | P1 | 🟡 | `ctl:optics.profileDistortion`, `ctl:optics.profileVignetting`, `crates/pipeline/src/optics.rs`, `crates/raw/src/vendor/rw2.rs`, `crates/raw/src/vendor/raf_lens.rs`, `crates/engine/src/crs.rs` | uses corrections embedded in the file: DNG `WarpRectilinear` / `WarpRectilinear2` (opcode 14, DNG 1.6: degree-14 radial polynomial, valid-radius clamp, reciprocal option, applied in list order with the spec's skip rule for a `WarpRectilinear` after an optional one, so Pixel DNGs' two-stage warp is corrected; up to 3 chained stages, sampled on the CPU because the polynomials need `f64`; issue #635) / `FixVignetteRadial`, and the camera's own distortion correction in Panasonic / Leica RW2 / RWL files (tag `0x0119`, read as the equivalent `WarpRectilinear`; on 79 photos from 13 bodies and 11 lenses the corrected render lines up with the camera JPEG within 0.75 px at 1440 px at the corners, from up to 13 % of the half diagonal uncorrected; issue #256); an imported preset's `LensProfileEnable=0` leaves them on, as Lightroom applies built-in corrections regardless (inferred); Sony ILCE-7RM4A Bayer ARW raw-IFD distortion tables (`0x7037`, 16-sample layout, native 3:2 framing) use the same warp path, enabled for the independently validated ILCE-7RM4A with FE 24–105 and FE 200–600 lenses, ILCE-7M3 (FE 16–35 F4 ZA, FE 28–70, FE 50 F1.8; 26 shots within 0.06–0.44 px median of the camera JPEG at 6000 px, from up to 26 px uncorrected), and ILCE-7CR full-frame Bayer 3:2 files with correction Auto or forced Auto (a separate corrected-radius conversion validated against camera JPEGs with FE 24-50mm, FE 16-25mm and FE 50mm lenses); A7CR Off, APS-C, aspect crops and lossless M/S remain uncorrected; ILCE-7RM6 verified against the camera JPEG on 54 photos with three lenses (`docs/sony-ilce7rm6-lens-corrections.md`); other Sony models remain uncorrected (see `docs/sony-lens-corrections.md`); Nikon NEF distortion from NikonNEFInfo (`0xc7d5`: polynomial, frame-filling zoom and the optical-centre offset left by in-body stabilisation; `crates/raw/src/convert.rs`, `docs/nikon-lens-corrections.md`) for the Z 6II, Z 8 and Z f, full-frame image area only: F-mount lenses on the FTZ match the camera JPEG within 0.2 px median, Z lenses within 0.5–1.5 px except the 24-70 f/4's wide end, where the camera applies a further correction that is not in the readable data (7 px median at 24 mm, from 16 px / 106 px p95 uncorrected); Fujifilm RAF raw-IFD tables (`0xf00b` distortion, `0xf010` vignetting; `crates/raw/src/vendor/raf_lens.rs`, `docs/fuji-lens-corrections.md`) become a `WarpRectilinear` with the camera's frame-filling zoom and a `FixVignetteRadial` gain for 59 body models with sample files checked against the camera JPEG (the table indexed by the source radius with last knot at the corner; on 67 body/lens combinations the corrected render's radial shape error against the camera JPEG falls from a median of 0.72 % to 0.05 % of the half diagonal, largest 0.42 %, and the vignetting gain of the JPEG tracks the table at a median correlation of 0.987); files whose table scale is not the recorded image's half diagonal (X-T30 III, X-M5, X-T5 crops; X-S20 supported) and six unmatched bodies stay uncorrected; Fujifilm's lateral CA table (`0xf00f`) is real but is not applied, because our demosaic already registers the planes and the stored shift over-corrects; vignetting and lateral CA data of Olympus raws not read yet; Sony ARW shading, lateral CA and distortion tables (raw IFD `0x7031`–`0x7037`, with the encrypted `SR2SubIFD` copies as a checked fallback) are decoded with their camera settings, provenance and framing evidence for every body that records them (`crates/raw/src/lens_metadata.rs`), but only the ILCE-7RM4A, ILCE-7M3, ILCE-7RM6 and ILCE-7CR use the separate distortion conversions above; Sony shading and CA semantics are not validated beyond the ILCE-7RM6's (lateral CA off) (`docs/sony-lens-corrections.md`); Reload from Disk reads the file's lens data for photos catalogued without it and turns the correction on for those still at import settings (issue #314); lens-profile database: a lensfun-format XML database in `LIGHTCRAFT_LENSFUN_DIR` (none is bundled) supplies distortion (poly3 / poly5 / PTLens), TCA and vignetting for lenses it lists (`crates/lensdb`, `crates/engine/src/lens_profiles.rs`, `docs/lens-profiles.md`); raws that name no lens model (Nikon DSLRs: maker-note lens specification only) look it up by a name built from the specification (`24-70mm f/2.8`) and take only a profile named exactly that; lens database: the desktop app offers lensfun's `data/db` once on the first launch (Download / Not Now with its size; Settings ▸ General ▸ Lens profiles downloads it later; nothing is fetched without that click; CC BY-SA 3.0, pinned by commit, size and SHA-256, never bundled; `cmd:lens.downloadDatabase`, `crates/engine/src/lensfun_download.rs`) and downloads it with an activity row, and when it arrives every library raw whose lens it knows is looked up again in the background (`cmd:library.refreshLensProfiles`, `crates/engine/src/cmd/lens_refresh.rs`), as is a photo whose Enable Lens Corrections is ticked; the Optics panel names the loaded profile and its source, or says "No lens profile found for " (`crates/ui-egui/src/lens_db.rs`); presets, Copy / Paste and Sync carry only the switch and amounts, never a profile (`crates/engine/src/tests/lens_refresh.rs`); no source picker or own calibration yet | ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | @@ -836,7 +836,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-27 | patch | MENU-BAR: every shortcut the app shows (a menu row, a button's tooltip, a hint, the empty-album line, the Keyboard Shortcuts dialog) lists its modifiers on macOS in the menu bar's order, ⌃⌥⇧⌘ (`⇧⌘I`, not `⌘⇧I`); the empty-album line follows the keymap; status counts unchanged | | 2026-10-25 | patch | LR-IMP-FORMATS: JPEG ICC APP2 chunk sequences are validated before colour conversion; valid reordered chunks remain supported and malformed profiles use the existing sRGB fallback; status unchanged (🟡) | | 2026-10-13 | minor | LR-IMP-FORMATS / LR-IMP-CAMERA-COVERAGE: Canon CRW decodes (clean-room; 6 bodies pixel-exact, G5 preview-only) | -| 2026-10-26 | minor | LR-IMP-FORMATS: the Canon CRW decoder moved to craft-libs as `craft-crw` (path dependency until that branch merges); `crates/raw/src/vendor/crw.rs` is the adapter, the clean-room record lives in craft-libs (crates/crw/clean-room there) | +| 2026-10-26 | minor | LR-IMP-FORMATS: the Canon CRW decoder moved to craft-libs as `craft-crw` (path dependency until that branch merges); `crates/raw/src/convert.rs` is the adapter, the clean-room record lives in craft-libs (crates/crw/clean-room there) | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | patch | LR-META-LOCATION: Info GPS text validates the complete decimal/DMS expression, axis markers and component ranges before metadata changes; readiness and feature counts unchanged | From 864b761f0c9c953d3ebf5d3d178ed87116ef72a5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 06:51:48 +0000 Subject: [PATCH 22/23] docs: clarify raw preview fallback in parity tracker --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 4cde34e939..0d9f260e45 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -81,7 +81,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-IMP-PROFILES | Import profiles & presets | P1 | ✅ | `cmd:file.importPresets`, `cmd:preset.import`, `cmd:profile.import`, `crates/engine/src/preset_import.rs`, `crates/engine/src/preset_luminar.rs` | presets: .lcpreset, XMP, classic .lrtemplate (local adjustment templates become mask effects, LR-MASK-EFFECTS), photos carrying edits ("DNG presets"), Luminar looks (.lmp, .mplumpack collections; sliders with a counterpart), .zip bundles, folders (folder → group), drag & drop (an `.xmp` dropped together with its photo is that photo's sidecar and is not imported as a preset, issue #936); masks carried over; unmapped settings reported (fields that only describe the preset or photo, e.g. `Cluster`, `SortName`, `SupportsAmount2`, the as-shot white, empty Point Color slots, are not); profiles: .cube 3D LUTs (one toast reports both halves; a LUT that fails is named with its reason); a preset that names a profile (`crs:Look`) applies the imported profile of that name, imported before or after it, and Lightroom's basic profiles map to ours (`crates/engine/src/profile_refs.rs`, issue #1001); Adobe profile formats deliberately unsupported (so `.xmp` creative profiles' colour tables aren't read) | | LR-IMP-LOCAL | Work on files in place | P0 | ✅ | `cmd:library.browse`, `cmd:photo.addToLibrary`, `cmd:library.import` (mode add), `cmd:local.addRoot`, `cmd:local.hide`, `cmd:local.restoreHidden`, `crates/engine/src/cmd/browse.rs`, `crates/ui-egui/src/panels/left.rs` (`local_section`), `crates/ui-egui/src/panels/grid.rs` (`folder_header`), `crates/engine/src/import.rs` (`browse_queue`) | Local: browse Pictures / Desktop / Downloads / Home or any folder without adding it (breadcrumb, Include subfolders, Add N to My Photos); the folder's photos join the view batch by batch while they are read, first screen first (`browse_queue`: newest file first for the default sort), so a 2,933-raw wedding folder shows its first photos in 0.9 s instead of after every file was read (30.6 s; the whole folder still takes ~30 s); browsed photos stay out of All Photos, albums and counts (album commands skip them and the album menus say to Add to My Photos first, issue #684); folders picked with Browse Folder… (or Keep in Local / Add to Local on a folder row) stay listed across restarts, and browsing a folder inside a listed one highlights it inside that tree (opened down to it, siblings reachable) instead of adding a root; edits go to XMP sidecars; importing promotes them; right-click a top-level location → Remove from Local hides the shortcut only (nothing on disk or in the catalog changes), saved with the UI state, and “Show N hidden locations” (or Browse Folder… on it) brings it back, each on its own from the row's list when several are hidden, or all at once with Restore All (issue #2114); a folder is one location however its path is spelled (`/` or `\`, trailing separator, `.`/`..`, drive-letter case; `folder_key` in `crates/catalog/src/query.rs`); browsed photos nobody changed are forgotten once their folder has not been browsed for 30 days (Settings → Performance → Local folders, 0 = never; checked when the library opens, or `cmd:library.forgetLocal` with `dryRun`; files and sidecars stay, browsing again brings them back; see `crates/catalog/src/local.rs` for what counts as a change); browsing a folder again forgets at once the untouched records of its files that another app deleted or moved, so they no longer fail to load on every visit (issue #1392; changed ones stay, shown as missing); browsing a folder keeps the active photo when the folder shows it, else makes the folder's first photo active as it arrives, the same rule as albums and the other sources (`Session::keep_active_in_view`; issue #1447: before, a library photo stayed active, so Photo Grid marked nothing and Detail, the histogram and the info showed a photo the folder doesn't hold) | | LR-IMP-SIDECAR-SPLIT | Separate XMP sidecar variants | P2 | ⬜ | `cmd:library.xmpPreferences` | sidecar naming option exists (stem/full), no split sidecars | -| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/convert.rs` (adapter for shared `craft-raw`) | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/convert.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/convert.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/convert.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/convert.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/convert.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/convert.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raws LightCraft cannot decode open as `preview_only` with any usable embedded JPEG, also Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan; ones with no JPEG still fail with "without an embedded preview", AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `craft-heif` from craft-libs, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (the shot's aspect ratio from the maker note's `AspectInfo`); the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275), and any decode failure of a recognised raw, not only an unsupported variant Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | +| LR-IMP-FORMATS | Supported formats | P0 | 🟡 | `crates/codecs/src/lib.rs`, `crates/raw/src/lib.rs`, `crates/raw/src/convert.rs` (adapter for shared `craft-raw`) | JPEG (ICC APP2 sequences require unique complete chunks with consistent totals; malformed profiles use the existing unsupported-profile sRGB fallback; a Samsung panorama whose scan data runs into its SEF trailer with no end-of-image marker reads as the image before the trailer, while a JPEG cut short is still refused, issue #3350, `crates/codecs/src/jpeg.rs`), PNG, TIFF (1- to 64-bit integer, 16- to 64-bit float, incl. bilevel and CCITT fax), WebP, JXL, PSD, GIF, BMP (lossy wide-gamut JXL decodes to the right colours: jxl-oxide desaturated XYB rendered to P3/Rec. 2020, worked around in `crates/codecs/src/jxl.rs`); DNG (incl. lossy / Smart Preview DNG and DNG 1.7 JPEG XL tiles/strips: lossless ones decode bit-exactly on synthetic CFA and LinearRaw files, lossy ones are restored to the declared primaries and transfer curve (linear, sRGB, BT.709 or a power; PQ / HLG stay preview-only) without clipping or gamut mapping, checked on one real file with 108 lossy tiles and on 2 Lightroom Classic 15.1 lossy LinearRaw DNGs (ILCE-7CM2) whose tiles declare Rec. 2100 primaries with the sRGB curve, which were preview-only before, and any tile that fails to decode makes the file preview-only; DNG 1.7 row/column-interleaved rasters (`RowInterleaveFactor` / `ColumnInterleaveFactor`) are undone before the mosaic is read, so a file from Adobe's converter with a 2×2 interleave no longer decodes as four scaled-down copies in the wrong colours; a dimension the factor does not divide decodes with short trailing fields; verified on 4 real ILCE-6400 JPEG XL DNGs rendering bit-identical to their non-interleaved twins, factors above 2 rest on the plain reading of the tag; a single-chunk JPEG XL preview IFD is offered as the embedded preview; a DNG whose samples pile up at one value well below its stated `WhiteLevel`, as a camera app's 12-bit Bayer DNG that states 4095 and clips at 3567, has those samples raised to the white level on decode, so highlight reconstruction sees the clipped areas instead of white balance tinting them magenta, issue #548, `crates/raw/src/saturation.rs`), CR2 (colour-filter layout from the file's `CR2CFAPattern` tag, issue #85), CRW (CIFF, the 2000–2004 Canon bodies: clean-room-derived decode frozen in `craft-libs crates/crw/clean-room/02-crw-format.md`, `crates/raw/src/convert.rs`; EOS D30/D60/10D/300D, PowerShot G1 (10-bit GBRG) and G6 pixel-exact against a black-box reference on 28 of 29 corpus files incl. 18 private D60s; as-shot white balance from the ColorBalance record's ShotInfo-selected slot; black level from the darkest flat masked-border strip; rotation from ImageInfo; starting look fitted from the file's own embedded JPEG like CR2/CR3 (`camera_preview::file_local_look`), accepted on all 10 decodable public corpus files (holdout RMS 0.009–0.047), with the fitted matrix absorbing the white balance on the bodies without a ColorBalance record (D30, PowerShots); the PowerShot G5's anomalous entropy coding and the pre-CIFF compacts stay preview-only, and G2/G3/G4/Pro1/S-series decode unverified for lack of redistributable samples), ARW (pre-2017 bodies: white balance and black level from the encrypted `SR2SubIFD`, issue #148, its `WB_RGGBLevels` being the white balance the camera applied, issue #535; the DSLR-A900's packed 12-bit strip, two pixels per three bytes, read only when the strip is exactly 1.5 bytes per pixel, with its camera-JPEG window centred, checked on one CC0 file (A850 unmeasured); downsized Sony lossless YCbCr 4:2:0 / 4:2:2 tiles decoded to linear RGB, verified on private ILCE-7M4 3:2 & 4:3 examples including 16-bit full-resolution export; Sony DSC-R1 .SR2 decodes, its big-endian 16-bit words read in the order that fits the sample range, checked on the CC0 3221 sample; its crop and white balance live in the SR2SubIFD and are not read yet; ARW6 Compressed / Compressed (HQ) of the ILCE-7RM6 (`crates/raw/src/vendor/arw6.rs`, `crates/raw/src/llvc.rs`; 12-bit codes exact against a black-box oracle on 8 CC0 files, FF over the full frame, APS-C in the interior (LibRaw's own edge rows differ); output through our own companding curve, measured from CC0 lossless / ARW6 pairs; geometry checked against the camera JPEG, `docs/arw6-compression.md`; the ILCE-7M5 writes the same codec, unverified)), NEF (uncompressed, lossless and lossy compressed 12/14-bit, `crates/raw/src/convert.rs`), RAF (uncompressed, lossless/lossy compressed Bayer and X-Trans; `crates/raw/src/vendor/rafc.rs`, full sensor verification on 13 bodies, `docs/raf-compression.md`), RW2 / Leica RWL / Panasonic RAW in every raw format (compressed 4 and 6, the prefix-coded strips of format 8 from the GH6 on, packed 2/5/7, the 16-bit words of the 2005–2007 bodies; black levels, in-camera aspect crops and mapped-out defect pixels; 178 CC0 files from 118 bodies checked, `crates/raw/src/vendor/rw2.rs`), PEF, ORF (uncompressed; colour-filter layout from the file's Exif `CFAPattern`; 12.8 bit/px 16-byte blocks of ten 12-bit samples + a zero pad byte, E-300 / E-330 / E-500 verified on CC0 files, E-M5 Mark II / PEN-F high-res files decode smooth; compressed ORF is unsupported and uses embedded JPEG previews when available), Kodak DCS520C TIFF (a two-component 12-bit lossless JPEG strip, the two components the even and odd columns; the file's `GrayResponseCurve` table linearises the companded samples to 12 bits, black measured per CFA position, white balance from the `KodakIFD`; `RawFormat::KodakDcs`, `crates/raw/src/convert.rs`, checked on the one CC0 sample against its IFD0 thumbnail), Hasselblad 3FR and FFF (a TIFF without a DNG version tag that describes its CFA IFD, levels, crop and white balance with DNG's tags; `RawFormat::CfaTiff`, read by `dng::decode_as`, RGGB when the file states no `CFAPattern`, checked against the camera preview on the CC0 H4D-40 FFF and CFV 3FR; an FFF has no colour matrix of its own and takes the camera's from the original 3FR header it embeds in tag `0xC51B`; neither carries a JPEG, so their uncompressed 8-bit RGB preview (1217 × 913 in the H4D-40 FFF, 218 × 218 in the CFV 3FR) is the embedded preview, handed on as a baseline TIFF, `crates/raw/src/convert.rs`): uncompressed (X1D, X1D II, X2D, CFV 100C) and Hasselblad's lossless JPEG with scan selection value 8 (every FFF; H3D, H4D and CFV-50c 3FR), `ljpeg::decode_hasselblad`, its rule measured on 14 CC0 files with the ljpeg-explorer tool, Minolta / Konica Minolta MRW (the `\0MRM` block container: `PRD` sensor size, 12-bit packed or 16-bit-word storage and the RGGB / GBRG cell, `WBG` gains in cell order, the `TTW` TIFF for Exif and orientation, black 0 and white from the saturation plateau; `crates/raw/src/convert.rs`, DiMAGE 7, 7Hi, A1, A2, A200 and Dynax / Maxxum 7D checked on CC0 files against their previews), Samsung SRW without compression (NX5, NX10, NX11 and the NX20-generation bodies NX20, NX200, NX210, NX1000 and NX1100 as 12-bit packed samples in either bit order, EX1 and WB2000 as 16-bit words; layout, camera-JPEG framing, levels and white balance from the maker note, `crates/raw/src/convert.rs`; median ΔE vs the camera JPEG 2.2–7.6 on 11 of the 12 files from 10 bodies checked, 10.7 (5.7 registered) on the backlit WB2000 sample). 12-bit NEF black level: maker note `0x003d` is in 14-bit units (D750, D780, D850, D7500, Z 50 checked). Lossy type 2 NEF curves of version `0x44 0x40` (D780, D6, Z 5, Z 6, Z 7, Z 7_2) span a quarter of the sample range, read from the table's own point spacing. Import probes (`probe_info`) of compressed NEFs decode only the first 128 rows, the ones the masked-trailing-column test reads in both the probe and the full decode (the D5100 and D7000 write 8 masked columns at 0 with no maker-note tag for them, compressed and uncompressed alike), instead of the whole Huffman stream: ~3 ms instead of the full decode time per file (386 ms on a 24 MP D750 file), issue #708. CR3 lossless CRX Bayer and version 0x100/0x200 C-RAW decodes to sensor pixels with timed white balance, black/white levels and file crop (EOS R6 Mark III `ColorData` version 66: as-shot white balance and black level from the file, white level from the data, `docs/cr3.md`) (the shot's aspect ratio from the maker note's `AspectInfo`); full sensor samples match the reference on M50/R100/R8/RP, incl. RP 1.6× crop mode (`crates/raw/tests/it/cr3_corpus.rs`, `docs/cr3.md`). EOS R5 Mark II C-RAW and RAW decode too (the QP map's first-symbol literal and 23-zero escape, odd-height Bayer planes): 4 CC0 files pinned, every QP map of 33,665 private C-RAW files decodes exactly, and full-frame images match the camera JPEG. Unsupported coding variants retain metadata and use the embedded JPEG when available; HEVC preview decoding remains unsupported. Missing: CR3 unverified CRX variants, compressed Samsung SRW (NX1, NX30, NX300, NX500, NX2000, NX3000, NX3300, NX mini: preview only with the reason), Nikon High Efficiency NEF (HE / HE★ from the Z 8, Z 9, Z 6III and Z f: compression 34713 with a JPEG XS codestream and no `0x0096` table; no public specification, so preview only with the reason "Nikon High Efficiency NEF", issue #193; Lossless compressed NEFs from the same bodies decode), NEF "lossy after split" (preview only: imported with `preview_only` = the decoder's reason, rendered as a rendered JPEG, flagged by a grid badge and loupe/Edit/Info notices, `previewOnly` in `catalog.query`; Reload clears it once the file decodes, and the notices carry a Reload from Disk button; each flag is stamped with the app version that set it, and a library opened in another version rechecks its preview-only raws in the background, so a raw a newer release decodes is cleared without a manual Reload, issue #662, `library.recheckPreviewOnly`), TIFF-based raws whose raw data sits in a private block (Phase One / Leaf IIQ, Canon EOS-1D / 1Ds and the Kodak DCS Pro / DCS760C TIFFs (compression 65000): IFD0 is only a reduced RGB image next to a much larger declared picture) are recognised from that structure and import as `preview_only` with the reason, instead of opening as a thumbnail-sized ordinary image (`thumbnail_shell` in `crates/raw/src/lib.rs`), Recognised raw formats LightCraft cannot decode—Sigma X3F (container recognised by magic, preview found by a structural JPEG scan), the Canon CRWs the decoder refuses (PowerShot G5, pre-CIFF compacts), Kodak KDC (IFD0 without `ImageWidth`), Leaf MOS and Epson ERF (scan)—open as `preview_only` with the reason and embedded JPEG when available; without a preview, import fails with "without an embedded preview". AVIF decode (HEIC decodes only behind the non-default `heif` feature, which the release packages enable: `craft-heif` from craft-libs, heic-rs for the container and HEVC (bit-exact against libde265 on iPhone tiles) plus our own colour conversion, matching libheif within 1 code value on iPhone-style grids (VUI full range, Display P3 ICC, nclx, 10-bit, irot/imir/clap, gain map/depth ignored); 4:2:0/monochrome only, 4:2:2/4:4:4 Canon/Sony HIF refused; same policy as PhotoCraft), palette (indexed-colour) TIFF (refused by the `tiff` crate); folder discovery and file pickers include Sony SR2 and SRF, with the same extension list used by CLI/MCP: DSC-R1 SR2 decodes from sensor data; DSC-F828 SRF stays preview-only; transparency is flattened onto white, in linear light, where the working image is built (`to_working` in `crates/codecs/src/lib.rs`): renders, previews, exports and contact sheets no longer turn transparent areas black, issue #1212; the Hasselblad Lunar, a Sony NEX-7 under Make HASSELBLAD, decodes as an ARW: a HASSELBLAD file with Sony's raw coding (compression 32767 or tag `0x7010`) goes to the ARW reader, and the body for its `Tag2010` layout comes from the maker note's `SonyModelID`, checked on the CC0 4051 file, issue #1275; an uncompressed MOS, whose IFD0 is the 16-bit mosaic with no Make tag, is recognised by Leaf's data block `0x8606` instead of opening as a greyscale image of its mosaic, issue #1275). Any decode failure of a recognised raw falls back to `preview_only` with the error reason and uses an embedded JPEG when available. Nikon 12-bit small RAW (D810 / D4S): packed Y0/Y1/Cb/Cr rows decode to linear RGB; header probes retain geometry without decoding pixels, and truncated strips are refused. Chroma gains are approximate. | | LR-IMP-PREVIEW-READ | Preview reads the header, not the raw | P0 | ✅ | `crates/raw/src/preview.rs` (`bounded_preview`, `embedded_preview_from_range`, `embedded_preview_covering`), `crates/engine/src/files.rs` (`preview_window`), `docs/raw-preview-reads.md`, `crates/engine/src/files.rs` (`preview_window`, `planned_preview`), `crates/raw/src/sparse.rs` (`preview_plan`), `crates/raw/src/convert.rs` (`decode_reduced`), `crates/codecs/src/lib.rs` (`decode_jpeg_srgb8_fit`) | a grid thumbnail and a loupe preview of an unedited raw show the camera's embedded JPEG, which sits near the start of the file (a 24 MP Fuji RAF keeps its 5.6 MB JPEG in a 56 MB file), so the preview loader reads the header and that JPEG instead of the whole file: 56.5 MB → 5.9 MB and ~10 s → 0.96 s measured on one real RAF over a GVFS/SMB Wi-Fi share (byte-identical preview pixels; `LIGHTCRAFT_PROFILE=1` reports the bytes); the RAF pointer is read from its fixed header fields, a CR3's boxes and a TIFF raw whose preview tag sits past the prefix are read through `lightcraft_raw::sparse::preview_plan`, which names the ranges `embedded_preview` reads and nothing else; a cached render as stand-in, an edited photo and a raw without an embedded JPEG still render; the formats it cannot describe (CRW/MRW/X3F are found by scanning, NEF/ORF/PEF probe from samples) keep the whole-file path, and a lying pointer, a short read or a file that changes underneath us falls back to it rather than losing the preview. An unedited raw's **grid thumbnail is that camera JPEG itself**, so no sensor decode is scheduled behind it (`Session::embedded_thumb_is_final`, `grid::skips_the_real_render`): drawing a 512 px thumbnail used to decode the whole raw — 45 s a photo at 1.2 MB/s, 8.3 GB for a 149-raw folder — and the queue it built delayed the render the user was waiting for. Stand-ins and grid thumbnails decode the smallest embedded JPEG that covers the requested size and is a copy of the largest (aspect ratio within 1 %, same component count), not always the largest, on the whole-file and the plan route alike: an A7R VI's 1616 × 1080 JPEG (0.3 MB) instead of its 9984 × 6656 one (5.6 MB), mid-sized NEF / RW2 JPEGs, and a Canon CR3's 1620 px `PRVW` (or 160 px `THMB`) instead of its 8192 px JPEG track (`cr3_preview_box_list`; EOS R5 C at 1280 px: 168–322 → 31 ms a photo); a plain 8-bit sRGB camera JPEG decodes straight to 8-bit (`decode_jpeg_srgb8_fit`, no float image), and the decoded camera JPEG of an unedited raw is kept in the library's thumbnail cache, so a folder seen before fills from small files (250 R5 C raws: first screen 553 → 294 ms, second visit 610 → 53 ms); a DNG that keeps reduced-resolution copies of its LinearRaw image (Lightroom HDR/panorama merges) develops a thumbnail or preview from the smallest copy that covers it (512 px of a 23836 × 7078 pano: 38 s → 1.1 s) | | LR-IMP-CAMERA-COVERAGE | Camera coverage, verified per model | P0 | 🟡 | `crates/raw/tests/it/corpus.rs`, `crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/evidence.tsv`, `docs/raw/coverage-sweep.tsv`, `xtask/src/main.rs` | a supported container is not the same as every camera that writes it decoding correctly: ~55 CC0 corpus files plus 6 exact-sensor CR3 cases and 4 pinned EOS R5 Mark II files (plus ~60 NEFs checked by hand and 178 Panasonic / Leica RW2, RWL and RAW files from 118 bodies, checked against each file's own JPEG) against the >1,000 models Lightroom lists; per-model differences still surface (e.g. the CR2 colour-filter layout differed by model until it was read from the file's own tag, issue #85, checked on 35 CR2 bodies; CR2 black levels were read from border columns light already reaches, left of `SensorInfo`'s border, so CR2s rendered dark with crushed shadows (EOS 6D: 2591 instead of 2047), now measured from the masked columns only, checked on 8 corpus bodies; pre-2017 Sony ARWs opened green until their scrambled white balance / black level were read, issue #148, checked on 16 ARWs from 15 Sony bodies; their white balance now comes from the encrypted `SR2SubIFD`'s `WB_RGGBLevels`, the gains the camera applied, which 14 bodies (DSLR-A450 … A700, NEX-3/5/C3, SLT-A33/A35/A55, ILCE-6001, UMC-R10C) had no other source for and which the maker-note estimate read before missed by up to 100 % on preset shots, issue #535, checked against ExifTool on 100 decoded ARWs from 87 Sony bodies; the encrypted SR2 black level is now read from its directory entry (the DSLR-A450/A500/A550/A700 read 354–975 instead of 512), checked on 126 ARWs from 97 Sony bodies, and downsized lossless M/S ARWs use their measured black level 1024 instead of 512, checked on 12 files from 4 bodies, issue #535, and on a fifth, the ILCE-7CM2 (issue #697: 0.5.0 rendered its lossless M file with that 512 pedestal, the darkest half of a dusk scene +11 L* and blue, the lamplight white; its darkest 0.1 % per channel sits at 1017/1020/1024, and with 1024 the render is within +3 L* of the camera JPEG; the body's compressed and uncompressed "M-size" files are Bayer at 4736×3132 with black 512, two public ones in the corpus); pre-2017 Sony bodies shot in the camera's 16:9 mode (ILCE-7SM2, DSLR-A580) now get the 16:9 crop of their camera JPEG instead of the whole 3:2 frame with padding columns, issue #535; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked; private Z 8 crop verified; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone); the D7100, whose data holds picture beyond the camera's frame, develops at Lightroom's frame (the camera JPEG's size) in full frame and 1.3x crop, so Lightroom crops line up (#1248).; CR2 white levels came from masked rows holding samples at 16383, so on the EOS 50D, 60D, 450D (Rebel XSi), 500D (Rebel T1i), 550D (Rebel T2i), 1200D (Rebel T5) and 100D (Rebel SL1) clipped highlights sat at 81–98% of the range and were not treated as clipped, now taken from the active area only, issue #1272). Canon CRW verified pixel-exact on 6 bodies (D30, D60, 10D, 300D, G1, G6; 10 CC0 files in the corpus, `crates/raw/tests/it/corpus.rs`, plus 18 maintainer D60 files via the digest-pinned sample test of craft-crw in craft-libs (crates/crw/tests/samples.rs there); `craft-libs crates/crw/clean-room/03-verification.md`). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Pentax PEFs without area tags (KP, KF, K-3 Mark III, K-70, K-1, K-1 Mark II, K-S1, K-S2, 645Z) no longer keep their masked border: black, empty and saturated lines are trimmed against the maker-note BlackPoint, issue #1271, measured on 38 CC0 PEFs from 30 bodies.; Canon PowerShot and EOS M CR2s whose `ColorData` is stored as bytes opened green until the bytes were read as 16-bit words, 25 files from 25 bodies checked). Compressed RAF sensor arrays verified on 13 Fujifilm bodies (`docs/raf-compression.md`). ILCE-7RM6 ARW6 12-bit codes verified on 8 CC0 files (FF and APS-C, both compression modes). Sony ILCE-7CR (61 MP): lossless compressed L and M and compressed ARW2 samples of one scene in the corpus (black level, default crop, as-shot gains, lossless vs compressed mosaic agreement, fitted camera look), and all nine public codings (also uncompressed, small and APS-C crop) decode and fit. Grow the CC0 corpus per model and test each sample decodes with plausible colour. Nikon CropArea and untagged-preview colour-space regression tests; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Canon PowerShot G9, which writes no `ColorData`, takes its as-shot white balance from the WBInfo row (`0x0029`) of the preset ShotInfo names, issue #1273, checked on 1 CC0 file against neutral areas of the camera JPEG (within 0.1 %).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). The Olympus E-10 (no ImageProcessing directory) takes its as-shot gains and its black level (`0x1012` in `0x102c` ValidBits units: 128 at 12 bits) from the main maker note, issue #1273: its render against the camera thumbnail goes from ΔE76 18.5 with a rejected fit to 11.5 with the fit accepted (measured by AlexChambers).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone), and the Nikon D90 likewise on 10 of 550 NEFs (42 filler columns on the right that developed as a pink band; green clips below red and blue).; the Nikon D4, which records no CropArea, gets its image area and white level measured on 148 NEFs against the camera JPEG (optical-black stripes and magenta clipped highlights gone). Public raw.pixls.us coverage sweep (#1327): 30 more models verified on 40 CC0 files, with SHA-256 and FNV-1a sensor hashes pinned (`crates/raw/tests/it/coverage_sweep_corpus.rs`, `docs/raw/coverage-sweep.tsv`; `docs/raw/coverage.py`: 515 → 545 verified rows). Render/reference luminance correlation is 0.6801 to 0.9998; eleven candidates excluded for identity, provenance or missing/mismatched reference images. Nikon D6 / Z 6 / Z 7 uncompressed and Z 8 HE variants remain preview-only. Own-matrix DNG tone differs from the camera JPEG (#1277); sensor verification is not colour calibration. | | LR-IMP-CULL-AT-IMPORT | Culling analysis at import | P2 | 🟡 | `cmd:photo.analyze` | run Assisted Culling on the imported photos (they're selected after an import); not automatic | From 48a5de32766a8ff8905db7ba91867fd98ce2f599 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 08:14:57 +0000 Subject: [PATCH 23/23] test: import PSD before corrupting resources --- crates/engine/src/tests/export.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/export.rs b/crates/engine/src/tests/export.rs index ca20da3489..4c9cc84d60 100644 --- a/crates/engine/src/tests/export.rs +++ b/crates/engine/src/tests/export.rs @@ -1071,6 +1071,13 @@ fn remove_location_refuses_a_psd_with_unreadable_resources() { let path = dir.join("Geo.psd"); let valid_bytes = synthetic_psd_with_metadata(&gps); assert_eq!(lightcraft_meta::extract(&valid_bytes).gps, gps.gps, "the fixture embeds EXIF GPS before corruption"); + std::fs::write(&path, &valid_bytes).unwrap(); + let mut session = Session::new().with_fs(); + session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let id = session.catalog.photos().next().unwrap().id; + + // Import the decodable original first. The malformed resource list below is the file state the + // export safety check must refuse; it is not a fixture the image importer should have to decode. let mut bytes = valid_bytes; let colour_length = usize::try_from(u32::from_be_bytes(bytes[26..30].try_into().unwrap())).unwrap(); let resource_length_at = 30 + colour_length; @@ -1082,9 +1089,6 @@ fn remove_location_refuses_a_psd_with_unreadable_resources() { assert!(lightcraft_meta::extract(&bytes).gps.is_none(), "the malformed trailing resource reproduces the metadata gap"); std::fs::write(&path, bytes).unwrap(); - let mut session = Session::new().with_fs(); - session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); - let id = session.catalog.photos().next().unwrap().id; let err = export_photo(&mut session, id, &ExportOptions::from_json(&json!({"format": "original", "removeLocation": true})), 1).err().unwrap(); assert!(err.contains("can't verify location metadata") && err.contains("malformed PSD/PSB"), "{err}"); let _ = std::fs::remove_dir_all(&dir);