C1: codec delle immagini scritti in casa, SkiaSharp esce (#58) #62
No files matched your search
@@ -4,3 +4,11 @@
|
|||||||
*.nsi text eol=lf
|
*.nsi text eol=lf
|
||||||
# Binari: mai conversioni.
|
# Binari: mai conversioni.
|
||||||
*.ico binary
|
*.ico binary
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.jpeg binary
|
||||||
|
*.gif binary
|
||||||
|
*.bmp binary
|
||||||
|
*.webp binary
|
||||||
|
# L'elenco delle immagini di riferimento si legge uguale su ogni sistema.
|
||||||
|
tests/Febe.Tests/Imaging/Riferimenti/elenco.txt text eol=lf
|
||||||
@@ -2,9 +2,6 @@
|
|||||||
<!-- Niente componenti esterni (specifica §2 regola 13, §3). Per aggiungere qualunque cosa si chiede prima. -->
|
<!-- Niente componenti esterni (specifica §2 regola 13, §3). Per aggiungere qualunque cosa si chiede prima. -->
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.12" />
|
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.12" />
|
||||||
<!-- Escono con la tappa C1 del traguardo 0.3.0 (specifica §15): li sostituisce codice di Febe. -->
|
|
||||||
<PackageVersion Include="SkiaSharp" Version="4.153.1" />
|
|
||||||
<PackageVersion Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="4.153.1" />
|
|
||||||
<PackageVersion Include="Microsoft.Web.WebView2" Version="1.0.4258.31" />
|
<PackageVersion Include="Microsoft.Web.WebView2" Version="1.0.4258.31" />
|
||||||
<PackageVersion Include="MSTest" Version="4.5.1" />
|
<PackageVersion Include="MSTest" Version="4.5.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -459,4 +459,28 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
|||||||
| 2026-11-18 | Seconda revisione di S4b. (1) La scelta «sessione.copia-incompleta» si legge prima dell'ultimo controllo che la pagina sia ancora di Alberto (`mayKeep`), non dopo; se non si legge (database occupato o in errore) vale la predefinita «Sostituisci comunque» e il registro scrive solo il tipo d'errore. (2) Ogni volta che lo stesso uso del browser viene lasciato senza «Ho finito» (finestra chiusa, fine della guida) dimentica la copia fatta a un abbandono precedente prima di provare la sua: un «Ho finito» tardivo segue l'ultimo abbandono | (1) Regola 7: fra l'ultimo sguardo alla pagina e la scrittura non deve passare nessuna attesa; un errore dell'impostazione faceva fallire «Ho finito» senza rilasciare il permesso di guida. (2) Dopo una copia riuscita e un secondo abbandono rifiutato (pagina di accesso, forse un altro account) il messaggio diceva «era già stata copiata… Non serve rifare l'accesso» |
|
| 2026-11-18 | Seconda revisione di S4b. (1) La scelta «sessione.copia-incompleta» si legge prima dell'ultimo controllo che la pagina sia ancora di Alberto (`mayKeep`), non dopo; se non si legge (database occupato o in errore) vale la predefinita «Sostituisci comunque» e il registro scrive solo il tipo d'errore. (2) Ogni volta che lo stesso uso del browser viene lasciato senza «Ho finito» (finestra chiusa, fine della guida) dimentica la copia fatta a un abbandono precedente prima di provare la sua: un «Ho finito» tardivo segue l'ultimo abbandono | (1) Regola 7: fra l'ultimo sguardo alla pagina e la scrittura non deve passare nessuna attesa; un errore dell'impostazione faceva fallire «Ho finito» senza rilasciare il permesso di guida. (2) Dopo una copia riuscita e un secondo abbandono rifiutato (pagina di accesso, forse un altro account) il messaggio diceva «era già stata copiata… Non serve rifare l'accesso» |
|
||||||
| 2026-11-18 | Terza revisione di S4b. (1) La fine della guida da sola, dopo la copia, guarda di nuovo nello stesso passo in cui rilascia il permesso (sotto lo stesso lucchetto): se nel frattempo è tornata la vista remota o la finestra, o è arrivato un nuovo «Accedi» / «Usa il browser», il permesso resta e il controllo continua (`ReleaseIdleLease`). (2) Ogni «Ho finito» che prova davvero a copiare, o che chiude lui il permesso, dimentica la copia fatta a un abbandono precedente; anche la chiusura della finestra che rinuncia (browser fermo, un altro comando ancora in corso) la dimentica. (3) Se il tempo della chiusura della finestra finisce mentre la ricerca dei profili tiene la pagina, il registro dice «la pagina era occupata dalla ricerca dei profili», non «il browser non ha risposto in tempo». (4) La riga di avvio del motore segue `IsReadyToCollect`, con una terza frase per «aspetta la copia della sessione». (5) Il riquadro «Se una copia nuova è incompleta» non mostra né lascia scegliere nulla finché il server non dice la scelta salvata; una risposta tardiva non cambia una scelta già fatta; una scelta non salvata torna alla precedente; se la scelta non si legge, una riga lo dice. (6) Singolare italiano nei messaggi e nel registro («manca 1 valore che serve», «1 di questi serve»). (7) La guida dice che in Docker copia solo «Ho finito»: lasciare la pagina vale «Annulla» e non copia; la copia alla fine della guida in Docker resta solo una riserva per una pagina sparita senza avvisare. Corregge la frase «In Docker c'è solo la fine del permesso» della riga sulla copia alla chiusura della finestra | (1) Dopo una copia lunga (fino a 15 s di turno della pagina più il browser e il database) il permesso finiva anche se Alberto era tornato al browser, e alla chiusura successiva il motore riprendeva subito, senza attesa né copia. (2) Dopo un «Ho finito» rifiutato, un secondo «Ho finito» diceva «era già stata copiata… Non serve rifare l'accesso» di una copia forse di un altro accesso. (3) Il registro dava la colpa al browser. (4) Il registro diceva «collegato» mentre il monitor diceva «Serve «Ho finito»». (5) La pagina poteva mostrare una scelta diversa da quella che la copia seguente usa. (7) In Docker la pagina, lasciandola, manda «Annulla» (`pageLeft`) e la vista remota tiene il suo permesso finché è aperta: la copia alla fine della guida non scatta quasi mai. Se Alberto vuole che in Docker anche lasciare la pagina copi, va deciso (domanda aperta) |
|
| 2026-11-18 | Terza revisione di S4b. (1) La fine della guida da sola, dopo la copia, guarda di nuovo nello stesso passo in cui rilascia il permesso (sotto lo stesso lucchetto): se nel frattempo è tornata la vista remota o la finestra, o è arrivato un nuovo «Accedi» / «Usa il browser», il permesso resta e il controllo continua (`ReleaseIdleLease`). (2) Ogni «Ho finito» che prova davvero a copiare, o che chiude lui il permesso, dimentica la copia fatta a un abbandono precedente; anche la chiusura della finestra che rinuncia (browser fermo, un altro comando ancora in corso) la dimentica. (3) Se il tempo della chiusura della finestra finisce mentre la ricerca dei profili tiene la pagina, il registro dice «la pagina era occupata dalla ricerca dei profili», non «il browser non ha risposto in tempo». (4) La riga di avvio del motore segue `IsReadyToCollect`, con una terza frase per «aspetta la copia della sessione». (5) Il riquadro «Se una copia nuova è incompleta» non mostra né lascia scegliere nulla finché il server non dice la scelta salvata; una risposta tardiva non cambia una scelta già fatta; una scelta non salvata torna alla precedente; se la scelta non si legge, una riga lo dice. (6) Singolare italiano nei messaggi e nel registro («manca 1 valore che serve», «1 di questi serve»). (7) La guida dice che in Docker copia solo «Ho finito»: lasciare la pagina vale «Annulla» e non copia; la copia alla fine della guida in Docker resta solo una riserva per una pagina sparita senza avvisare. Corregge la frase «In Docker c'è solo la fine del permesso» della riga sulla copia alla chiusura della finestra | (1) Dopo una copia lunga (fino a 15 s di turno della pagina più il browser e il database) il permesso finiva anche se Alberto era tornato al browser, e alla chiusura successiva il motore riprendeva subito, senza attesa né copia. (2) Dopo un «Ho finito» rifiutato, un secondo «Ho finito» diceva «era già stata copiata… Non serve rifare l'accesso» di una copia forse di un altro accesso. (3) Il registro dava la colpa al browser. (4) Il registro diceva «collegato» mentre il monitor diceva «Serve «Ho finito»». (5) La pagina poteva mostrare una scelta diversa da quella che la copia seguente usa. (7) In Docker la pagina, lasciandola, manda «Annulla» (`pageLeft`) e la vista remota tiene il suo permesso finché è aperta: la copia alla fine della guida non scatta quasi mai. Se Alberto vuole che in Docker anche lasciare la pagina copi, va deciso (domanda aperta) |
|
||||||
| 2026-11-25 | **In Docker lasciare la pagina del browser copia la sessione: costruito** (risposta 1 di Alberto del 25 novembre 2026; ramo `funzione/sessione-s4b`). `cancel` con `pageLeft` in Docker va a `IConnectionService.LeavePageAsync` (predefinita: «Annulla», per i servizi senza sessione salvata come la dimostrazione) e non più a `CancelAsync`; la vista remota chiusa dalla sua pagina (né sostituita da un'altra scheda, né chiusa da Febe perché si ferma o perché la vista non è partita, né con il browser fermo) lo dice alla connessione (`BrowserRemoteViewHost`, `viewClosed` → `RemoteViewClosed`). Il controllo del permesso di guida, se dopo l'ultimo dei due segni passano `PageLeaveGrace` (5 s) senza viste aperte né `begin`, fa la copia di `CopyOnLetGoAsync` («Pagina del browser lasciata» nel registro, con le garanzie della chiusura della finestra), poi finisce il permesso e il motore rimette il browser a riposo; un `begin` (la pagina ricaricata) dimentica il segno. Il solo pulsante «Annulla» non copia. Windows non cambia (`pageLeft` → `ReleaseAsync`). Chiude la domanda aperta della riga «Terza revisione di S4b» (punto 7) e supera «la guida dice che in Docker copia solo «Ho finito»» | Prima in Docker lasciare la pagina valeva «Annulla» e la sessione non si copiava; una scheda chiusa senza `cancel` teneva il permesso fino ai 2 minuti di `DrivingGrace`. Il riposo lo fa il motore dopo la fine del permesso, come per la fine della guida: rimettere a riposo prima, sotto il permesso, avrebbe lasciato la pagina vuota a una vista riaperta proprio in quel momento |
|
| 2026-11-25 | **In Docker lasciare la pagina del browser copia la sessione: costruito** (risposta 1 di Alberto del 25 novembre 2026; ramo `funzione/sessione-s4b`). `cancel` con `pageLeft` in Docker va a `IConnectionService.LeavePageAsync` (predefinita: «Annulla», per i servizi senza sessione salvata come la dimostrazione) e non più a `CancelAsync`; la vista remota chiusa dalla sua pagina (né sostituita da un'altra scheda, né chiusa da Febe perché si ferma o perché la vista non è partita, né con il browser fermo) lo dice alla connessione (`BrowserRemoteViewHost`, `viewClosed` → `RemoteViewClosed`). Il controllo del permesso di guida, se dopo l'ultimo dei due segni passano `PageLeaveGrace` (5 s) senza viste aperte né `begin`, fa la copia di `CopyOnLetGoAsync` («Pagina del browser lasciata» nel registro, con le garanzie della chiusura della finestra), poi finisce il permesso e il motore rimette il browser a riposo; un `begin` (la pagina ricaricata) dimentica il segno. Il solo pulsante «Annulla» non copia. Windows non cambia (`pageLeft` → `ReleaseAsync`). Chiude la domanda aperta della riga «Terza revisione di S4b» (punto 7) e supera «la guida dice che in Docker copia solo «Ho finito»» | Prima in Docker lasciare la pagina valeva «Annulla» e la sessione non si copiava; una scheda chiusa senza `cancel` teneva il permesso fino ai 2 minuti di `DrivingGrace`. Il riposo lo fa il motore dopo la fine del permesso, come per la fine della guida: rimettere a riposo prima, sotto il permesso, avrebbe lasciato la pagina vuota a una vista riaperta proprio in quel momento |
|
||||||
|
| 2026-11-18 | Insieme fisso di immagini di riferimento per i codec di casa in `tests/Febe.Tests/Imaging/Riferimenti` (57 casi, circa 2,2 MB, descritti in `LEGGIMI.md`): per ogni caso un file d'ingresso (PNG, GIF e BMP costruiti a mano dalle specifiche; PNG, JPEG base e WebP codificati da SkiaSharp; JPEG con un `APP1` EXIF di orientamento inserito a mano) e `.atteso.png`, la lettura di SkiaSharp 4.153.1 in RGBA a 8 bit non premoltiplicata, raddrizzata. Generato una volta sola, con il permesso di Alberto, da un programma usa e getta fuori dal repository; contenuto solo sintetico. Le immagini attese sono PNG RGBA a 8 bit senza interlacciamento, filtro 0, un solo `IDAT`, scritti a mano e non dal codificatore di SkiaSharp, così le legge il lettore PNG di casa (passo 2 di C1); fino ad allora `ReferenceSetTests` controlla solo la struttura (firme, misure, CRC dei blocchi, nessun file in più o in meno). JPEG progressivo, intervalli di ripristino e CMYK/Adobe non hanno riferimento: li proveranno codificatori di prova nostri dalla T.81 (allegati F e G) con controlli sui coefficienti. Estensioni delle immagini `binary` in `.gitattributes`, `elenco.txt` con `eol=lf` | SkiaSharp esce da Febe (C1): serve un termine di confronto prima di toglierlo, e dopo non si potrà più generarlo. Un riferimento che solo SkiaSharp sapesse leggere sarebbe inutile proprio quando serve |
|
||||||
|
| 2026-11-18 | Base dei codec d'immagine di casa in `src/Febe.Core/Codecs/Images` (spazio dei nomi `Febe.Core.Codecs.Images`, accanto a `Codecs/Containers` del ramo `funzione/decoder-h264`): `RgbaImage` (RGBA a 8 bit non premoltiplicata, array suo o preso dal pool e reso con `Dispose`), `ImageLimits` (predefiniti 65535 pixel per lato, 100 milioni di pixel come `ImageDecoding.MaxDecodedPixels`, 512 MiB di memoria di lavoro, 16 MiB di metadati decompressi), `ImageDecodeException` con `ImageLimitException` e `ImageFormatNotSupportedException`, `ImageFormatSniffer`, la facciata `ImageDecoder`; lettore e scrittore PNG, lettori GIF e BMP dalle specifiche, CRC-32 e LZW scritti in casa, zlib di `System.IO.Compression`. Scelte di lettura: i campioni a 16 bit tengono il byte alto e le maschere BMP sotto gli 8 bit si scalano con arrotondamento (così i 37 riferimenti PNG, GIF e BMP coincidono byte per byte); nessuna gestione del colore (profilo ICC, gamma); un blocco PNG ausiliario con il CRC sbagliato si salta, uno critico ferma la lettura; un PNG senza `IEND` dopo dati completi si accetta, uno tagliato prima no; un GIF tagliato o con dati LZW rotti dà ciò che si è letto, il resto trasparente; del GIF solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo, più il numero dei fotogrammi; nel BMP l'alfa viene solo da una maschera alfa di `BI_BITFIELDS`/`BI_ALPHABITFIELDS`, i pixel saltati da RLE restano trasparenti, `BI_PNG` passa al lettore PNG, `BI_JPEG` e 64 bit non si leggono. `Identify` legge misura, fotogrammi e metadati senza applicare i limiti di misura; `Decode` li applica prima di allocare. Lo scrittore PNG scrive RGB o RGBA a 8 bit (RGB in automatico se tutto è opaco), per ogni riga il filtro con la minima somma dei valori assoluti (specifica PNG §12.8), `IDAT` da 64 KiB e, a richiesta, `eXIf`, `iCCP` e l'XMP in un `iTXt` | C1: SkiaSharp esce da Febe e niente componenti esterni (decisione di Alberto del 18 novembre 2026). Lettori tolleranti dove lo sono i browser (GIF, metadati), severi dove un'immagine letta a metà passerebbe per buona (PNG, BMP); limiti controllati prima di ogni allocazione, perché pochi byte di un file possono chiedere gigabyte |
|
||||||
|
| 2026-11-18 | Lettore e scrittore JPEG di casa (`JpegDecoder`, `JpegEncoder`), scritti dalla T.81: il lettore fa sequenziale di base ed esteso, progressivo, senza perdita, con Huffman e con codifica aritmetica, a 8 e 12 bit (senza perdita da 2 a 16), qualunque campionamento, ripristino, DNL; IDCT esatta in virgola mobile e crominanza con il filtro triangolare dove il rapporto è 2; colori secondo JFIF, Adobe APP14 (CMYK e YCCK invertiti come li scrive Adobe) e identificatori `R`, `G`, `B`; tabelle dell'allegato K quando manca `DHT` (Motion JPEG); dati troncati dentro una scansione = file danneggiato, EOI mancante e byte dopo EOI accettati; gerarchici e JPEG a 2 componenti rifiutati come formato non letto. L'orientamento EXIF va in `ImageMetadata.Orientation` e non si applica ai pixel. Lo scrittore fa solo il sequenziale di base (qualità 1–100 sulle tabelle dell'allegato K, 4:2:0 e 4:4:4, grigio, ripristino) con EXIF, ICC a pezzi, XMP e commenti. Progressivo, aritmetico, 12 bit e senza perdita si provano con un codificatore di prova (`tests/Febe.Tests/Imaging/JpegTestEncoder.cs`) confrontando i coefficienti con la codifica di base; contro SkiaSharp la tolleranza è PSNR ≥ 40 dB per canale e ≤ 0,1% di pixel con scarto oltre 16 | Tappa C1, passo 3: niente componenti esterni (decisione del 18 novembre 2026). Due lettori JPEG corretti differiscono per gli arrotondamenti, quindi contro il riferimento serve una soglia; il nostro sta fra 59 e 67 dB. La codifica aritmetica è verificata solo con il nostro codificatore e le tabelle della specifica: nessun file di riferimento esterno |
|
||||||
|
| 2026-11-18 | Lettore e scrittore WebP di casa (`WebPDecoder`, `WebPEncoder`), scritti dalla RFC 9649 e, per VP8, dalla RFC 6386: il lettore fa VP8 con perdita (decodificatore booleano, segmenti, modi intra, DCT e WHT, filtro semplice e normale, più partizioni), VP8L senza perdita (codici prefissi, cache dei colori, le quattro trasformate), `ALPH` grezzo e compresso con ogni filtro, VP8X con ICCP, EXIF (tolto il prefisso «Exif» se c'è) e XMP; di un'animazione solo il primo fotogramma, sulla tela trasparente senza il colore di sfondo di `ANIM`, con lo scostamento di `ANMF` e la fusione della specifica, più il numero dei fotogrammi. Scelte di lettura: YUV→RGB BT.601 a intervallo ridotto in virgola fissa a 16 bit e crominanza ricampionata con i pesi 9/3/3/1 (così i quattro riferimenti con perdita stanno fra 68,7 e 74,4 dB, scarto massimo 1, alfa esatta; i quattro senza perdita coincidono); severo dove un'immagine letta a metà passerebbe per buona: dimensione RIFF oltre il file, blocco oltre la fine, tela diversa dall'immagine, trasformata ripetuta, codice prefisso incompleto, distanza prima dell'inizio, dati VP8 finiti prima dell'ultimo macroblocco (si tollera un solo byte di riempimento a zero, perché il codificatore booleano chiude con byte che il lettore può non usare), `ALPH` corto o con bit riservati; i modi 14 e 15 del predittore VP8L, non definiti, valgono come 0. Lo scrittore fa solo VP8L senza perdita (tavolozza fino a 256 colori, sottrazione del verde, predittore per blocchi, trasformata del colore, LZ77 con catene di hash, cache dei colori scelta stimando l'entropia, codici di Huffman limitati a 15 bit) e il formato esteso VP8X solo se ci sono metadati, nell'ordine VP8X, ICCP, VP8L, EXIF, XMP | Tappa C1, passo 4: niente componenti esterni (decisione del 18 novembre 2026). Uno scrittore con perdita servirebbe solo a file più piccoli, e la libreria conserva gli originali: senza perdita i 57 riferimenti stanno all'88% del PNG di casa, e sul riferimento grande 70952 byte contro i 64406 di libwebp |
|
||||||
|
| 2026-11-18 | SkiaSharp e SkiaSharp.NativeAssets.Linux.NoDependencies tolti da `Directory.Packages.props` e da ogni progetto (C1, passo 5): miniature, impronte, anteprime dell'importazione, icona, immagini dimostrative, riquadro neutro dei video, foto del sito di prova e aiuti delle prove usano i codec di casa e `Febe.Core.Drawing` | Regola «niente componenti esterni» del 18 novembre 2026; l'elenco chiuso di §3 si riduce a Microsoft.Data.Sqlite, Microsoft.Web.WebView2 e MSTest. Il Dockerfile non aveva librerie native solo per Skia (il pacchetto NoDependencies non ne chiedeva): restano quelle di .NET e di Chromium |
|
||||||
|
| 2026-11-18 | Ridimensionamento di casa (`ImageResampler`): filtro separabile Lanczos3 allargato del rapporto di riduzione, o media per area esatta; alfa premoltiplicata quando l'immagine non è opaca (il colore si divide per l'alfa filtrata prima di limitarla), luce lineare facoltativa con tabelle sRGB; righe filtrate in orizzontale tenute in un anello, `Vector4`, nessuna allocazione per pixel | Qualità almeno pari al filtro di Skia senza dipendere da lui; la luce lineare resta spenta per le miniature, come prima |
|
||||||
|
| 2026-11-18 | Il lettore JPEG decodifica anche ridotto a 1/2, 1/4, 1/8 (`JpegDecoder.DecodeReduced`, `ImageDecoder.DecodeAtLeast`): ogni blocco trasformato intero e mediato, a 1/8 il solo coefficiente DC. Le miniature chiedono almeno il doppio del lato lungo (960 per 480), le impronte almeno 256 | Una foto da 12 MP si legge a un quarto dei pixel. Il doppio e non il lato esatto: a 1/8 le medie dei blocchi 8 × 8 si vedevano, quasi 1:1, sotto i 30 dB contro la lettura intera |
|
||||||
|
| 2026-11-18 | Disegnatore di casa `Febe.Core.Drawing` (`Canvas`, `PathBuilder`, `SolidBrush`, `LinearGradientBrush`, `Matrix2D`): rasterizzatore ad area con segno, regola non-zero, curve spezzate entro 0,01 pixel, riempimenti, tratti con estremi tondi, gradienti lineari, cerchi sfumati con erfc, fusione «sopra» in alfa non premoltiplicata. Nessun testo e nessun carattere | Serve solo a icona, immagini dimostrative, riquadro dei video, foto del sito di prova e prove: nessuno di questi scrive testo, quindi niente caratteri di terzi |
|
||||||
|
| 2026-11-18 | Orientamento EXIF applicato in un punto solo (`ImageOrientation.Apply`, da `ImageDecoding.DecodeUpright`) per miniature, impronte, anteprime e dimensioni mostrate; `ImageConverter` cambia formato (JPEG, PNG, WebP) portando EXIF, ICC e XMP, i testi in blocchi PNG o commenti JPEG, e tiene l'etichetta d'orientamento senza ruotare i pixel; ciò che non entra nel formato d'arrivo lo elenca in `NotCarried` | Per le esportazioni (#58): stessa foto, altra estensione. Ruotare i pixel e insieme tenere l'etichetta la ruoterebbe due volte |
|
||||||
|
| 2026-11-18 | Impronte percettive già salvate: restano confrontabili, nessun ricalcolo. Misurato prima di togliere Skia su 393 campioni (scene a 7 misure fino a 4000×3000 e 3024×4032 in JPEG q92 e q70, PNG, WebP q80, più i 57 file di riferimento): 390 impronte identiche, 3 a distanza 2, soglia dei doppioni 6 | Stesso algoritmo (luma su bianco con pesi BT.601, media per area a 32×32 in double, DCT 8×8, mediana); cambia solo il lettore |
|
||||||
|
| 2026-11-18 | Un PNG o un JPEG troncato ora non dà miniatura né impronta (il file si importa lo stesso, con SHA-256, nome e date) | SkiaSharp teneva l'immagine a metà («IncompleteInput»); i lettori di casa la rifiutano, come per gli altri file rovinati, e una miniatura a metà non è la foto |
|
||||||
|
| 2026-11-18 | `Febe.ico` ridisegnata dal disegnatore di casa e rigenerata; `tools/Febe.SitoDiProva` ora fa riferimento a `Febe.Core` per disegnare e codificare le foto finte | Le stesse forme del marchio (appendice C), con un rasterizzatore diverso: la prova dell'icona le confronta con il disegno. Il sito di prova non aveva altro modo di fare JPEG senza Skia |
|
||||||
|
| 2026-11-18 | Tabelle di Huffman JPEG: il controllo «i codici non stanno nella loro lunghezza» si fa per ogni lunghezza prima di scrivere le voci (`code + count <= 1 << length`) | Fatto dopo, una tabella con troppi codici corti (per esempio tre di lunghezza 1) scriveva oltre la tabella di ricerca e dava `ArgumentOutOfRangeException` invece di `ImageDecodeException`: un JPEG rovinato faceva fallire importazione e ricostruzione di quel file invece di lasciarlo senza miniatura (revisione di C1) |
|
||||||
|
| 2026-11-18 | Scansioni JPEG di Huffman (sequenziali, progressive, senza perdita): il troncamento si controlla a ogni riga di MCU, non solo ai marcatori di ripristino e alla fine | Oltre la fine il lettore dà bit zero, che sono codici validi delle tabelle dell'allegato K: un file tagliato dopo le intestazioni che dichiara 8192×8192 veniva decodificato fino all'ultimo MCU (6,7 s in Debug) per poi fallire comunque; ora si ferma alla prima riga (circa 0,1 s, quasi tutto per riservare i piani). Il risultato non cambia: i bit di riempimento usati restano usati fino al ripristino successivo |
|
||||||
|
| 2026-11-18 | IDCT ridotta JPEG a 1/2 e 1/4 calcolata direttamente dai coefficienti (`JpegDct.InverseReduced`): la media di due punti vicini dell'inversa a 8 punti è un'inversa a 4 punti dei coefficienti ripiegati (Yk = Xk cos(kπ/16) − X(8−k) sin(kπ/16), X4 sparisce), e a 1/4 restano X0, X1, X3, X5, X7 | Prima ogni blocco era trasformato intero e poi mediato: il decodificare ridotto risparmiava memoria ma non lavoro. Stesso risultato entro un livello (prova contro la definizione di T.81 in doppia precisione). Misurato in Release su questa macchina, il migliore di 5, scena 4000×3000 JPEG q90: miniatura da 126 a 59 ms, decodifica ad almeno 960 pixel da 114 a 45 ms; impronta (1/8, solo DC) invariata, 27-28 ms |
|
||||||
|
| 2026-11-18 | VP8: con `loop_filter_level` del fotogramma a 0 il filtro di blocco è spento per tutto il fotogramma, qualunque cosa dicano segmenti e differenze | Così fanno libvpx, libwebp e il decodificatore di riferimento di RFC 6386; prima un WebP con segmenti a forza assoluta o differenze positive veniva filtrato e usciva diverso |
|
||||||
|
| 2026-11-18 | VP8L: si costruiscono solo i gruppi di codici prefisso che l'immagine dei meta codici nomina, rinumerati in fila; i codici degli altri si leggono e si controllano (`Vp8LHuffman.IsValid`) senza costruire tabelle | Un solo pixel di valore 65535 chiedeva 65.536 gruppi: un file di circa 160 KB faceva costruire circa 335 MB di tabelle. Come libwebp |
|
||||||
|
| 2026-11-18 | BMP con intestazione OS/2 1.x (12 byte): altezza letta senza segno, immagine sempre dal basso | `bcHeight` è una WORD senza segno: letta con segno, le altezze da 32768 a 65535 diventavano negative, cioè capovolte e della misura sbagliata |
|
||||||
|
| 2026-11-18 | Array di lavoro dei codec (`ImageBuffers`): dal pool condiviso fino a 16 MiB, array normali sopra (immagini decodificate, piani e coefficienti JPEG, piani VP8, ARGB VP8L, alfa WebP, indici GIF, tabelle dello scrittore VP8L) | Il pool condiviso arrotonda alla potenza di due e tiene gli array fino a 1 GiB dopo la restituzione finché non passa una raccolta completa: un'immagine di 100 megapixel lasciava 512 MiB per ogni decodifica parallela (nella prova della revisione, quattro decodifiche parallele lasciavano 2 GiB tenuti per almeno 15 s; non rifatta qui). Sopra la soglia il raccoglitore li libera subito |
|
||||||
|
| 2026-11-18 | `ImageConverter`: il profilo ICC si copia solo se descrive dati RGB (byte 16-19 «RGB »); un profilo CMYK, in grigi o illeggibile si lascia e lo si dice in `NotCarried`. Un sorgente con più di 8 bit per campione (`ImageInfo.BitsPerSample`: PNG a 16 bit, JPEG a 12 bit o senza perdita, BMP con maschere larghe) dà `Lossy` vero e una riga in `NotCarried`; i blocchi di colore PNG gAMA, cHRM e sRGB (`ImageMetadata.ColorChunks`) non si scrivono e lo si dice | I pixel scritti sono sempre RGB a 8 bit: un profilo CMYK o GRAY su pixel RGB fa sbagliare i colori ai programmi che li gestiscono e in un PNG viola la regola di iCCP. La decisione sulle esportazioni chiede di copiare tutto il possibile e di avvisare di ogni perdita |
|
||||||
|
| 2026-11-18 | Impronta percettiva e misure di una foto da una sola lettura e una sola decodifica (`PerceptualHash.ComputeWithSize`, usata da importazione, ricostruzione, copia dell'importazione e analisi); `ImageDecoding.ReadSize(Stream)` legge prima 256 KiB per JPEG, GIF e BMP e il resto solo se le intestazioni non ci stanno; PNG e WebP sempre interi | Senza SkiaSharp `ReadSize` leggeva tutto il file solo per le misure, subito dopo l'impronta che lo leggeva di nuovo: ogni foto entrava in memoria due volte, e i file oltre 64 MiB dell'analisi («troppo grandi da tenere in memoria») due volte interi. Se la foto non si decodifica le misure vengono ancora dalle intestazioni, come prima |
|
||||||
|
| 2026-11-18 | Correzione della riga sulle immagini di riferimento: l'insieme è di 116 file per 2.003.752 byte (circa 2,0 MB), non «circa 2,2 MB» | Somma di `git ls-tree -l` sul ramo `funzione/codec-immagini`; la riga resta com'era perché le righe si aggiungono soltanto |
|
||||||
|
| 2026-11-18 | `Febe.exe` pubblicato senza SkiaSharp (`dotnet publish` come `installer/costruisci.sh`, un file solo e compresso): 85.583.840 byte, circa 86 MB come prima | Misurato di nuovo per `docs/windows.md`; la libreria nativa di Skia, compressa nel file solo, pesava poco |
|
||||||
|
| 2026-11-25 | **«File danneggiato o incompleto» nel visualizzatore** (risposta 3 di Alberto del 25 novembre; §4.6, §8.4): `MediaDto` ha `damaged`, vero per una foto sul disco senza miniatura che i codec di casa riconoscono ma non riescono a decodificare (`DamagedImage` in `Febe.Core.Library`: un errore di decodifica che non sia «formato non letto» né «troppo grande»). Il visualizzatore mostra «File danneggiato o incompleto» al posto dell'immagine, con le azioni sul file che restano; il mosaico ha già la tessera neutra (nessuna miniatura). Il controllo si fa quando il visualizzatore apre l'elemento, solo per le sue foto senza miniatura, decodificando un JPEG alla riduzione più piccola; nulla nel database. HEIC, i formati sconosciuti e le immagini oltre i limiti non sono «danneggiati». Il file si legge soltanto (§2 regola 12) | Il ramo dei codec rifiutava già le immagini troncate (niente miniatura, niente impronta, file tenuto con il suo SHA-256), ma il visualizzatore mostrava il file a metà come lo disegna il browser. Calcolarlo al volo evita una colonna e una migrazione e vale anche per le librerie già scaricate; con 200.000 elementi non pesa, perché riguarda solo le poche foto senza miniatura e solo quando si aprono. Restano da fare la revisione e il resoconto dell'importazione (§9.3) e l'anteprima della Dashboard (D1) |
|
||||||
| 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana |
|
| 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana |
|
||||||
@@ -11,8 +11,11 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b
|
|||||||
|
|
||||||
- Debian stabile ridotta (`debian:trixie-slim`). Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona.
|
- Debian stabile ridotta (`debian:trixie-slim`). Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona.
|
||||||
- Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET.
|
- Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET.
|
||||||
- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati, fino alla tappa C3 del traguardo 0.3.0: regola 13), ICU, caratteri di sistema con le emoji
|
- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati, fino alla tappa C3 del traguardo
|
||||||
(`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata.
|
0.3.0: regola 13), ICU, caratteri di sistema con le emoji (`fonts-noto-color-emoji`, `fonts-liberation`,
|
||||||
|
`fonts-dejavu-core`, per Chromium), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata.
|
||||||
|
- Nessuna libreria per le immagini: miniature, impronte e disegni li fanno i codec di Febe scritti in C#
|
||||||
|
(`src/Febe.Core/Codecs/Images`, `src/Febe.Core/Drawing`).
|
||||||
- `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per
|
- `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per
|
||||||
scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium.
|
scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium.
|
||||||
- Un file di criteri di Chromium (`/etc/chromium/policies/managed/febe.json`) che spegne il salvataggio delle password e
|
- Un file di criteri di Chromium (`/etc/chromium/policies/managed/febe.json`) che spegne il salvataggio delle password e
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti):
|
|||||||
| File «da scaricare» che non arrivano | Gli scaricamenti hanno un loro tetto giornaliero di dati; durante un fermo continuano solo quelli già in coda. Un indirizzo scaduto torna «da scaricare» e si recupera rileggendo il post; per le storie scadute non c'è recupero |
|
| File «da scaricare» che non arrivano | Gli scaricamenti hanno un loro tetto giornaliero di dati; durante un fermo continuano solo quelli già in coda. Un indirizzo scaduto torna «da scaricare» e si recupera rileggendo il post; per le storie scadute non c'è recupero |
|
||||||
| Elementi «falliti» | Dopo cinque tentativi non riusciti un file resta «fallito»; anche una storia scaduta prima dello scaricamento finisce così |
|
| Elementi «falliti» | Dopo cinque tentativi non riusciti un file resta «fallito»; anche una storia scaduta prima dello scaricamento finisce così |
|
||||||
| Nel visualizzatore: «Il file non è sul disco» | Il file è stato spostato o cancellato fuori da Febe. Rimettilo dov'era o elimina l'elemento |
|
| Nel visualizzatore: «Il file non è sul disco» | Il file è stato spostato o cancellato fuori da Febe. Rimettilo dov'era o elimina l'elemento |
|
||||||
|
| Nel visualizzatore: «File danneggiato o incompleto», nel mosaico una tessera neutra | La foto è troncata o rovinata (uno scaricamento o una copia interrotti): Febe non la mostra a metà e non ne calcola l'impronta, quindi non la propone mai come doppione. Il file resta in libreria così com'è: Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. Se non ti serve, elimina l'elemento |
|
||||||
| «N doppioni da decidere» | Foto che sembrano la stessa immagine salvata due volte: decidi tu in «Doppioni da decidere» (vedi [Libreria](Libreria)) |
|
| «N doppioni da decidere» | Foto che sembrano la stessa immagine salvata due volte: decidi tu in «Doppioni da decidere» (vedi [Libreria](Libreria)) |
|
||||||
| Un elemento eliminato torna | Hai usato «Eliminalo e lascia che torni»: elimina di nuovo con «Elimina dalla libreria» |
|
| Un elemento eliminato torna | Hai usato «Eliminalo e lascia che torni»: elimina di nuovo con «Elimina dalla libreria» |
|
||||||
| Il CSV si apre male in Excel | Aprilo con doppio clic (non con «Importa testo» impostando un altro separatore): è fatto per Excel in italiano, con `;` e UTF-8 con BOM |
|
| Il CSV si apre male in Excel | Aprilo con doppio clic (non con «Importa testo» impostando un altro separatore): è fatto per Excel in italiano, con `;` e UTF-8 con BOM |
|
||||||
|
|||||||
@@ -14,7 +14,9 @@ framework né fase di build. La specifica è `docs/SPECIFICA.md`; le scelte pres
|
|||||||
specifiche pubbliche. Ammessi solo .NET, Microsoft.Data.Sqlite, il browser (Microsoft.Web.WebView2 su Windows) e
|
specifiche pubbliche. Ammessi solo .NET, Microsoft.Data.Sqlite, il browser (Microsoft.Web.WebView2 su Windows) e
|
||||||
MSTest (`Directory.Packages.props`); nella sola CI gitleaks e Trivy; nell'immagine Docker solo Chromium, i pacchetti
|
MSTest (`Directory.Packages.props`); nella sola CI gitleaks e Trivy; nell'immagine Docker solo Chromium, i pacchetti
|
||||||
Debian che gli servono e Xvfb. Ciò che è ancora in uso esce con la sua tappa del traguardo 0.3.0, e intanto lo usa il
|
Debian che gli servono e Xvfb. Ciò che è ancora in uso esce con la sua tappa del traguardo 0.3.0, e intanto lo usa il
|
||||||
codice di prima: SkiaSharp con C1, ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. Prima
|
codice di prima: ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. SkiaSharp è già uscito,
|
||||||
|
con la tappa C1: le immagini (PNG, JPEG, GIF, BMP, WebP) le leggono e scrivono codec di Febe
|
||||||
|
(`src/Febe.Core/Codecs/Images`), e icona, immagini dimostrative e riquadri li disegna `src/Febe.Core/Drawing`. Prima
|
||||||
di aggiungere qualunque cosa, si chiede.
|
di aggiungere qualunque cosa, si chiede.
|
||||||
|
|
||||||
## Com'è fatto il repository
|
## Com'è fatto il repository
|
||||||
|
|||||||
@@ -46,8 +46,9 @@ un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; i
|
|||||||
dove si vuole e si apre, senza installazione. Anche la versione portabile tiene i dati in `%LOCALAPPDATA%\Febe` e la
|
dove si vuole e si apre, senza installazione. Anche la versione portabile tiene i dati in `%LOCALAPPDATA%\Febe` e la
|
||||||
libreria in `Immagini\Febe`, finché non scegli altre cartelle.
|
libreria in `Immagini\Febe`, finché non scegli altre cartelle.
|
||||||
|
|
||||||
`Febe.exe` è un file solo (circa 86 MB): contiene il runtime .NET, l'interfaccia e le librerie native (SQLite, SkiaSharp,
|
`Febe.exe` è un file solo (circa 86 MB, misurato di nuovo senza SkiaSharp): contiene il runtime .NET, l'interfaccia
|
||||||
WebView2Loader). Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale.
|
e le librerie native (SQLite, WebView2Loader). Le immagini le leggono, le scrivono e le disegnano codec di Febe scritti
|
||||||
|
in C#. Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale.
|
||||||
|
|
||||||
## Il primo collegamento a Instagram
|
## Il primo collegamento a Instagram
|
||||||
|
|
||||||
@@ -224,12 +225,13 @@ installer/costruisci.sh 0.2.0 # oppure una versione esplicita
|
|||||||
```
|
```
|
||||||
|
|
||||||
Il risultato è in `out/`: `Febe-Setup-<versione>.exe` e `Febe-<versione>-portabile.zip`, ognuno sotto i 100 MB
|
Il risultato è in `out/`: `Febe-Setup-<versione>.exe` e `Febe-<versione>-portabile.zip`, ognuno sotto i 100 MB
|
||||||
(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB). Lo script
|
(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB; senza
|
||||||
controlla che la pubblicazione abbia prodotto un solo file e che nulla superi il limite. Lo script NSIS è
|
SkiaSharp, il 18 novembre 2026, Febe.exe 85,6 MB). Lo script controlla che la pubblicazione abbia prodotto un solo
|
||||||
|
file e che nulla superi il limite. Lo script NSIS è
|
||||||
`installer/febe.nsi` (Unicode, testi in italiano, versione passata con `/DVERSION=…`).
|
`installer/febe.nsi` (Unicode, testi in italiano, versione passata con `/DVERSION=…`).
|
||||||
|
|
||||||
L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è disegnata dal marchio dell'appendice C con
|
L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è disegnata dal marchio dell'appendice C con
|
||||||
SkiaSharp e scritta a mano: per rigenerarla dopo un cambio del marchio,
|
il disegnatore di casa (`Febe.Core.Drawing`) e scritta a mano: per rigenerarla dopo un cambio del marchio,
|
||||||
`FEBE_RIGENERA_ICONA=1 dotnet test tests/Febe.Tests --filter IconTests`.
|
`FEBE_RIGENERA_ICONA=1 dotnet test tests/Febe.Tests --filter IconTests`.
|
||||||
|
|
||||||
## Prove automatiche su Windows
|
## Prove automatiche su Windows
|
||||||
|
|||||||
@@ -0,0 +1,502 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads Windows BMP files: core (OS/2 1.x), information and V2–V5 headers; 1, 2, 4, 8, 16, 24 and 32 bits per pixel;
|
||||||
|
/// BI_RGB, BI_BITFIELDS, BI_ALPHABITFIELDS, BI_RLE8, BI_RLE4 and an embedded PNG (BI_PNG); rows from the bottom or
|
||||||
|
/// from the top. Alpha comes only from an alpha mask of a BITFIELDS image (V3 headers and later); everything else is
|
||||||
|
/// opaque. Pixels an RLE image skips stay (0, 0, 0, 0). Colour profiles and gamma are not applied.
|
||||||
|
/// </summary>
|
||||||
|
public static class BmpDecoder
|
||||||
|
{
|
||||||
|
private const int FileHeaderSize = 14;
|
||||||
|
private const uint BiRgb = 0;
|
||||||
|
private const uint BiRle8 = 1;
|
||||||
|
private const uint BiRle4 = 2;
|
||||||
|
private const uint BiBitfields = 3;
|
||||||
|
private const uint BiJpeg = 4;
|
||||||
|
private const uint BiPng = 5;
|
||||||
|
private const uint BiAlphaBitfields = 6;
|
||||||
|
|
||||||
|
/// <summary>Whether the bytes start like a BMP file.</summary>
|
||||||
|
public static bool IsBmp(ReadOnlySpan<byte> data) =>
|
||||||
|
data.Length >= 18 && data[0] == (byte)'B' && data[1] == (byte)'M' && ImageFormatSniffer.IsBmpHeaderSize(BinaryPrimitives.ReadUInt32LittleEndian(data[14..]));
|
||||||
|
|
||||||
|
/// <summary>Size of a BMP, without decoding the pixels.</summary>
|
||||||
|
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
|
||||||
|
{
|
||||||
|
var header = ReadHeader(data.Span);
|
||||||
|
if (header.Compression == BiPng)
|
||||||
|
{
|
||||||
|
var png = PngDecoder.Identify(data[header.PixelOffset..], limits);
|
||||||
|
return png with { Format = ImageFormat.Bmp };
|
||||||
|
}
|
||||||
|
|
||||||
|
var widest = Math.Max(Math.Max(BitOperations.PopCount(header.RedMask), BitOperations.PopCount(header.GreenMask)), Math.Max(BitOperations.PopCount(header.BlueMask), BitOperations.PopCount(header.AlphaMask)));
|
||||||
|
return new ImageInfo(ImageFormat.Bmp, header.Width, header.Height, 1, header.AlphaMask != 0, ImageMetadata.Empty)
|
||||||
|
{
|
||||||
|
BitsPerSample = Math.Max(8, widest),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a BMP to straight RGBA8, top row first.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a BMP.</exception>
|
||||||
|
/// <exception cref="ImageFormatNotSupportedException">A BMP variant Febe does not read (JPEG inside, OS/2 Huffman, 64 bits).</exception>
|
||||||
|
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
limits ??= ImageLimits.Default;
|
||||||
|
var span = data.Span;
|
||||||
|
var header = ReadHeader(span);
|
||||||
|
if (header.Compression == BiPng)
|
||||||
|
{
|
||||||
|
return PngDecoder.Decode(data[header.PixelOffset..], limits, pooled);
|
||||||
|
}
|
||||||
|
|
||||||
|
var image = RgbaImage.Create(header.Width, header.Height, limits, pooled);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
switch (header.Compression)
|
||||||
|
{
|
||||||
|
case BiRle8:
|
||||||
|
case BiRle4:
|
||||||
|
DecodeRle(span, header, image);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
DecodeRows(span, header, image);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a BMP and returns what <see cref="Identify"/> returns as well.</summary>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
var image = Decode(data, limits, pooled);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
info = Identify(data, limits);
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class BmpHeader
|
||||||
|
{
|
||||||
|
public int Width;
|
||||||
|
public int Height;
|
||||||
|
public bool TopDown;
|
||||||
|
public int BitsPerPixel;
|
||||||
|
public uint Compression;
|
||||||
|
public int PixelOffset;
|
||||||
|
public uint RedMask;
|
||||||
|
public uint GreenMask;
|
||||||
|
public uint BlueMask;
|
||||||
|
public uint AlphaMask;
|
||||||
|
|
||||||
|
/// <summary>RGBA of each palette index (256 entries; those the file does not give are opaque black).</summary>
|
||||||
|
public uint[]? Palette;
|
||||||
|
|
||||||
|
public int Stride => (int)((((long)Width * BitsPerPixel) + 31) / 32 * 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BmpHeader ReadHeader(ReadOnlySpan<byte> data)
|
||||||
|
{
|
||||||
|
if (data.Length < 2 || data[0] != (byte)'B' || data[1] != (byte)'M')
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("Non è un file BMP.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.Length < FileHeaderSize + 4)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: manca l'intestazione.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var infoSize = BinaryPrimitives.ReadUInt32LittleEndian(data[FileHeaderSize..]);
|
||||||
|
if (!ImageFormatSniffer.IsBmpHeaderSize(infoSize))
|
||||||
|
{
|
||||||
|
throw new ImageFormatNotSupportedException($"BMP con un'intestazione di {infoSize} byte, che Febe non conosce.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.Length < FileHeaderSize + infoSize)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: l'intestazione finisce dopo il file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var info = data.Slice(FileHeaderSize, (int)infoSize);
|
||||||
|
var header = new BmpHeader();
|
||||||
|
long width;
|
||||||
|
long height;
|
||||||
|
int planes;
|
||||||
|
var paletteEntrySize = 4;
|
||||||
|
uint colorsUsed = 0;
|
||||||
|
if (infoSize == 12)
|
||||||
|
{
|
||||||
|
width = BinaryPrimitives.ReadUInt16LittleEndian(info[4..]);
|
||||||
|
// bcHeight is an unsigned WORD and core bitmaps are always bottom-up (the sign test below keeps them so).
|
||||||
|
height = BinaryPrimitives.ReadUInt16LittleEndian(info[6..]);
|
||||||
|
planes = BinaryPrimitives.ReadUInt16LittleEndian(info[8..]);
|
||||||
|
header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[10..]);
|
||||||
|
header.Compression = BiRgb;
|
||||||
|
paletteEntrySize = 3;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
width = BinaryPrimitives.ReadInt32LittleEndian(info[4..]);
|
||||||
|
height = BinaryPrimitives.ReadInt32LittleEndian(info[8..]);
|
||||||
|
planes = BinaryPrimitives.ReadUInt16LittleEndian(info[12..]);
|
||||||
|
header.BitsPerPixel = BinaryPrimitives.ReadUInt16LittleEndian(info[14..]);
|
||||||
|
if (infoSize >= 20)
|
||||||
|
{
|
||||||
|
header.Compression = BinaryPrimitives.ReadUInt32LittleEndian(info[16..]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (infoSize >= 36)
|
||||||
|
{
|
||||||
|
colorsUsed = BinaryPrimitives.ReadUInt32LittleEndian(info[32..]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (infoSize is 16 or 64 && header.Compression is 3 or 4)
|
||||||
|
{
|
||||||
|
throw new ImageFormatNotSupportedException("BMP di OS/2 con compressione Huffman o RLE24, che Febe non legge.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (planes != 1 && planes != 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException($"BMP danneggiato: {planes} piani di colore.");
|
||||||
|
}
|
||||||
|
|
||||||
|
header.TopDown = height < 0;
|
||||||
|
height = Math.Abs(height);
|
||||||
|
if (width <= 0 || height == 0 || height > int.MaxValue)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException($"BMP danneggiato: misura non valida ({width}×{height}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
header.Width = (int)width;
|
||||||
|
header.Height = (int)height;
|
||||||
|
|
||||||
|
switch (header.Compression)
|
||||||
|
{
|
||||||
|
case BiJpeg:
|
||||||
|
throw new ImageFormatNotSupportedException("BMP con un JPEG dentro, che Febe non legge.");
|
||||||
|
case BiRgb or BiBitfields or BiAlphaBitfields or BiRle8 or BiRle4 or BiPng:
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new ImageFormatNotSupportedException($"BMP con la compressione {header.Compression}, che Febe non conosce.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var bpp = header.BitsPerPixel;
|
||||||
|
var valid = header.Compression switch
|
||||||
|
{
|
||||||
|
BiRgb => bpp is 1 or 2 or 4 or 8 or 16 or 24 or 32,
|
||||||
|
BiBitfields or BiAlphaBitfields => bpp is 16 or 32,
|
||||||
|
BiRle8 => bpp == 8,
|
||||||
|
BiRle4 => bpp == 4,
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
if (!valid)
|
||||||
|
{
|
||||||
|
throw bpp == 64
|
||||||
|
? new ImageFormatNotSupportedException("BMP a 64 bit per pixel, che Febe non legge.")
|
||||||
|
: new ImageDecodeException($"BMP danneggiato: {bpp} bit per pixel con la compressione {header.Compression}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((header.Compression is BiRle8 or BiRle4) && header.TopDown)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP danneggiato: un'immagine RLE non può essere dall'alto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var afterHeader = FileHeaderSize + (int)infoSize;
|
||||||
|
if (header.Compression is BiBitfields or BiAlphaBitfields)
|
||||||
|
{
|
||||||
|
if (infoSize >= 52)
|
||||||
|
{
|
||||||
|
header.RedMask = BinaryPrimitives.ReadUInt32LittleEndian(info[40..]);
|
||||||
|
header.GreenMask = BinaryPrimitives.ReadUInt32LittleEndian(info[44..]);
|
||||||
|
header.BlueMask = BinaryPrimitives.ReadUInt32LittleEndian(info[48..]);
|
||||||
|
header.AlphaMask = infoSize >= 56 ? BinaryPrimitives.ReadUInt32LittleEndian(info[52..]) : 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// An information header is followed by the three (or four) masks.
|
||||||
|
var maskCount = header.Compression == BiAlphaBitfields ? 4 : 3;
|
||||||
|
if (data.Length < afterHeader + (maskCount * 4))
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: mancano le maschere dei colori.");
|
||||||
|
}
|
||||||
|
|
||||||
|
header.RedMask = BinaryPrimitives.ReadUInt32LittleEndian(data[afterHeader..]);
|
||||||
|
header.GreenMask = BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 4)..]);
|
||||||
|
header.BlueMask = BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 8)..]);
|
||||||
|
header.AlphaMask = maskCount == 4 ? BinaryPrimitives.ReadUInt32LittleEndian(data[(afterHeader + 12)..]) : 0;
|
||||||
|
afterHeader += maskCount * 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!IsContiguous(header.RedMask) || !IsContiguous(header.GreenMask) || !IsContiguous(header.BlueMask) || !IsContiguous(header.AlphaMask)
|
||||||
|
|| (header.BitsPerPixel == 16 && ((header.RedMask | header.GreenMask | header.BlueMask | header.AlphaMask) >> 16) != 0))
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP danneggiato: maschere dei colori non valide.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (bpp == 16)
|
||||||
|
{
|
||||||
|
(header.RedMask, header.GreenMask, header.BlueMask) = (0x7C00, 0x03E0, 0x001F);
|
||||||
|
}
|
||||||
|
else if (bpp == 32)
|
||||||
|
{
|
||||||
|
(header.RedMask, header.GreenMask, header.BlueMask) = (0x00FF0000, 0x0000FF00, 0x000000FF);
|
||||||
|
}
|
||||||
|
|
||||||
|
var offset = BinaryPrimitives.ReadUInt32LittleEndian(data[10..]);
|
||||||
|
if (bpp <= 8 && header.Compression != BiPng)
|
||||||
|
{
|
||||||
|
var max = 1 << bpp;
|
||||||
|
var count = colorsUsed == 0 || colorsUsed > max ? max : (int)colorsUsed;
|
||||||
|
if (offset >= afterHeader)
|
||||||
|
{
|
||||||
|
// The pixels may start before the palette would end: the palette is what fits in between.
|
||||||
|
count = (int)Math.Min(count, (offset - afterHeader) / paletteEntrySize);
|
||||||
|
}
|
||||||
|
|
||||||
|
count = Math.Min(count, Math.Max(0, (data.Length - afterHeader) / paletteEntrySize));
|
||||||
|
var palette = new uint[256];
|
||||||
|
Array.Fill(palette, 0xFF000000u);
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var p = afterHeader + (i * paletteEntrySize);
|
||||||
|
palette[i] = Rgba(data[p + 2], data[p + 1], data[p], 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
header.Palette = palette;
|
||||||
|
if (offset < afterHeader)
|
||||||
|
{
|
||||||
|
offset = (uint)(afterHeader + (count * paletteEntrySize));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (offset < afterHeader)
|
||||||
|
{
|
||||||
|
offset = (uint)afterHeader;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (offset >= data.Length)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: i pixel cominciano dopo la fine del file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
header.PixelOffset = (int)offset;
|
||||||
|
return header;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsContiguous(uint mask) => mask == 0 || (((mask >> BitOperations.TrailingZeroCount(mask)) + 1) & (mask >> BitOperations.TrailingZeroCount(mask))) == 0;
|
||||||
|
|
||||||
|
private static uint Rgba(byte r, byte g, byte b, byte a) => r | ((uint)g << 8) | ((uint)b << 16) | ((uint)a << 24);
|
||||||
|
|
||||||
|
private static void DecodeRows(ReadOnlySpan<byte> data, BmpHeader header, RgbaImage image)
|
||||||
|
{
|
||||||
|
var stride = header.Stride;
|
||||||
|
var width = header.Width;
|
||||||
|
var height = header.Height;
|
||||||
|
var needed = (long)stride * (height - 1) + ((((long)width * header.BitsPerPixel) + 7) / 8);
|
||||||
|
if (header.PixelOffset + needed > data.Length)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: i pixel finiscono dopo il file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var bpp = header.BitsPerPixel;
|
||||||
|
Span<byte> red = stackalloc byte[256];
|
||||||
|
Span<byte> green = stackalloc byte[256];
|
||||||
|
Span<byte> blue = stackalloc byte[256];
|
||||||
|
Span<byte> alpha = stackalloc byte[256];
|
||||||
|
var rs = MaskShift(header.RedMask, red);
|
||||||
|
var gs = MaskShift(header.GreenMask, green);
|
||||||
|
var bs = MaskShift(header.BlueMask, blue);
|
||||||
|
var hasAlpha = header.AlphaMask != 0;
|
||||||
|
var @as = hasAlpha ? MaskShift(header.AlphaMask, alpha) : default;
|
||||||
|
var palette = header.Palette;
|
||||||
|
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
var source = data.Slice(header.PixelOffset + (y * stride));
|
||||||
|
var destination = image.GetRow(header.TopDown ? y : height - 1 - y);
|
||||||
|
switch (bpp)
|
||||||
|
{
|
||||||
|
case 1 or 2 or 4 or 8:
|
||||||
|
{
|
||||||
|
var mask = (1 << bpp) - 1;
|
||||||
|
var perByte = 8 / bpp;
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
var shift = 8 - bpp - ((x % perByte) * bpp);
|
||||||
|
var index = (source[x / perByte] >> shift) & mask;
|
||||||
|
BinaryPrimitives.WriteUInt32LittleEndian(destination[(x * 4)..], palette![index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 24:
|
||||||
|
for (int x = 0, s = 0, d = 0; x < width; x++, s += 3, d += 4)
|
||||||
|
{
|
||||||
|
destination[d] = source[s + 2];
|
||||||
|
destination[d + 1] = source[s + 1];
|
||||||
|
destination[d + 2] = source[s];
|
||||||
|
destination[d + 3] = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 32 when header.RedMask == 0x00FF0000 && header.GreenMask == 0x0000FF00 && header.BlueMask == 0x000000FF && (!hasAlpha || header.AlphaMask == 0xFF000000):
|
||||||
|
for (int x = 0, s = 0; x < width; x++, s += 4)
|
||||||
|
{
|
||||||
|
destination[s] = source[s + 2];
|
||||||
|
destination[s + 1] = source[s + 1];
|
||||||
|
destination[s + 2] = source[s];
|
||||||
|
destination[s + 3] = hasAlpha ? source[s + 3] : (byte)255;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
for (int x = 0, d = 0; x < width; x++, d += 4)
|
||||||
|
{
|
||||||
|
var pixel = bpp == 16
|
||||||
|
? BinaryPrimitives.ReadUInt16LittleEndian(source[(x * 2)..])
|
||||||
|
: BinaryPrimitives.ReadUInt32LittleEndian(source[(x * 4)..]);
|
||||||
|
destination[d] = Channel(pixel, header.RedMask, rs, red);
|
||||||
|
destination[d + 1] = Channel(pixel, header.GreenMask, gs, green);
|
||||||
|
destination[d + 2] = Channel(pixel, header.BlueMask, bs, blue);
|
||||||
|
destination[d + 3] = hasAlpha ? Channel(pixel, header.AlphaMask, @as, alpha) : (byte)255;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The shift of a mask and, for masks of up to 8 bits, the 8-bit value of each of their values (scaled with
|
||||||
|
/// rounding: 31 → 255, 1 of 5 bits → 8) in <paramref name="table"/>. Wider masks keep their top 8 bits.
|
||||||
|
/// </summary>
|
||||||
|
private static (int Shift, int Bits) MaskShift(uint mask, Span<byte> table)
|
||||||
|
{
|
||||||
|
if (mask == 0)
|
||||||
|
{
|
||||||
|
return (0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
var shift = BitOperations.TrailingZeroCount(mask);
|
||||||
|
var bits = BitOperations.PopCount(mask);
|
||||||
|
if (bits <= 8)
|
||||||
|
{
|
||||||
|
var max = (1 << bits) - 1;
|
||||||
|
for (var v = 0; v <= max; v++)
|
||||||
|
{
|
||||||
|
table[v] = (byte)(((v * 255) + (max / 2)) / max);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (shift, bits);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte Channel(uint pixel, uint mask, (int Shift, int Bits) layout, ReadOnlySpan<byte> table)
|
||||||
|
{
|
||||||
|
if (layout.Bits == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = (pixel & mask) >> layout.Shift;
|
||||||
|
return layout.Bits <= 8 ? table[(int)value] : (byte)(value >> (layout.Bits - 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DecodeRle(ReadOnlySpan<byte> data, BmpHeader header, RgbaImage image)
|
||||||
|
{
|
||||||
|
var palette = header.Palette!;
|
||||||
|
var four = header.Compression == BiRle4;
|
||||||
|
var width = header.Width;
|
||||||
|
var height = header.Height;
|
||||||
|
var pixels = image.Pixels;
|
||||||
|
var pos = header.PixelOffset;
|
||||||
|
int x = 0, y = 0;
|
||||||
|
while (y < height)
|
||||||
|
{
|
||||||
|
if (pos + 2 > data.Length)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: i dati RLE finiscono prima della fine dell'immagine.");
|
||||||
|
}
|
||||||
|
|
||||||
|
int count = data[pos], value = data[pos + 1];
|
||||||
|
pos += 2;
|
||||||
|
if (count > 0)
|
||||||
|
{
|
||||||
|
// An encoded run: «count» pixels of one index (RLE8) or of two alternating indices (RLE4).
|
||||||
|
var rowStart = (height - 1 - y) * width;
|
||||||
|
for (var k = 0; k < count && x < width; k++, x++)
|
||||||
|
{
|
||||||
|
var index = four ? ((k & 1) == 0 ? value >> 4 : value & 0x0F) : value;
|
||||||
|
BinaryPrimitives.WriteUInt32LittleEndian(pixels[((rowStart + x) * 4)..], palette[index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (value)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
x = 0;
|
||||||
|
y++;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
if (pos + 2 > data.Length)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: uno spostamento RLE finisce dopo il file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
x += data[pos];
|
||||||
|
y += data[pos + 1];
|
||||||
|
pos += 2;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
// An absolute run: «value» indices one after the other, padded to an even number of bytes.
|
||||||
|
var bytes = four ? (value + 1) / 2 : value;
|
||||||
|
if (pos + bytes > data.Length)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("BMP troncato: un tratto RLE assoluto finisce dopo il file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var rowStart = (height - 1 - y) * width;
|
||||||
|
for (var k = 0; k < value && x < width; k++, x++)
|
||||||
|
{
|
||||||
|
var index = four ? ((k & 1) == 0 ? data[pos + (k / 2)] >> 4 : data[pos + (k / 2)] & 0x0F) : data[pos + k];
|
||||||
|
BinaryPrimitives.WriteUInt32LittleEndian(pixels[((rowStart + x) * 4)..], palette[index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += bytes + (bytes & 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The CRC-32 of PNG chunks (ISO 3309 / ITU-T V.42, polynomial 0xEDB88320 reflected, PNG specification annex D),
|
||||||
|
/// computed eight bytes at a time with tables built at start-up.
|
||||||
|
/// </summary>
|
||||||
|
internal static class Crc32
|
||||||
|
{
|
||||||
|
private const uint Polynomial = 0xEDB88320u;
|
||||||
|
|
||||||
|
// Table[k][b]: the CRC of byte b followed by k zero bytes; Table[0] is the classic byte table.
|
||||||
|
private static readonly uint[] Table = BuildTable();
|
||||||
|
|
||||||
|
/// <summary>The CRC of <paramref name="data"/>.</summary>
|
||||||
|
public static uint Compute(ReadOnlySpan<byte> data) => Append(0, data);
|
||||||
|
|
||||||
|
/// <summary>The CRC of the bytes already summed into <paramref name="crc"/> followed by <paramref name="data"/>.</summary>
|
||||||
|
public static uint Append(uint crc, ReadOnlySpan<byte> data)
|
||||||
|
{
|
||||||
|
var table = Table;
|
||||||
|
var c = ~crc;
|
||||||
|
while (data.Length >= 8)
|
||||||
|
{
|
||||||
|
var low = BinaryPrimitives.ReadUInt32LittleEndian(data) ^ c;
|
||||||
|
var high = BinaryPrimitives.ReadUInt32LittleEndian(data[4..]);
|
||||||
|
c = table[(7 * 256) + (low & 0xFF)]
|
||||||
|
^ table[(6 * 256) + ((low >> 8) & 0xFF)]
|
||||||
|
^ table[(5 * 256) + ((low >> 16) & 0xFF)]
|
||||||
|
^ table[(4 * 256) + (low >> 24)]
|
||||||
|
^ table[(3 * 256) + (high & 0xFF)]
|
||||||
|
^ table[(2 * 256) + ((high >> 8) & 0xFF)]
|
||||||
|
^ table[256 + ((high >> 16) & 0xFF)]
|
||||||
|
^ table[high >> 24];
|
||||||
|
data = data[8..];
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var b in data)
|
||||||
|
{
|
||||||
|
c = table[(c ^ b) & 0xFF] ^ (c >> 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ~c;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static uint[] BuildTable()
|
||||||
|
{
|
||||||
|
var table = new uint[8 * 256];
|
||||||
|
for (uint n = 0; n < 256; n++)
|
||||||
|
{
|
||||||
|
var c = n;
|
||||||
|
for (var k = 0; k < 8; k++)
|
||||||
|
{
|
||||||
|
c = (c & 1) != 0 ? Polynomial ^ (c >> 1) : c >> 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
table[n] = c;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var n = 0; n < 256; n++)
|
||||||
|
{
|
||||||
|
for (var k = 1; k < 8; k++)
|
||||||
|
{
|
||||||
|
var previous = table[((k - 1) * 256) + n];
|
||||||
|
table[(k * 256) + n] = table[previous & 0xFF] ^ (previous >> 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Reads the Orientation tag (0x0112) of the first IFD of an EXIF block (a TIFF structure).</summary>
|
||||||
|
internal static class ExifOrientation
|
||||||
|
{
|
||||||
|
private const ushort OrientationTag = 0x0112;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The orientation 1-8 of <paramref name="tiff"/> (starting with «II*\0» or «MM\0*»), or 1 when the block has no
|
||||||
|
/// such tag, an invalid value or is damaged.
|
||||||
|
/// </summary>
|
||||||
|
public static int Read(ReadOnlySpan<byte> tiff)
|
||||||
|
{
|
||||||
|
if (tiff.Length < 8)
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool little;
|
||||||
|
if (tiff[0] == (byte)'I' && tiff[1] == (byte)'I')
|
||||||
|
{
|
||||||
|
little = true;
|
||||||
|
}
|
||||||
|
else if (tiff[0] == (byte)'M' && tiff[1] == (byte)'M')
|
||||||
|
{
|
||||||
|
little = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (U16(tiff[2..], little) != 42)
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var ifd = U32(tiff[4..], little);
|
||||||
|
if (ifd > (uint)(tiff.Length - 2))
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var entries = U16(tiff[(int)ifd..], little);
|
||||||
|
for (var i = 0; i < entries; i++)
|
||||||
|
{
|
||||||
|
var entry = (long)ifd + 2 + (12L * i);
|
||||||
|
if (entry + 12 > tiff.Length)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var e = tiff.Slice((int)entry, 12);
|
||||||
|
if (U16(e, little) != OrientationTag)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var type = U16(e[2..], little);
|
||||||
|
var value = type switch
|
||||||
|
{
|
||||||
|
3 => U16(e[8..], little),
|
||||||
|
4 => U32(e[8..], little),
|
||||||
|
_ => 0u,
|
||||||
|
};
|
||||||
|
return value is >= 1 and <= 8 ? (int)value : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
|
||||||
|
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
|
||||||
|
|
||||||
|
private static uint U32(ReadOnlySpan<byte> b, bool little) =>
|
||||||
|
little ? BinaryPrimitives.ReadUInt32LittleEndian(b) : BinaryPrimitives.ReadUInt32BigEndian(b);
|
||||||
|
}
|
||||||
@@ -0,0 +1,531 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads GIF files (GIF87a and GIF89a): the first frame only, on a canvas of the logical screen size, with global or
|
||||||
|
/// local palette, the transparent index of its graphic control extension and interlacing. Outside the first frame,
|
||||||
|
/// and where the frame's index is transparent, the canvas is (0, 0, 0, 0); the background colour is not painted, as
|
||||||
|
/// browsers do. Disposal methods only matter from the second frame, which is not decoded; the frames are counted.
|
||||||
|
/// A file that ends before its trailer, or LZW data that stops early, gives what was decoded so far.
|
||||||
|
/// </summary>
|
||||||
|
public static class GifDecoder
|
||||||
|
{
|
||||||
|
private const int MaxCodeBits = 12;
|
||||||
|
private const int MaxCodes = 1 << MaxCodeBits;
|
||||||
|
|
||||||
|
/// <summary>Whether the bytes start with a GIF signature.</summary>
|
||||||
|
public static bool IsGif(ReadOnlySpan<byte> data) =>
|
||||||
|
data.Length >= 6 && data[..3].SequenceEqual("GIF"u8) && (data[3..6].SequenceEqual("89a"u8) || data[3..6].SequenceEqual("87a"u8));
|
||||||
|
|
||||||
|
/// <summary>Canvas size, frame count and comments of a GIF, without decoding the pixels.</summary>
|
||||||
|
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
|
||||||
|
{
|
||||||
|
limits ??= ImageLimits.Default;
|
||||||
|
var file = Walk(data.Span, limits, countFrames: true);
|
||||||
|
return file.ToInfo();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes the first frame of a GIF to straight RGBA8.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged, has no frame or is not a GIF.</exception>
|
||||||
|
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
limits ??= ImageLimits.Default;
|
||||||
|
var span = data.Span;
|
||||||
|
var file = Walk(span, limits, countFrames: false);
|
||||||
|
return DecodeFirstFrame(span, file, limits, pooled);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes the first frame of a GIF and returns what <see cref="Identify"/> returns as well.</summary>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
limits ??= ImageLimits.Default;
|
||||||
|
var span = data.Span;
|
||||||
|
var file = Walk(span, limits, countFrames: true);
|
||||||
|
var image = DecodeFirstFrame(span, file, limits, pooled);
|
||||||
|
info = file.ToInfo();
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class GifFile
|
||||||
|
{
|
||||||
|
public int CanvasWidth;
|
||||||
|
public int CanvasHeight;
|
||||||
|
public int GlobalPaletteStart = -1;
|
||||||
|
public int GlobalPaletteCount;
|
||||||
|
|
||||||
|
public int FrameCount;
|
||||||
|
public int FrameLeft;
|
||||||
|
public int FrameTop;
|
||||||
|
public int FrameWidth;
|
||||||
|
public int FrameHeight;
|
||||||
|
public bool FrameInterlaced;
|
||||||
|
public int FramePaletteStart = -1;
|
||||||
|
public int FramePaletteCount;
|
||||||
|
public int FrameTransparent = -1;
|
||||||
|
public int FrameCodeSize;
|
||||||
|
public int FrameDataStart;
|
||||||
|
|
||||||
|
public List<ImageText>? Comments;
|
||||||
|
|
||||||
|
public ImageInfo ToInfo() => new(
|
||||||
|
ImageFormat.Gif,
|
||||||
|
CanvasWidth,
|
||||||
|
CanvasHeight,
|
||||||
|
Math.Max(1, FrameCount),
|
||||||
|
true,
|
||||||
|
Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments });
|
||||||
|
}
|
||||||
|
|
||||||
|
private static GifFile Walk(ReadOnlySpan<byte> data, ImageLimits limits, bool countFrames)
|
||||||
|
{
|
||||||
|
if (!IsGif(data))
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("Non è un file GIF.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.Length < 13)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("GIF troncato: manca il descrittore dello schermo logico.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var file = new GifFile
|
||||||
|
{
|
||||||
|
CanvasWidth = BinaryPrimitives.ReadUInt16LittleEndian(data[6..]),
|
||||||
|
CanvasHeight = BinaryPrimitives.ReadUInt16LittleEndian(data[8..]),
|
||||||
|
};
|
||||||
|
var packed = data[10];
|
||||||
|
var pos = 13;
|
||||||
|
if ((packed & 0x80) != 0)
|
||||||
|
{
|
||||||
|
file.GlobalPaletteCount = 2 << (packed & 7);
|
||||||
|
file.GlobalPaletteStart = pos;
|
||||||
|
pos += file.GlobalPaletteCount * 3;
|
||||||
|
if (pos > data.Length)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("GIF troncato: la tavolozza globale finisce dopo il file.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var transparent = -1;
|
||||||
|
var metadataBudget = limits.MaxMetadataBytes;
|
||||||
|
while (pos < data.Length)
|
||||||
|
{
|
||||||
|
var block = data[pos++];
|
||||||
|
if (block == 0x3B)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (block == 0x21)
|
||||||
|
{
|
||||||
|
if (pos >= data.Length)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var label = data[pos++];
|
||||||
|
if (label == 0xF9 && pos + 5 <= data.Length && data[pos] >= 4)
|
||||||
|
{
|
||||||
|
// Graphic control extension: the transparent index applies to the next image only.
|
||||||
|
transparent = (data[pos + 1] & 1) != 0 ? data[pos + 4] : -1;
|
||||||
|
}
|
||||||
|
else if (label == 0xFE && file.FrameCount == 0)
|
||||||
|
{
|
||||||
|
ReadComment(data, pos, file, ref metadataBudget);
|
||||||
|
}
|
||||||
|
|
||||||
|
pos = SkipSubBlocks(data, pos);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (block != 0x2C)
|
||||||
|
{
|
||||||
|
// Not a block GIF knows: what follows cannot be read; browsers stop here too.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos + 9 > data.Length)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
file.FrameCount++;
|
||||||
|
var framePacked = data[pos + 8];
|
||||||
|
if (file.FrameCount == 1)
|
||||||
|
{
|
||||||
|
file.FrameLeft = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
|
||||||
|
file.FrameTop = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
|
||||||
|
file.FrameWidth = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 4)..]);
|
||||||
|
file.FrameHeight = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 6)..]);
|
||||||
|
file.FrameInterlaced = (framePacked & 0x40) != 0;
|
||||||
|
file.FrameTransparent = transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += 9;
|
||||||
|
if ((framePacked & 0x80) != 0)
|
||||||
|
{
|
||||||
|
var count = 2 << (framePacked & 7);
|
||||||
|
if (file.FrameCount == 1)
|
||||||
|
{
|
||||||
|
file.FramePaletteStart = pos;
|
||||||
|
file.FramePaletteCount = count;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += count * 3;
|
||||||
|
if (pos > data.Length)
|
||||||
|
{
|
||||||
|
if (file.FrameCount == 1)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("GIF troncato: la tavolozza locale finisce dopo il file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
file.FrameCount--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos >= data.Length)
|
||||||
|
{
|
||||||
|
if (file.FrameCount == 1)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("GIF troncato: mancano i dati del primo fotogramma.");
|
||||||
|
}
|
||||||
|
|
||||||
|
file.FrameCount--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.FrameCount == 1)
|
||||||
|
{
|
||||||
|
file.FrameCodeSize = data[pos];
|
||||||
|
file.FrameDataStart = pos + 1;
|
||||||
|
if (!countFrames)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pos = SkipSubBlocks(data, pos + 1);
|
||||||
|
transparent = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.FrameCount == 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("GIF senza fotogrammi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.CanvasWidth == 0 || file.CanvasHeight == 0)
|
||||||
|
{
|
||||||
|
// Some encoders leave the logical screen empty: the first frame then gives the size.
|
||||||
|
file.CanvasWidth = file.FrameLeft + file.FrameWidth;
|
||||||
|
file.CanvasHeight = file.FrameTop + file.FrameHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SkipSubBlocks(ReadOnlySpan<byte> data, int pos)
|
||||||
|
{
|
||||||
|
while (pos < data.Length)
|
||||||
|
{
|
||||||
|
var size = data[pos++];
|
||||||
|
if (size == 0)
|
||||||
|
{
|
||||||
|
return pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += size;
|
||||||
|
}
|
||||||
|
|
||||||
|
return data.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ReadComment(ReadOnlySpan<byte> data, int pos, GifFile file, ref int budget)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
while (pos < data.Length)
|
||||||
|
{
|
||||||
|
var size = data[pos++];
|
||||||
|
if (size == 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var n = Math.Min(size, data.Length - pos);
|
||||||
|
if (n > budget)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
budget -= n;
|
||||||
|
builder.Append(Encoding.Latin1.GetString(data.Slice(pos, n)));
|
||||||
|
pos += n;
|
||||||
|
}
|
||||||
|
|
||||||
|
(file.Comments ??= []).Add(new ImageText(string.Empty, builder.ToString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RgbaImage DecodeFirstFrame(ReadOnlySpan<byte> data, GifFile file, ImageLimits limits, bool pooled)
|
||||||
|
{
|
||||||
|
var (paletteStart, paletteCount) = file.FramePaletteStart >= 0
|
||||||
|
? (file.FramePaletteStart, file.FramePaletteCount)
|
||||||
|
: (file.GlobalPaletteStart, file.GlobalPaletteCount);
|
||||||
|
if (paletteStart < 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("GIF danneggiato: il primo fotogramma non ha tavolozza.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.FrameCodeSize is < 1 or > MaxCodeBits - 1)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException($"GIF danneggiato: dimensione iniziale dei codici LZW non valida ({file.FrameCodeSize}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
var image = RgbaImage.Create(file.CanvasWidth, file.CanvasHeight, limits, pooled);
|
||||||
|
var frameWidth = file.FrameWidth;
|
||||||
|
var frameHeight = file.FrameHeight;
|
||||||
|
if (frameWidth == 0 || frameHeight == 0)
|
||||||
|
{
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
var frameBytes = (long)frameWidth * frameHeight;
|
||||||
|
limits.CheckWorkingBytes(frameBytes);
|
||||||
|
var indices = ImageBuffers.Rent<byte>((int)frameBytes);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var decoded = DecodeLzw(data, file.FrameDataStart, file.FrameCodeSize, indices.AsSpan(0, (int)frameBytes));
|
||||||
|
|
||||||
|
// RGBA of each palette index; indices beyond the palette are opaque black, the transparent one is skipped.
|
||||||
|
Span<uint> colours = stackalloc uint[256];
|
||||||
|
Span<byte> rgba = stackalloc byte[4];
|
||||||
|
for (var i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
if (i < paletteCount)
|
||||||
|
{
|
||||||
|
var p = paletteStart + (i * 3);
|
||||||
|
rgba[0] = data[p];
|
||||||
|
rgba[1] = data[p + 1];
|
||||||
|
rgba[2] = data[p + 2];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
rgba[0] = rgba[1] = rgba[2] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
rgba[3] = 255;
|
||||||
|
colours[i] = BinaryPrimitives.ReadUInt32LittleEndian(rgba);
|
||||||
|
}
|
||||||
|
|
||||||
|
var transparent = file.FrameTransparent;
|
||||||
|
var pixels = image.Pixels;
|
||||||
|
var canvasWidth = file.CanvasWidth;
|
||||||
|
var canvasHeight = file.CanvasHeight;
|
||||||
|
var visibleWidth = Math.Min(frameWidth, canvasWidth - file.FrameLeft);
|
||||||
|
for (var r = 0; r < frameHeight; r++)
|
||||||
|
{
|
||||||
|
var rowStart = r * frameWidth;
|
||||||
|
if (rowStart >= decoded)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var y = file.FrameTop + (file.FrameInterlaced ? InterlacedRow(r, frameHeight) : r);
|
||||||
|
if (y >= canvasHeight || visibleWidth <= 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var count = Math.Min(visibleWidth, decoded - rowStart);
|
||||||
|
var destination = pixels.Slice(((y * canvasWidth) + file.FrameLeft) * RgbaImage.BytesPerPixel, count * RgbaImage.BytesPerPixel);
|
||||||
|
var source = indices.AsSpan(rowStart, count);
|
||||||
|
for (var x = 0; x < count; x++)
|
||||||
|
{
|
||||||
|
var index = source[x];
|
||||||
|
if (index != transparent)
|
||||||
|
{
|
||||||
|
BinaryPrimitives.WriteUInt32LittleEndian(destination[(x * 4)..], colours[index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ImageBuffers.Return(indices);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The row of the image that the <paramref name="r"/>-th decoded row of an interlaced frame fills.</summary>
|
||||||
|
internal static int InterlacedRow(int r, int height)
|
||||||
|
{
|
||||||
|
var pass1 = (height + 7) / 8;
|
||||||
|
if (r < pass1)
|
||||||
|
{
|
||||||
|
return r * 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
r -= pass1;
|
||||||
|
var pass2 = (height + 3) / 8;
|
||||||
|
if (r < pass2)
|
||||||
|
{
|
||||||
|
return 4 + (r * 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
r -= pass2;
|
||||||
|
var pass3 = (height + 1) / 4;
|
||||||
|
if (r < pass3)
|
||||||
|
{
|
||||||
|
return 2 + (r * 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
r -= pass3;
|
||||||
|
return 1 + (r * 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes the LZW data sub-blocks that start at <paramref name="pos"/> into <paramref name="output"/> (GIF89a
|
||||||
|
/// appendix F: variable-length codes from <paramref name="minCodeSize"/> + 1 bits up to 12, least significant bit
|
||||||
|
/// first) and returns how many indices were written. A damaged stream stops the decoding there.
|
||||||
|
/// </summary>
|
||||||
|
internal static int DecodeLzw(ReadOnlySpan<byte> data, int pos, int minCodeSize, Span<byte> output)
|
||||||
|
{
|
||||||
|
var prefix = ArrayPool<ushort>.Shared.Rent(MaxCodes);
|
||||||
|
var lengths = ArrayPool<ushort>.Shared.Rent(MaxCodes);
|
||||||
|
var suffix = ArrayPool<byte>.Shared.Rent(MaxCodes);
|
||||||
|
var first = ArrayPool<byte>.Shared.Rent(MaxCodes);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var clear = 1 << minCodeSize;
|
||||||
|
var end = clear + 1;
|
||||||
|
for (var i = 0; i < clear; i++)
|
||||||
|
{
|
||||||
|
prefix[i] = 0;
|
||||||
|
lengths[i] = 1;
|
||||||
|
suffix[i] = (byte)i;
|
||||||
|
first[i] = (byte)i;
|
||||||
|
}
|
||||||
|
|
||||||
|
var codeSize = minCodeSize + 1;
|
||||||
|
var next = clear + 2;
|
||||||
|
var old = -1;
|
||||||
|
var written = 0;
|
||||||
|
uint bits = 0;
|
||||||
|
var bitCount = 0;
|
||||||
|
var blockLeft = 0;
|
||||||
|
while (written < output.Length)
|
||||||
|
{
|
||||||
|
while (bitCount < codeSize)
|
||||||
|
{
|
||||||
|
if (blockLeft == 0)
|
||||||
|
{
|
||||||
|
if (pos >= data.Length || data[pos] == 0)
|
||||||
|
{
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
|
||||||
|
blockLeft = data[pos++];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos >= data.Length)
|
||||||
|
{
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
|
||||||
|
bits |= (uint)data[pos++] << bitCount;
|
||||||
|
bitCount += 8;
|
||||||
|
blockLeft--;
|
||||||
|
}
|
||||||
|
|
||||||
|
var code = (int)(bits & ((1u << codeSize) - 1));
|
||||||
|
bits >>= codeSize;
|
||||||
|
bitCount -= codeSize;
|
||||||
|
|
||||||
|
if (code == clear)
|
||||||
|
{
|
||||||
|
codeSize = minCodeSize + 1;
|
||||||
|
next = clear + 2;
|
||||||
|
old = -1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (code == end)
|
||||||
|
{
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (old < 0)
|
||||||
|
{
|
||||||
|
if (code > clear)
|
||||||
|
{
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
|
||||||
|
output[written++] = (byte)code;
|
||||||
|
old = code;
|
||||||
|
if (next >= 1 << codeSize && codeSize < MaxCodeBits)
|
||||||
|
{
|
||||||
|
codeSize++;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (code > next || (code == next && next >= MaxCodes))
|
||||||
|
{
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (next < MaxCodes)
|
||||||
|
{
|
||||||
|
// The new entry is the previous string followed by the first byte of the current one; when the code
|
||||||
|
// is the entry being made (KwKwK), that first byte is the previous string's own.
|
||||||
|
var firstByte = code == next ? first[old] : first[code];
|
||||||
|
prefix[next] = (ushort)old;
|
||||||
|
suffix[next] = firstByte;
|
||||||
|
first[next] = first[old];
|
||||||
|
lengths[next] = (ushort)(lengths[old] + 1);
|
||||||
|
next++;
|
||||||
|
}
|
||||||
|
|
||||||
|
var length = lengths[code];
|
||||||
|
var stop = written + length;
|
||||||
|
var c = code;
|
||||||
|
for (var o = stop - 1; o >= written; o--)
|
||||||
|
{
|
||||||
|
if (o < output.Length)
|
||||||
|
{
|
||||||
|
output[o] = suffix[c];
|
||||||
|
}
|
||||||
|
|
||||||
|
c = prefix[c];
|
||||||
|
}
|
||||||
|
|
||||||
|
written = Math.Min(stop, output.Length);
|
||||||
|
old = code;
|
||||||
|
if (next >= 1 << codeSize && codeSize < MaxCodeBits)
|
||||||
|
{
|
||||||
|
codeSize++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<ushort>.Shared.Return(prefix);
|
||||||
|
ArrayPool<ushort>.Shared.Return(lengths);
|
||||||
|
ArrayPool<byte>.Shared.Return(suffix);
|
||||||
|
ArrayPool<byte>.Shared.Return(first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Working arrays of the codecs: from <see cref="ArrayPool{T}.Shared"/> up to <see cref="PooledBytes"/>, plain arrays
|
||||||
|
/// above it.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// The shared pool rounds every request up to a power of two and keeps arrays up to 1 GiB in its per-thread and
|
||||||
|
/// per-core slots after they are given back, until a full collection trims them: a 100-megapixel picture (400 MB)
|
||||||
|
/// would leave a 512 MiB array behind for each decoder that ran in parallel. Picture-sized arrays above the threshold
|
||||||
|
/// are therefore allocated and left to the collector, which frees them at once; the copy they save is small next to
|
||||||
|
/// the decoding itself.
|
||||||
|
/// </remarks>
|
||||||
|
internal static class ImageBuffers
|
||||||
|
{
|
||||||
|
/// <summary>Largest array, in bytes, taken from the shared pool (a power of two, so a pooled array never exceeds it).</summary>
|
||||||
|
public const int PooledBytes = 16 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// <summary>An array of at least <paramref name="length"/> elements, contents undefined.</summary>
|
||||||
|
public static T[] Rent<T>(int length)
|
||||||
|
{
|
||||||
|
if ((long)length * Unsafe.SizeOf<T>() <= PooledBytes)
|
||||||
|
{
|
||||||
|
return ArrayPool<T>.Shared.Rent(length);
|
||||||
|
}
|
||||||
|
|
||||||
|
return GC.AllocateUninitializedArray<T>(length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Gives back an array from <see cref="Rent{T}"/>; those above the threshold are left to the collector.</summary>
|
||||||
|
public static void Return<T>(T[] array)
|
||||||
|
{
|
||||||
|
if ((long)array.Length * Unsafe.SizeOf<T>() <= PooledBytes)
|
||||||
|
{
|
||||||
|
ArrayPool<T>.Shared.Return(array);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether <paramref name="array"/> of <see cref="Rent{T}"/> came from the shared pool.</summary>
|
||||||
|
public static bool IsPooled<T>(T[] array) => (long)array.Length * Unsafe.SizeOf<T>() <= PooledBytes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Options of <see cref="ImageConverter"/>.</summary>
|
||||||
|
public sealed record ImageConversionOptions
|
||||||
|
{
|
||||||
|
/// <summary>The options used when a caller passes none.</summary>
|
||||||
|
public static ImageConversionOptions Default { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Quality of a JPEG target (1-100): 92 by Alberto's choice for exports (decision of 18 November 2026).</summary>
|
||||||
|
public int JpegQuality { get; init; } = 92;
|
||||||
|
|
||||||
|
/// <summary>Chroma of a JPEG target: full (4:4:4) by default, so that the converted picture loses as little as possible.</summary>
|
||||||
|
public JpegSubsampling JpegSubsampling { get; init; } = JpegSubsampling.Ratio444;
|
||||||
|
|
||||||
|
/// <summary>What transparent areas become in a JPEG target, which has no alpha.</summary>
|
||||||
|
public Drawing.Color JpegBackground { get; init; } = Drawing.Color.White;
|
||||||
|
|
||||||
|
/// <summary>Limits of the decoding of the source.</summary>
|
||||||
|
public ImageLimits Limits { get; init; } = ImageLimits.Default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What <see cref="ImageConverter.Convert"/> made.</summary>
|
||||||
|
/// <param name="Data">The converted file.</param>
|
||||||
|
/// <param name="Source">The format of the source.</param>
|
||||||
|
/// <param name="Target">The format written.</param>
|
||||||
|
/// <param name="Width">Width as stored (the orientation is not applied: the tag is copied).</param>
|
||||||
|
/// <param name="Height">Height as stored.</param>
|
||||||
|
/// <param name="Lossy">
|
||||||
|
/// Whether pixels may differ from the source's: a JPEG target, or a source with more than 8 bits per sample (the
|
||||||
|
/// decoders keep 8).
|
||||||
|
/// </param>
|
||||||
|
/// <param name="Metadata">The metadata written.</param>
|
||||||
|
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
|
||||||
|
public sealed record ImageConversionResult(
|
||||||
|
byte[] Data,
|
||||||
|
ImageFormat Source,
|
||||||
|
ImageFormat Target,
|
||||||
|
int Width,
|
||||||
|
int Height,
|
||||||
|
bool Lossy,
|
||||||
|
ImageMetadata Metadata,
|
||||||
|
IReadOnlyList<string> NotCarried);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
|
||||||
|
/// the same photo with another extension (exports, decision of 18 November 2026): PNG and WebP without further loss,
|
||||||
|
/// JPEG at the quality of the options. The pixels written are always 8-bit RGB(A): a source with more bits per
|
||||||
|
/// sample (16-bit PNG, 12-bit or lossless JPEG) loses that precision, which the result reports as lossy. The EXIF
|
||||||
|
/// block (dates, camera, the orientation tag) and the XMP packet are copied as they are, the ICC profile only when it
|
||||||
|
/// describes RGB data (a CMYK or grey profile would no longer fit the RGB pixels); the pixels stay as stored, not
|
||||||
|
/// turned by the orientation, which the copied tag still describes. Texts go where the target can hold them: PNG
|
||||||
|
/// text chunks, JPEG comments; WebP has none. The PNG colour chunks (gAMA, cHRM, sRGB) are not written. Whatever
|
||||||
|
/// cannot be carried is listed in <see cref="ImageConversionResult.NotCarried"/>. Animations keep their first frame
|
||||||
|
/// only, and say so.
|
||||||
|
/// </summary>
|
||||||
|
public static class ImageConverter
|
||||||
|
{
|
||||||
|
/// <summary>The formats a conversion can write.</summary>
|
||||||
|
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
|
||||||
|
|
||||||
|
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
|
||||||
|
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
|
||||||
|
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
|
||||||
|
public static ImageConversionResult Convert(ReadOnlyMemory<byte> source, ImageFormat target, ImageConversionOptions? options = null)
|
||||||
|
{
|
||||||
|
if (!CanWrite(target))
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
options ??= ImageConversionOptions.Default;
|
||||||
|
using var image = ImageDecoder.Decode(source, out var info, options.Limits, pooled: true);
|
||||||
|
var notCarried = new List<string>();
|
||||||
|
if (info.FrameCount > 1)
|
||||||
|
{
|
||||||
|
notCarried.Add($"l'animazione: resta solo il primo fotogramma di {info.FrameCount}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var lossy = target == ImageFormat.Jpeg;
|
||||||
|
if (info.BitsPerSample > 8)
|
||||||
|
{
|
||||||
|
notCarried.Add($"la profondità di {info.BitsPerSample} bit per campione (i pixel sono scritti a 8 bit)");
|
||||||
|
lossy = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var metadata = info.Metadata;
|
||||||
|
var exif = metadata.Exif;
|
||||||
|
var icc = metadata.IccProfile;
|
||||||
|
var iccName = metadata.IccProfileName;
|
||||||
|
if (icc is not null && IccColorSpace(icc) != "RGB ")
|
||||||
|
{
|
||||||
|
notCarried.Add(IccColorSpace(icc) switch
|
||||||
|
{
|
||||||
|
"CMYK" => "il profilo colore CMYK (i pixel sono stati convertiti in RGB)",
|
||||||
|
"GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)",
|
||||||
|
_ => "il profilo colore (non descrive pixel RGB)",
|
||||||
|
});
|
||||||
|
icc = null;
|
||||||
|
iccName = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var chunk in metadata.ColorChunks)
|
||||||
|
{
|
||||||
|
notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)");
|
||||||
|
}
|
||||||
|
|
||||||
|
var xmp = metadata.Xmp;
|
||||||
|
var texts = metadata.Texts;
|
||||||
|
byte[] data;
|
||||||
|
switch (target)
|
||||||
|
{
|
||||||
|
case ImageFormat.Png:
|
||||||
|
data = PngEncoder.Encode(image, new PngEncoderOptions
|
||||||
|
{
|
||||||
|
Exif = exif,
|
||||||
|
IccProfile = icc,
|
||||||
|
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
|
||||||
|
Xmp = xmp,
|
||||||
|
Texts = PngTexts(texts, notCarried),
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case ImageFormat.WebP:
|
||||||
|
if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
|
||||||
|
{
|
||||||
|
throw new ImageLimitException($"Un'immagine WebP non supera {WebPEncoder.MaxDimension} pixel per lato ({image.Width}×{image.Height}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (texts.Count > 0)
|
||||||
|
{
|
||||||
|
notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
|
||||||
|
}
|
||||||
|
|
||||||
|
data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
|
||||||
|
{
|
||||||
|
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
|
||||||
|
exif = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
|
||||||
|
{
|
||||||
|
notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
|
||||||
|
xmp = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var comments = new List<string>();
|
||||||
|
foreach (var text in texts)
|
||||||
|
{
|
||||||
|
comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!image.IsOpaque())
|
||||||
|
{
|
||||||
|
ImageBackground.Flatten(image, options.JpegBackground);
|
||||||
|
notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
|
||||||
|
}
|
||||||
|
|
||||||
|
data = JpegEncoder.Encode(image, new JpegEncoderOptions
|
||||||
|
{
|
||||||
|
Quality = options.JpegQuality,
|
||||||
|
Subsampling = options.JpegSubsampling,
|
||||||
|
Exif = exif,
|
||||||
|
IccProfile = icc,
|
||||||
|
Xmp = xmp,
|
||||||
|
Comments = comments,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var written = new ImageMetadata
|
||||||
|
{
|
||||||
|
Exif = exif,
|
||||||
|
Orientation = metadata.Orientation,
|
||||||
|
IccProfile = icc,
|
||||||
|
IccProfileName = icc is null ? null : iccName,
|
||||||
|
Xmp = xmp,
|
||||||
|
Texts = target == ImageFormat.WebP ? [] : texts,
|
||||||
|
};
|
||||||
|
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
|
||||||
|
internal static string? IccColorSpace(ReadOnlySpan<byte> profile)
|
||||||
|
{
|
||||||
|
if (profile.Length < 20)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Span<char> name = stackalloc char[4];
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
var b = profile[16 + i];
|
||||||
|
if (b is < 32 or > 126)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
name[i] = (char)b;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new string(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
|
||||||
|
private const int JpegMaxSegmentPayload = 65533;
|
||||||
|
|
||||||
|
private static string? ValidIccName(string? name)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(name) || name.Length > 79)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var c in name)
|
||||||
|
{
|
||||||
|
if (c < 32 || c > 255 || (c > 126 && c < 161))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return name.Trim().Length == name.Length ? name : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried)
|
||||||
|
{
|
||||||
|
var result = new List<ImageText>(texts.Count);
|
||||||
|
foreach (var text in texts)
|
||||||
|
{
|
||||||
|
var keyword = text.Keyword.Length == 0 ? "Comment" : text.Keyword;
|
||||||
|
if (!PngEncoder.IsValidKeyword(keyword))
|
||||||
|
{
|
||||||
|
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Add(text with { Keyword = keyword });
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Composites an image over a plain colour.</summary>
|
||||||
|
public static class ImageBackground
|
||||||
|
{
|
||||||
|
/// <summary>Every pixel of <paramref name="image"/> seen over <paramref name="background"/>, opaque, in place.</summary>
|
||||||
|
public static void Flatten(RgbaImage image, Drawing.Color background)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(image);
|
||||||
|
var pixels = image.Pixels;
|
||||||
|
for (var i = 0; i < pixels.Length; i += 4)
|
||||||
|
{
|
||||||
|
int a = pixels[i + 3];
|
||||||
|
if (a == 255)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var keep = 255 - a;
|
||||||
|
pixels[i] = (byte)(((pixels[i] * a) + (background.R * keep) + 127) / 255);
|
||||||
|
pixels[i + 1] = (byte)(((pixels[i + 1] * a) + (background.G * keep) + 127) / 255);
|
||||||
|
pixels[i + 2] = (byte)(((pixels[i + 2] * a) + (background.B * keep) + 127) / 255);
|
||||||
|
pixels[i + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The bytes are not an image Febe can read: damaged, truncated, or outside what the format allows. The message
|
||||||
|
/// (Italian) says what was wrong, never what the image contains.
|
||||||
|
/// </summary>
|
||||||
|
public class ImageDecodeException : Exception
|
||||||
|
{
|
||||||
|
public ImageDecodeException()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImageDecodeException(string message)
|
||||||
|
: base(message)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImageDecodeException(string message, Exception innerException)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The image is well formed but larger than <see cref="ImageLimits"/> allows: it is not decoded.</summary>
|
||||||
|
public sealed class ImageLimitException : ImageDecodeException
|
||||||
|
{
|
||||||
|
public ImageLimitException()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImageLimitException(string message)
|
||||||
|
: base(message)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImageLimitException(string message, Exception innerException)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The format was recognised but Febe has no decoder for it (yet), or not for this variant of it.</summary>
|
||||||
|
public sealed class ImageFormatNotSupportedException : ImageDecodeException
|
||||||
|
{
|
||||||
|
public ImageFormatNotSupportedException()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImageFormatNotSupportedException(string message)
|
||||||
|
: base(message)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ImageFormatNotSupportedException(string message, Exception innerException)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes an image of any format Febe reads, chosen from its first bytes. The pixels come out as stored in the file:
|
||||||
|
/// the EXIF orientation is not applied here.
|
||||||
|
/// </summary>
|
||||||
|
public static class ImageDecoder
|
||||||
|
{
|
||||||
|
/// <summary>Whether Febe has a decoder for <paramref name="format"/>.</summary>
|
||||||
|
public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp or ImageFormat.WebP;
|
||||||
|
|
||||||
|
/// <summary>Size, frames and metadata of an image, without decoding the pixels.</summary>
|
||||||
|
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged.</exception>
|
||||||
|
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null) =>
|
||||||
|
ImageFormatSniffer.Detect(data.Span) switch
|
||||||
|
{
|
||||||
|
ImageFormat.Png => PngDecoder.Identify(data, limits),
|
||||||
|
ImageFormat.Jpeg => JpegDecoder.Identify(data, limits),
|
||||||
|
ImageFormat.Gif => GifDecoder.Identify(data, limits),
|
||||||
|
ImageFormat.Bmp => BmpDecoder.Identify(data, limits),
|
||||||
|
ImageFormat.WebP => WebPDecoder.Identify(data, limits),
|
||||||
|
var other => throw NotSupported(other),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Decodes an image to straight RGBA8 (the first frame of an animation).</summary>
|
||||||
|
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged.</exception>
|
||||||
|
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false) =>
|
||||||
|
ImageFormatSniffer.Detect(data.Span) switch
|
||||||
|
{
|
||||||
|
ImageFormat.Png => PngDecoder.Decode(data, limits, pooled),
|
||||||
|
ImageFormat.Jpeg => JpegDecoder.Decode(data, limits, pooled),
|
||||||
|
ImageFormat.Gif => GifDecoder.Decode(data, limits, pooled),
|
||||||
|
ImageFormat.Bmp => BmpDecoder.Decode(data, limits, pooled),
|
||||||
|
ImageFormat.WebP => WebPDecoder.Decode(data, limits, pooled),
|
||||||
|
var other => throw NotSupported(other),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Decodes an image to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
|
||||||
|
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged.</exception>
|
||||||
|
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
switch (ImageFormatSniffer.Detect(data.Span))
|
||||||
|
{
|
||||||
|
case ImageFormat.Png:
|
||||||
|
return PngDecoder.Decode(data, out info, limits, pooled);
|
||||||
|
case ImageFormat.Jpeg:
|
||||||
|
return JpegDecoder.Decode(data, out info, limits, pooled);
|
||||||
|
case ImageFormat.Gif:
|
||||||
|
return GifDecoder.Decode(data, out info, limits, pooled);
|
||||||
|
case ImageFormat.Bmp:
|
||||||
|
return BmpDecoder.Decode(data, out info, limits, pooled);
|
||||||
|
case ImageFormat.WebP:
|
||||||
|
return WebPDecoder.Decode(data, out info, limits, pooled);
|
||||||
|
case var other:
|
||||||
|
throw NotSupported(other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes an image no smaller than <paramref name="minLongSide"/> on its long side where the format allows a
|
||||||
|
/// cheaper reduced decode (JPEG: a half, a quarter or an eighth, the smallest that keeps that side), at full size
|
||||||
|
/// otherwise; with what <see cref="Identify"/> returns (the full size). The result may still need resizing.
|
||||||
|
/// </summary>
|
||||||
|
public static RgbaImage DecodeAtLeast(ReadOnlyMemory<byte> data, int minLongSide, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(minLongSide);
|
||||||
|
if (ImageFormatSniffer.Detect(data.Span) != ImageFormat.Jpeg)
|
||||||
|
{
|
||||||
|
return Decode(data, out info, limits, pooled);
|
||||||
|
}
|
||||||
|
|
||||||
|
var header = JpegDecoder.Identify(data, limits);
|
||||||
|
var longSide = Math.Max(header.Width, header.Height);
|
||||||
|
var reduction = 0;
|
||||||
|
while (reduction < 3 && ((longSide + (2 << reduction) - 1) >> (reduction + 1)) >= minLongSide)
|
||||||
|
{
|
||||||
|
reduction++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return JpegDecoder.DecodeReduced(data, reduction, out info, limits, pooled);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ImageFormatNotSupportedException NotSupported(ImageFormat format) =>
|
||||||
|
format == ImageFormat.Unknown
|
||||||
|
? new ImageFormatNotSupportedException("Formato d'immagine non riconosciuto.")
|
||||||
|
: new ImageFormatNotSupportedException($"Febe non legge ancora le immagini {format.ToString().ToUpperInvariant()}.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Image formats Febe recognises from their first bytes (not all of them can be decoded).</summary>
|
||||||
|
public enum ImageFormat
|
||||||
|
{
|
||||||
|
Unknown,
|
||||||
|
Png,
|
||||||
|
Jpeg,
|
||||||
|
Gif,
|
||||||
|
Bmp,
|
||||||
|
WebP,
|
||||||
|
Tiff,
|
||||||
|
|
||||||
|
/// <summary>HEIF with HEVC pictures (HEIC), or a generic HEIF.</summary>
|
||||||
|
Heif,
|
||||||
|
|
||||||
|
/// <summary>HEIF with AV1 pictures.</summary>
|
||||||
|
Avif,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Recognises an image format from the first bytes of a file.</summary>
|
||||||
|
public static class ImageFormatSniffer
|
||||||
|
{
|
||||||
|
/// <summary>Bytes <see cref="Detect"/> needs to tell every format apart; fewer are fine for most formats.</summary>
|
||||||
|
public const int HeaderLength = 32;
|
||||||
|
|
||||||
|
/// <summary>The format the bytes start with, or <see cref="ImageFormat.Unknown"/>.</summary>
|
||||||
|
public static ImageFormat Detect(ReadOnlySpan<byte> header)
|
||||||
|
{
|
||||||
|
if (header.Length >= 8 && header[..8].SequenceEqual(PngSignature))
|
||||||
|
{
|
||||||
|
return ImageFormat.Png;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.Length >= 3 && header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF)
|
||||||
|
{
|
||||||
|
return ImageFormat.Jpeg;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.Length >= 6 && header[..3].SequenceEqual("GIF"u8) && (header[3..6].SequenceEqual("89a"u8) || header[3..6].SequenceEqual("87a"u8)))
|
||||||
|
{
|
||||||
|
return ImageFormat.Gif;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.Length >= 18 && header[0] == (byte)'B' && header[1] == (byte)'M' && IsBmpHeaderSize(BinaryPrimitives.ReadUInt32LittleEndian(header[14..])))
|
||||||
|
{
|
||||||
|
return ImageFormat.Bmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.Length >= 12 && header[..4].SequenceEqual("RIFF"u8) && header[8..12].SequenceEqual("WEBP"u8))
|
||||||
|
{
|
||||||
|
return ImageFormat.WebP;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.Length >= 4 && (header[..4].SequenceEqual("II*\0"u8) || header[..4].SequenceEqual("MM\0*"u8)))
|
||||||
|
{
|
||||||
|
return ImageFormat.Tiff;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.Length >= 12 && header[4..8].SequenceEqual("ftyp"u8))
|
||||||
|
{
|
||||||
|
var brand = header[8..12];
|
||||||
|
if (brand.SequenceEqual("avif"u8) || brand.SequenceEqual("avis"u8))
|
||||||
|
{
|
||||||
|
return ImageFormat.Avif;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) || brand.SequenceEqual("heim"u8) || brand.SequenceEqual("heis"u8)
|
||||||
|
|| brand.SequenceEqual("hevc"u8) || brand.SequenceEqual("hevx"u8) || brand.SequenceEqual("mif1"u8) || brand.SequenceEqual("msf1"u8))
|
||||||
|
{
|
||||||
|
return ImageFormat.Heif;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ImageFormat.Unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The eight bytes every PNG file starts with.</summary>
|
||||||
|
internal static ReadOnlySpan<byte> PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||||
|
|
||||||
|
/// <summary>The sizes of the BMP information headers that exist (core, info, V2, V3, OS/2 2.x, V4, V5).</summary>
|
||||||
|
internal static bool IsBmpHeaderSize(uint size) => size is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124;
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Grey levels of RGBA pixels.</summary>
|
||||||
|
public static class ImageGray
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The grey level 0-255 of each pixel of an RGBA row seen over white, with the weights of ITU-R BT.601
|
||||||
|
/// (0.299 R + 0.587 G + 0.114 B): a transparent pixel is white, a half-transparent one halfway to white.
|
||||||
|
/// </summary>
|
||||||
|
public static void LumaOverWhite(ReadOnlySpan<byte> rgba, Span<double> output)
|
||||||
|
{
|
||||||
|
if (output.Length * 4 > rgba.Length)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The row has fewer pixels than the output.", nameof(rgba));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var x = 0; x < output.Length; x++)
|
||||||
|
{
|
||||||
|
var i = x * 4;
|
||||||
|
int a = rgba[i + 3];
|
||||||
|
if (a == 255)
|
||||||
|
{
|
||||||
|
output[x] = (0.299 * rgba[i]) + (0.587 * rgba[i + 1]) + (0.114 * rgba[i + 2]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Over white each channel becomes c·α + 255·(1 − α), with α = a / 255.
|
||||||
|
var alpha = a / 255.0;
|
||||||
|
var white = 255 - a;
|
||||||
|
output[x] = (0.299 * ((rgba[i] * alpha) + white)) + (0.587 * ((rgba[i + 1] * alpha) + white)) + (0.114 * ((rgba[i + 2] * alpha) + white));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// How large an image the decoders accept. A file states its size in a few bytes, so without limits a tiny file could
|
||||||
|
/// ask for gigabytes; the decoders check these before allocating anything.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ImageLimits
|
||||||
|
{
|
||||||
|
/// <summary>The limits used when a caller passes none.</summary>
|
||||||
|
public static ImageLimits Default { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Largest width, in pixels.</summary>
|
||||||
|
public int MaxWidth { get; init; } = 65535;
|
||||||
|
|
||||||
|
/// <summary>Largest height, in pixels.</summary>
|
||||||
|
public int MaxHeight { get; init; } = 65535;
|
||||||
|
|
||||||
|
/// <summary>Largest width × height. 100 megapixels are 400 MB of RGBA.</summary>
|
||||||
|
public long MaxPixels { get; init; } = 100_000_000;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Largest working memory a decoder may take besides the decoded image (for example the indices of a GIF frame).
|
||||||
|
/// </summary>
|
||||||
|
public long MaxWorkingBytes { get; init; } = 512L * 1024 * 1024;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Largest size of the metadata of one image once decompressed (texts, colour profile, EXIF), all chunks together:
|
||||||
|
/// a compressed text chunk can otherwise expand a thousandfold.
|
||||||
|
/// </summary>
|
||||||
|
public int MaxMetadataBytes { get; init; } = 16 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// <summary>Throws <see cref="ImageLimitException"/> when an image of that size is not allowed.</summary>
|
||||||
|
internal void CheckSize(long width, long height)
|
||||||
|
{
|
||||||
|
if (width <= 0 || height <= 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException($"Misura dell'immagine non valida ({width}×{height}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (width > MaxWidth || height > MaxHeight || width * height > MaxPixels)
|
||||||
|
{
|
||||||
|
throw new ImageLimitException($"Immagine troppo grande ({width}×{height}): il limite è {MaxWidth}×{MaxHeight} e {MaxPixels} pixel.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (width * height * RgbaImage.BytesPerPixel > Array.MaxLength)
|
||||||
|
{
|
||||||
|
throw new ImageLimitException($"Immagine troppo grande ({width}×{height}) per la memoria di un processo.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Throws <see cref="ImageLimitException"/> when a decoder would need more working memory than allowed.</summary>
|
||||||
|
internal void CheckWorkingBytes(long bytes)
|
||||||
|
{
|
||||||
|
if (bytes > MaxWorkingBytes || bytes > Array.MaxLength)
|
||||||
|
{
|
||||||
|
throw new ImageLimitException($"La lettura dell'immagine chiederebbe troppa memoria ({bytes} byte, il limite è {MaxWorkingBytes}).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment; JPEG COM).</summary>
|
||||||
|
/// <param name="Keyword">The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF or JPEG comment.</param>
|
||||||
|
/// <param name="Text">The text.</param>
|
||||||
|
/// <param name="Language">The language tag of an iTXt chunk, empty otherwise.</param>
|
||||||
|
/// <param name="TranslatedKeyword">The translated keyword of an iTXt chunk, empty otherwise.</param>
|
||||||
|
public sealed record ImageText(string Keyword, string Text, string Language = "", string TranslatedKeyword = "");
|
||||||
|
|
||||||
|
/// <summary>Metadata read from an image file, without interpreting it.</summary>
|
||||||
|
public sealed class ImageMetadata
|
||||||
|
{
|
||||||
|
/// <summary>No metadata.</summary>
|
||||||
|
public static ImageMetadata Empty { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>The EXIF block as a TIFF structure (starts with «II*\0» or «MM\0*»), or null.</summary>
|
||||||
|
public byte[]? Exif { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The EXIF orientation, 1-8 (T.81 has none of its own: it is the Orientation tag of <see cref="Exif"/>); 1 when the
|
||||||
|
/// image has no EXIF block, no such tag or an invalid value. The decoders never apply it to the pixels.
|
||||||
|
/// </summary>
|
||||||
|
public int Orientation { get; init; } = 1;
|
||||||
|
|
||||||
|
/// <summary>The ICC colour profile, decompressed, or null.</summary>
|
||||||
|
public byte[]? IccProfile { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The name of the ICC profile as the file gives it, or null.</summary>
|
||||||
|
public string? IccProfileName { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG, the APP1 segment of a JPEG), or null.</summary>
|
||||||
|
public string? Xmp { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The texts, in file order (the XMP packet is in <see cref="Xmp"/>, not here).</summary>
|
||||||
|
public IReadOnlyList<ImageText> Texts { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The PNG chunks that describe the colour of the pixels (gAMA, cHRM, sRGB) the file has, in file order. They are
|
||||||
|
/// not applied to the pixels and no encoder writes them, so a conversion says they are left behind.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<string> ColorChunks { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a file says about its image, read without decoding the pixels.</summary>
|
||||||
|
/// <param name="Format">The format.</param>
|
||||||
|
/// <param name="Width">Width in pixels, as stored (no EXIF orientation applied).</param>
|
||||||
|
/// <param name="Height">Height in pixels, as stored.</param>
|
||||||
|
/// <param name="FrameCount">Frames of an animation (GIF images, APNG frames); 1 for a still image.</param>
|
||||||
|
/// <param name="HasAlpha">Whether the format of the pixels can carry transparency (not whether any pixel is transparent).</param>
|
||||||
|
/// <param name="Metadata">The metadata.</param>
|
||||||
|
public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Bits of one sample as the file stores them (PNG bit depth, JPEG precision, BMP mask width; 8 for palettes and
|
||||||
|
/// for GIF and WebP). The decoders give 8-bit samples, so above 8 the decoded pixels have lost precision.
|
||||||
|
/// </summary>
|
||||||
|
public int BitsPerSample { get; init; } = 8;
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The eight EXIF orientations (TIFF 6.0, tag 0x0112): how the stored pixels must be turned to be shown upright.
|
||||||
|
/// 1 upright; 2 mirrored left-right; 3 turned 180°; 4 mirrored top-bottom; 5 mirrored along the main diagonal
|
||||||
|
/// (transposed); 6 to be turned 90° clockwise; 7 mirrored along the other diagonal; 8 to be turned 90° anticlockwise.
|
||||||
|
/// The decoders report the orientation and never apply it: only what Febe shows (thumbnails, previews, the perceptual
|
||||||
|
/// hash) is turned; files and conversions keep the stored pixels and the tag.
|
||||||
|
/// </summary>
|
||||||
|
public static class ImageOrientation
|
||||||
|
{
|
||||||
|
/// <summary>Whether the orientation swaps width and height (5-8).</summary>
|
||||||
|
public static bool SwapsAxes(int orientation) => orientation is >= 5 and <= 8;
|
||||||
|
|
||||||
|
/// <summary>The size of an image as shown, from its stored size.</summary>
|
||||||
|
public static (int Width, int Height) ShownSize(int width, int height, int orientation) =>
|
||||||
|
SwapsAxes(orientation) ? (height, width) : (width, height);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The image turned upright. Returns <paramref name="stored"/> itself for orientation 1 (or any value outside
|
||||||
|
/// 1-8); otherwise a new image (pooled when asked), and <paramref name="stored"/> is left as it is.
|
||||||
|
/// </summary>
|
||||||
|
public static RgbaImage Apply(RgbaImage stored, int orientation, bool pooled = false)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(stored);
|
||||||
|
if (orientation is < 2 or > 8)
|
||||||
|
{
|
||||||
|
return stored;
|
||||||
|
}
|
||||||
|
|
||||||
|
var w = stored.Width;
|
||||||
|
var h = stored.Height;
|
||||||
|
var (ow, oh) = ShownSize(w, h, orientation);
|
||||||
|
var result = pooled ? RgbaImage.Rent(ow, oh) : new RgbaImage(ow, oh);
|
||||||
|
var source = stored.Pixels;
|
||||||
|
var target = result.Pixels;
|
||||||
|
var sourceStride = w * 4;
|
||||||
|
|
||||||
|
// For every target pixel (x, y) the stored pixel it shows: sx = x0 + x·dxx + y·dxy, sy = y0 + x·dyx + y·dyy.
|
||||||
|
var (x0, dxx, dxy, y0, dyx, dyy) = orientation switch
|
||||||
|
{
|
||||||
|
2 => (w - 1, -1, 0, 0, 0, 1),
|
||||||
|
3 => (w - 1, -1, 0, h - 1, 0, -1),
|
||||||
|
4 => (0, 1, 0, h - 1, 0, -1),
|
||||||
|
5 => (0, 0, 1, 0, 1, 0),
|
||||||
|
6 => (0, 0, 1, h - 1, -1, 0),
|
||||||
|
7 => (w - 1, 0, -1, h - 1, -1, 0),
|
||||||
|
_ => (w - 1, 0, -1, 0, 1, 0), // 8
|
||||||
|
};
|
||||||
|
|
||||||
|
var step = (dyx * sourceStride) + (dxx * 4);
|
||||||
|
for (var y = 0; y < oh; y++)
|
||||||
|
{
|
||||||
|
var sx = x0 + (y * dxy);
|
||||||
|
var sy = y0 + (y * dyy);
|
||||||
|
var s = (sy * sourceStride) + (sx * 4);
|
||||||
|
var row = target.Slice(y * ow * 4, ow * 4);
|
||||||
|
for (var x = 0; x < row.Length; x += 4)
|
||||||
|
{
|
||||||
|
row[x] = source[s];
|
||||||
|
row[x + 1] = source[s + 1];
|
||||||
|
row[x + 2] = source[s + 2];
|
||||||
|
row[x + 3] = source[s + 3];
|
||||||
|
s += step;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,433 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>The filter <see cref="ImageResampler"/> weighs the source pixels with.</summary>
|
||||||
|
public enum ResampleFilter
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The Lanczos window of three lobes, sinc(x) sinc(x/3) for |x| < 3: sharp, with a faint ring along hard edges.
|
||||||
|
/// When reducing, the window is stretched by the reduction so that every source pixel counts (no aliasing).
|
||||||
|
/// </summary>
|
||||||
|
Lanczos3,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Area averaging when reducing: each target pixel is the mean of the source area it covers, partial pixels
|
||||||
|
/// weighted by the fraction covered. Enlarging falls back to linear interpolation.
|
||||||
|
/// </summary>
|
||||||
|
Area,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Options of <see cref="ImageResampler"/>.</summary>
|
||||||
|
public sealed record ResampleOptions
|
||||||
|
{
|
||||||
|
/// <summary>The options used when a caller passes none.</summary>
|
||||||
|
public static ResampleOptions Default { get; } = new();
|
||||||
|
|
||||||
|
public ResampleFilter Filter { get; init; } = ResampleFilter.Lanczos3;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Average the light rather than the stored values: sRGB samples are turned into linear light before filtering and
|
||||||
|
/// back afterwards. Off by default, as other programs resize (thin bright lines on dark keep more of their weight
|
||||||
|
/// when on).
|
||||||
|
/// </summary>
|
||||||
|
public bool LinearLight { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Changes the size of an image with a separable filter: every row is filtered horizontally into a short ring of
|
||||||
|
/// floating-point rows, and each target row is a weighted sum of the ring's rows. Memory is the target image plus
|
||||||
|
/// a few rows, whatever the size of the source. Images with transparency are filtered with premultiplied alpha, so
|
||||||
|
/// the colour under transparent pixels does not bleed into the visible ones.
|
||||||
|
/// </summary>
|
||||||
|
public static class ImageResampler
|
||||||
|
{
|
||||||
|
/// <summary><paramref name="source"/> resized to <paramref name="width"/> × <paramref name="height"/>.</summary>
|
||||||
|
public static RgbaImage Resize(RgbaImage source, int width, int height, ResampleOptions? options = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(source);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
|
||||||
|
options ??= ResampleOptions.Default;
|
||||||
|
var target = pooled ? RgbaImage.Rent(width, height) : new RgbaImage(width, height);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (width == source.Width && height == source.Height)
|
||||||
|
{
|
||||||
|
source.Pixels.CopyTo(target.Pixels);
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
Run(source, target, options);
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
target.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The size that fits <paramref name="width"/> × <paramref name="height"/> inside a square of
|
||||||
|
/// <paramref name="longSide"/>, keeping the proportions (rounded, at least 1); the same size when it already fits.
|
||||||
|
/// </summary>
|
||||||
|
public static (int Width, int Height) FitWithin(int width, int height, int longSide)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(longSide);
|
||||||
|
var scale = Math.Min(1.0, (double)longSide / Math.Max(width, height));
|
||||||
|
return (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Run(RgbaImage source, RgbaImage target, ResampleOptions options)
|
||||||
|
{
|
||||||
|
var premultiply = !source.IsOpaque();
|
||||||
|
var linear = options.LinearLight;
|
||||||
|
var horizontal = Weights.Build(source.Width, target.Width, options.Filter);
|
||||||
|
var vertical = Weights.Build(source.Height, target.Height, options.Filter);
|
||||||
|
|
||||||
|
var sw = source.Width;
|
||||||
|
var dw = target.Width;
|
||||||
|
var capacity = Math.Min(vertical.MaxTaps + 1, source.Height);
|
||||||
|
var pool = ArrayPool<Vector4>.Shared;
|
||||||
|
var input = pool.Rent(sw);
|
||||||
|
var accumulator = pool.Rent(dw);
|
||||||
|
var ring = new Vector4[capacity][];
|
||||||
|
var ringRow = new int[capacity];
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (var i = 0; i < capacity; i++)
|
||||||
|
{
|
||||||
|
ring[i] = pool.Rent(dw);
|
||||||
|
ringRow[i] = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var toFloat = linear ? Tables.SrgbToLinear : Tables.Identity;
|
||||||
|
for (var y = 0; y < target.Height; y++)
|
||||||
|
{
|
||||||
|
var start = vertical.Start[y];
|
||||||
|
var count = vertical.Count[y];
|
||||||
|
var acc = accumulator.AsSpan(0, dw);
|
||||||
|
acc.Clear();
|
||||||
|
for (var k = 0; k < count; k++)
|
||||||
|
{
|
||||||
|
var sy = start + k;
|
||||||
|
var slot = sy % capacity;
|
||||||
|
if (ringRow[slot] != sy)
|
||||||
|
{
|
||||||
|
LoadRow(source.GetRow(sy), input.AsSpan(0, sw), toFloat, premultiply);
|
||||||
|
FilterRow(input.AsSpan(0, sw), ring[slot].AsSpan(0, dw), horizontal);
|
||||||
|
ringRow[slot] = sy;
|
||||||
|
}
|
||||||
|
|
||||||
|
var weight = vertical.Values[(y * vertical.MaxTaps) + k];
|
||||||
|
if (weight != 0)
|
||||||
|
{
|
||||||
|
AddScaled(acc, ring[slot].AsSpan(0, dw), weight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
StoreRow(acc, target.GetRow(y), linear, premultiply);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
pool.Return(input);
|
||||||
|
pool.Return(accumulator);
|
||||||
|
foreach (var row in ring)
|
||||||
|
{
|
||||||
|
if (row is not null)
|
||||||
|
{
|
||||||
|
pool.Return(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void LoadRow(ReadOnlySpan<byte> row, Span<Vector4> output, float[] toFloat, bool premultiply)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < output.Length; x++)
|
||||||
|
{
|
||||||
|
var i = x * 4;
|
||||||
|
var a = row[i + 3] * (1f / 255f);
|
||||||
|
var value = new Vector4(toFloat[row[i]], toFloat[row[i + 1]], toFloat[row[i + 2]], a);
|
||||||
|
if (premultiply)
|
||||||
|
{
|
||||||
|
value = new Vector4(value.X * a, value.Y * a, value.Z * a, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
output[x] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void FilterRow(ReadOnlySpan<Vector4> input, Span<Vector4> output, Weights weights)
|
||||||
|
{
|
||||||
|
var taps = weights.MaxTaps;
|
||||||
|
var values = weights.Values;
|
||||||
|
for (var x = 0; x < output.Length; x++)
|
||||||
|
{
|
||||||
|
var start = weights.Start[x];
|
||||||
|
var count = weights.Count[x];
|
||||||
|
var w = values.AsSpan(x * taps, count);
|
||||||
|
var src = input.Slice(start, count);
|
||||||
|
var sum = Vector4.Zero;
|
||||||
|
for (var k = 0; k < w.Length; k++)
|
||||||
|
{
|
||||||
|
sum += src[k] * w[k];
|
||||||
|
}
|
||||||
|
|
||||||
|
output[x] = sum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddScaled(Span<Vector4> accumulator, ReadOnlySpan<Vector4> row, float weight)
|
||||||
|
{
|
||||||
|
var acc = MemoryMarshal.Cast<Vector4, float>(accumulator);
|
||||||
|
var add = MemoryMarshal.Cast<Vector4, float>(row);
|
||||||
|
var i = 0;
|
||||||
|
if (Vector.IsHardwareAccelerated && acc.Length >= Vector<float>.Count)
|
||||||
|
{
|
||||||
|
var w = new Vector<float>(weight);
|
||||||
|
var accVectors = MemoryMarshal.Cast<float, Vector<float>>(acc);
|
||||||
|
var addVectors = MemoryMarshal.Cast<float, Vector<float>>(add);
|
||||||
|
for (var v = 0; v < accVectors.Length; v++)
|
||||||
|
{
|
||||||
|
accVectors[v] += addVectors[v] * w;
|
||||||
|
}
|
||||||
|
|
||||||
|
i = accVectors.Length * Vector<float>.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (; i < acc.Length; i++)
|
||||||
|
{
|
||||||
|
acc[i] += add[i] * weight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StoreRow(ReadOnlySpan<Vector4> row, Span<byte> output, bool linear, bool premultiplied)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < row.Length; x++)
|
||||||
|
{
|
||||||
|
var v = row[x];
|
||||||
|
var a = Math.Clamp(v.W, 0f, 1f);
|
||||||
|
var o = x * 4;
|
||||||
|
if (premultiplied)
|
||||||
|
{
|
||||||
|
if (v.W <= 0f)
|
||||||
|
{
|
||||||
|
output[o] = 0;
|
||||||
|
output[o + 1] = 0;
|
||||||
|
output[o + 2] = 0;
|
||||||
|
output[o + 3] = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Divided by the alpha as filtered, before clamping: the ratio of colour to alpha is what was averaged,
|
||||||
|
// and Lanczos overshooting at a hard edge must not tint the colour.
|
||||||
|
var inverse = 1f / v.W;
|
||||||
|
v = new Vector4(v.X * inverse, v.Y * inverse, v.Z * inverse, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
output[o] = ToByte(v.X, linear);
|
||||||
|
output[o + 1] = ToByte(v.Y, linear);
|
||||||
|
output[o + 2] = ToByte(v.Z, linear);
|
||||||
|
output[o + 3] = (byte)((a * 255f) + 0.5f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static byte ToByte(float value, bool linear)
|
||||||
|
{
|
||||||
|
if (linear)
|
||||||
|
{
|
||||||
|
var index = (int)((value * (Tables.LinearSteps - 1)) + 0.5f);
|
||||||
|
return Tables.LinearToSrgb[Math.Clamp(index, 0, Tables.LinearSteps - 1)];
|
||||||
|
}
|
||||||
|
|
||||||
|
var v = (int)(value + 0.5f);
|
||||||
|
return (uint)v <= 255 ? (byte)v : v < 0 ? (byte)0 : (byte)255;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The weights of one direction: for each target index the first source index, how many follow and their
|
||||||
|
/// weights (summing to 1), <see cref="MaxTaps"/> slots per target index. Source indices outside the image are
|
||||||
|
/// folded onto the nearest edge pixel.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class Weights
|
||||||
|
{
|
||||||
|
private Weights(int[] start, int[] count, float[] values, int maxTaps)
|
||||||
|
{
|
||||||
|
Start = start;
|
||||||
|
Count = count;
|
||||||
|
Values = values;
|
||||||
|
MaxTaps = maxTaps;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] Start { get; }
|
||||||
|
|
||||||
|
public int[] Count { get; }
|
||||||
|
|
||||||
|
public float[] Values { get; }
|
||||||
|
|
||||||
|
public int MaxTaps { get; }
|
||||||
|
|
||||||
|
public static Weights Build(int sourceLength, int targetLength, ResampleFilter filter)
|
||||||
|
{
|
||||||
|
var scale = (double)sourceLength / targetLength;
|
||||||
|
var stretch = Math.Max(1.0, scale);
|
||||||
|
var area = filter == ResampleFilter.Area;
|
||||||
|
double radius = area ? (scale > 1 ? 0.5 * scale : 1.0) : 3.0 * stretch;
|
||||||
|
var maxTaps = Math.Min(sourceLength, (int)Math.Ceiling(2 * radius) + 2);
|
||||||
|
var start = new int[targetLength];
|
||||||
|
var count = new int[targetLength];
|
||||||
|
var values = new float[targetLength * maxTaps];
|
||||||
|
Span<double> raw = maxTaps <= 1024 ? stackalloc double[maxTaps] : new double[maxTaps];
|
||||||
|
for (var t = 0; t < targetLength; t++)
|
||||||
|
{
|
||||||
|
var centre = ((t + 0.5) * scale) - 0.5;
|
||||||
|
var first = (int)Math.Floor(centre - radius) + 1;
|
||||||
|
var last = (int)Math.Ceiling(centre + radius) - 1;
|
||||||
|
if (area && scale > 1)
|
||||||
|
{
|
||||||
|
// Exact coverage of [t·scale, (t+1)·scale) by the source cells.
|
||||||
|
var from = t * scale;
|
||||||
|
var to = from + scale;
|
||||||
|
first = (int)Math.Floor(from);
|
||||||
|
last = Math.Min(sourceLength - 1, (int)Math.Ceiling(to) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var lo = Math.Max(first, 0);
|
||||||
|
var hi = Math.Min(last, sourceLength - 1);
|
||||||
|
if (hi < lo)
|
||||||
|
{
|
||||||
|
lo = hi = Math.Clamp((int)Math.Round(centre), 0, sourceLength - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var n = hi - lo + 1;
|
||||||
|
if (n > maxTaps)
|
||||||
|
{
|
||||||
|
// Only at the far edges of a very small source; keep the taps nearest the centre.
|
||||||
|
var middle = Math.Clamp((int)Math.Round(centre), 0, sourceLength - 1);
|
||||||
|
lo = Math.Clamp(middle - (maxTaps / 2), 0, sourceLength - maxTaps);
|
||||||
|
hi = lo + maxTaps - 1;
|
||||||
|
n = maxTaps;
|
||||||
|
}
|
||||||
|
|
||||||
|
raw[..n].Clear();
|
||||||
|
double sum = 0;
|
||||||
|
for (var s = first; s <= last; s++)
|
||||||
|
{
|
||||||
|
double weight;
|
||||||
|
if (area && scale > 1)
|
||||||
|
{
|
||||||
|
var from = t * scale;
|
||||||
|
weight = Math.Min(from + scale, s + 1) - Math.Max(from, s);
|
||||||
|
}
|
||||||
|
else if (area)
|
||||||
|
{
|
||||||
|
weight = Math.Max(0, 1 - Math.Abs(s - centre));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
weight = Lanczos3((s - centre) / stretch);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (weight == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var index = Math.Clamp(s, lo, hi) - lo;
|
||||||
|
raw[index] += weight;
|
||||||
|
sum += weight;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sum == 0)
|
||||||
|
{
|
||||||
|
raw[Math.Clamp((int)Math.Round(centre), lo, hi) - lo] = 1;
|
||||||
|
sum = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
start[t] = lo;
|
||||||
|
count[t] = n;
|
||||||
|
var row = values.AsSpan(t * maxTaps, maxTaps);
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
row[i] = (float)(raw[i] / sum);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Weights(start, count, values, maxTaps);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double Lanczos3(double x)
|
||||||
|
{
|
||||||
|
x = Math.Abs(x);
|
||||||
|
if (x < 1e-9)
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (x >= 3)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var px = Math.PI * x;
|
||||||
|
return 3 * Math.Sin(px) * Math.Sin(px / 3) / (px * px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Conversions between 8-bit sRGB and linear light (IEC 61966-2-1).</summary>
|
||||||
|
internal static class Tables
|
||||||
|
{
|
||||||
|
public const int LinearSteps = 4096;
|
||||||
|
|
||||||
|
public static readonly float[] Identity = BuildIdentity();
|
||||||
|
|
||||||
|
public static readonly float[] SrgbToLinear = BuildToLinear();
|
||||||
|
|
||||||
|
public static readonly byte[] LinearToSrgb = BuildToSrgb();
|
||||||
|
|
||||||
|
private static float[] BuildIdentity()
|
||||||
|
{
|
||||||
|
var table = new float[256];
|
||||||
|
for (var i = 0; i < table.Length; i++)
|
||||||
|
{
|
||||||
|
table[i] = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float[] BuildToLinear()
|
||||||
|
{
|
||||||
|
var table = new float[256];
|
||||||
|
for (var i = 0; i < table.Length; i++)
|
||||||
|
{
|
||||||
|
var c = i / 255.0;
|
||||||
|
table[i] = (float)(c <= 0.04045 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4));
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] BuildToSrgb()
|
||||||
|
{
|
||||||
|
var table = new byte[LinearSteps];
|
||||||
|
for (var i = 0; i < table.Length; i++)
|
||||||
|
{
|
||||||
|
var l = i / (double)(LinearSteps - 1);
|
||||||
|
var c = l <= 0.0031308 ? l * 12.92 : (1.055 * Math.Pow(l, 1 / 2.4)) - 0.055;
|
||||||
|
table[i] = (byte)Math.Clamp((int)Math.Round(c * 255), 0, 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The probability estimation state machine of the T.81 arithmetic coder (Table D.2), shared by the decoder and the
|
||||||
|
/// test encoder. A context is one byte: bit 7 the sense of the MPS, bits 0-6 the index in the table.
|
||||||
|
/// </summary>
|
||||||
|
internal static class JpegArithmeticTable
|
||||||
|
{
|
||||||
|
/// <summary>Index of the fixed estimate (Qe = 0x5A1D, never adapted) used for the signs of AC coefficients.</summary>
|
||||||
|
public const byte FixedState = 113;
|
||||||
|
|
||||||
|
/// <summary>Qe of each index; entry 113 is the fixed estimate.</summary>
|
||||||
|
public static ReadOnlySpan<ushort> Qe =>
|
||||||
|
[
|
||||||
|
0x5A1D, 0x2586, 0x1114, 0x080B, 0x03D8, 0x01DA, 0x00E5, 0x006F, 0x0036, 0x001A, 0x000D, 0x0006, 0x0003, 0x0001,
|
||||||
|
0x5A7F, 0x3F25, 0x2CF2, 0x207C, 0x17B9, 0x1182, 0x0CEF, 0x09A1, 0x072F, 0x055C, 0x0406, 0x0303, 0x0240, 0x01B1,
|
||||||
|
0x0144, 0x00F5, 0x00B7, 0x008A, 0x0068, 0x004E, 0x003B, 0x002C, 0x5AE1, 0x484C, 0x3A0D, 0x2EF1, 0x261F, 0x1F33,
|
||||||
|
0x19A8, 0x1518, 0x1177, 0x0E74, 0x0BFB, 0x09F8, 0x0861, 0x0706, 0x05CD, 0x04DE, 0x040F, 0x0363, 0x02D4, 0x025C,
|
||||||
|
0x01F8, 0x01A4, 0x0160, 0x0125, 0x00F6, 0x00CB, 0x00AB, 0x008F, 0x5B12, 0x4D04, 0x412C, 0x37D8, 0x2FE8, 0x293C,
|
||||||
|
0x2379, 0x1EDF, 0x1AA9, 0x174E, 0x1424, 0x119C, 0x0F6B, 0x0D51, 0x0BB6, 0x0A40, 0x5832, 0x4D1C, 0x438E, 0x3BDD,
|
||||||
|
0x34EE, 0x2EAE, 0x299A, 0x2516, 0x5570, 0x4CA9, 0x44D9, 0x3E22, 0x3824, 0x32B4, 0x2E17, 0x56A8, 0x4F46, 0x47E5,
|
||||||
|
0x41CF, 0x3C3D, 0x375E, 0x5231, 0x4C0F, 0x4639, 0x415E, 0x5627, 0x50E7, 0x4B85, 0x5597, 0x504F, 0x5A10, 0x5522,
|
||||||
|
0x59EB, 0x5A1D,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Next_Index_LPS of each index.</summary>
|
||||||
|
public static ReadOnlySpan<byte> NextLps =>
|
||||||
|
[
|
||||||
|
1, 14, 16, 18, 20, 23, 25, 28, 30, 33, 35, 9, 10, 12, 15, 36, 38, 39, 40, 42, 43, 45, 46, 48, 49, 51, 52, 54, 56,
|
||||||
|
57, 59, 60, 62, 63, 32, 33, 37, 64, 65, 67, 68, 69, 70, 72, 73, 74, 75, 77, 78, 79, 48, 50, 50, 51, 52, 53, 54, 55,
|
||||||
|
56, 57, 58, 59, 61, 61, 65, 80, 81, 82, 83, 84, 86, 87, 87, 72, 72, 74, 74, 75, 77, 77, 80, 88, 89, 90, 91, 92, 93,
|
||||||
|
86, 88, 95, 96, 97, 99, 99, 93, 95, 101, 102, 103, 104, 99, 105, 106, 107, 103, 105, 108, 109, 110, 111, 110, 112,
|
||||||
|
112, 113,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Next_Index_MPS of each index.</summary>
|
||||||
|
public static ReadOnlySpan<byte> NextMps =>
|
||||||
|
[
|
||||||
|
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
|
||||||
|
32, 33, 34, 35, 9, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
|
||||||
|
61, 62, 63, 32, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 48, 81, 82, 83, 84, 85, 86, 87, 71, 89,
|
||||||
|
90, 91, 92, 93, 94, 86, 96, 97, 98, 99, 100, 93, 102, 103, 104, 99, 106, 107, 103, 109, 107, 111, 109, 111, 113,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Switch_MPS of each index: 1 where an LPS inverts the sense of the MPS.</summary>
|
||||||
|
public static bool Switches(int index) => index is 0 or 14 or 36 or 64 or 80 or 88 or 95 or 105 or 110 or 112;
|
||||||
|
|
||||||
|
/// <summary>The state of a context after coding its LPS with renormalization (T.81 D.1.5.4).</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static byte AfterLps(byte state)
|
||||||
|
{
|
||||||
|
var index = state & 0x7F;
|
||||||
|
var mps = state & 0x80;
|
||||||
|
if (Switches(index))
|
||||||
|
{
|
||||||
|
mps ^= 0x80;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (byte)(mps | NextLps[index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The state of a context after coding its MPS with renormalization (T.81 D.1.5.3).</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static byte AfterMps(byte state) => (byte)((state & 0x80) | NextMps[state & 0x7F]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The arithmetic decoder of T.81 D.2, with the register layout of Table D.5: C is 32 bits, Cx its high half; bytes
|
||||||
|
/// enter the high byte of C-low. At a marker or at the end of the data it supplies zero bytes, as D.1.8 requires.
|
||||||
|
/// </summary>
|
||||||
|
internal ref struct JpegArithmeticDecoder
|
||||||
|
{
|
||||||
|
private readonly ReadOnlySpan<byte> _data;
|
||||||
|
private int _position;
|
||||||
|
private uint _c;
|
||||||
|
private int _a;
|
||||||
|
private int _ct;
|
||||||
|
|
||||||
|
public JpegArithmeticDecoder(ReadOnlySpan<byte> data, int position)
|
||||||
|
{
|
||||||
|
_data = data;
|
||||||
|
_position = position;
|
||||||
|
Initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Position of the next byte not yet read.</summary>
|
||||||
|
public readonly int Position => _position;
|
||||||
|
|
||||||
|
/// <summary>Initdec (Figure D.22) at <paramref name="position"/>, for a restart interval.</summary>
|
||||||
|
public void Restart(int position)
|
||||||
|
{
|
||||||
|
_position = position;
|
||||||
|
Initialize();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decode(S) of Figure D.16: one binary decision of context <paramref name="state"/>, updated in place.</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public int Decode(ref byte state)
|
||||||
|
{
|
||||||
|
var s = state;
|
||||||
|
int qe = JpegArithmeticTable.Qe[s & 0x7F];
|
||||||
|
var mps = s >> 7;
|
||||||
|
_a -= qe;
|
||||||
|
int decision;
|
||||||
|
if ((int)(_c >> 16) < _a)
|
||||||
|
{
|
||||||
|
if (_a >= 0x8000)
|
||||||
|
{
|
||||||
|
return mps;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cond_MPS_exchange (Figure D.18).
|
||||||
|
if (_a < qe)
|
||||||
|
{
|
||||||
|
decision = 1 - mps;
|
||||||
|
state = JpegArithmeticTable.AfterLps(s);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
decision = mps;
|
||||||
|
state = JpegArithmeticTable.AfterMps(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Cond_LPS_exchange (Figure D.17).
|
||||||
|
_c -= (uint)_a << 16;
|
||||||
|
if (_a < qe)
|
||||||
|
{
|
||||||
|
decision = mps;
|
||||||
|
state = JpegArithmeticTable.AfterMps(s);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
decision = 1 - mps;
|
||||||
|
state = JpegArithmeticTable.AfterLps(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
_a = qe;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Renorm_d (Figure D.19).
|
||||||
|
do
|
||||||
|
{
|
||||||
|
if (_ct == 0)
|
||||||
|
{
|
||||||
|
ByteIn();
|
||||||
|
_ct = 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
_a <<= 1;
|
||||||
|
_c <<= 1;
|
||||||
|
_ct--;
|
||||||
|
}
|
||||||
|
while (_a < 0x8000);
|
||||||
|
|
||||||
|
return decision;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A decision with the fixed estimate of probability one half (signs of AC coefficients).</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public int DecodeFixed()
|
||||||
|
{
|
||||||
|
var state = JpegArithmeticTable.FixedState;
|
||||||
|
return Decode(ref state);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Initialize()
|
||||||
|
{
|
||||||
|
_c = 0;
|
||||||
|
ByteIn();
|
||||||
|
_c <<= 8;
|
||||||
|
ByteIn();
|
||||||
|
_c <<= 8;
|
||||||
|
_ct = 0;
|
||||||
|
_a = 0x10000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Byte_in of Figure D.20: a stuffed 0xFF 0x00 is one 0xFF; at a marker nothing is consumed.</summary>
|
||||||
|
private void ByteIn()
|
||||||
|
{
|
||||||
|
uint value = 0;
|
||||||
|
if (_position < _data.Length)
|
||||||
|
{
|
||||||
|
var b = _data[_position];
|
||||||
|
if (b != 0xFF)
|
||||||
|
{
|
||||||
|
value = b;
|
||||||
|
_position++;
|
||||||
|
}
|
||||||
|
else if (_position + 1 < _data.Length && _data[_position + 1] == 0)
|
||||||
|
{
|
||||||
|
value = 0xFF;
|
||||||
|
_position += 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_c += value << 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The 8×8 discrete cosine transforms of T.81 (A.3.3), separable, in single precision. Each one-dimensional pass
|
||||||
|
/// splits the eight points into an even half (a four-point transform on coefficients 0, 2, 4, 6) and an odd half
|
||||||
|
/// (coefficients 1, 3, 5, 7), which is the textbook factorisation of the defining sums: accurate to well under one
|
||||||
|
/// level, which is what the "accurate" integer IDCT of other decoders gives too.
|
||||||
|
/// </summary>
|
||||||
|
internal static class JpegDct
|
||||||
|
{
|
||||||
|
private const float C1 = 0.98078528040323044913f; // cos(1π/16)
|
||||||
|
private const float C2 = 0.92387953251128675613f; // cos(2π/16)
|
||||||
|
private const float C3 = 0.83146961230254523708f; // cos(3π/16)
|
||||||
|
private const float C4 = 0.70710678118654752440f; // cos(4π/16)
|
||||||
|
private const float C5 = 0.55557023301960222474f; // cos(5π/16)
|
||||||
|
private const float C6 = 0.38268343236508977173f; // cos(6π/16)
|
||||||
|
private const float C7 = 0.19509032201612826785f; // cos(7π/16)
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Dequantizes a block (natural order) and writes its 8×8 samples to <paramref name="output"/>, row after row
|
||||||
|
/// <paramref name="stride"/> bytes apart. With <paramref name="precision"/> 12 the samples are 12-bit and are
|
||||||
|
/// reduced to 8 bits through <paramref name="to8Bit"/> (4096 entries); with 8 they are written as they are.
|
||||||
|
/// </summary>
|
||||||
|
public static void Inverse(ReadOnlySpan<short> block, ReadOnlySpan<ushort> quantization, Span<byte> output, int stride, int precision, ReadOnlySpan<byte> to8Bit)
|
||||||
|
{
|
||||||
|
Span<float> work = stackalloc float[64];
|
||||||
|
for (var c = 0; c < 8; c++)
|
||||||
|
{
|
||||||
|
if (block[8 + c] == 0 && block[16 + c] == 0 && block[24 + c] == 0 && block[32 + c] == 0
|
||||||
|
&& block[40 + c] == 0 && block[48 + c] == 0 && block[56 + c] == 0)
|
||||||
|
{
|
||||||
|
var dc = block[c] * quantization[c] * C4;
|
||||||
|
for (var r = 0; r < 8; r++)
|
||||||
|
{
|
||||||
|
work[(r * 8) + c] = dc;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
float x0 = block[c] * quantization[c];
|
||||||
|
float x1 = block[8 + c] * quantization[8 + c];
|
||||||
|
float x2 = block[16 + c] * quantization[16 + c];
|
||||||
|
float x3 = block[24 + c] * quantization[24 + c];
|
||||||
|
float x4 = block[32 + c] * quantization[32 + c];
|
||||||
|
float x5 = block[40 + c] * quantization[40 + c];
|
||||||
|
float x6 = block[48 + c] * quantization[48 + c];
|
||||||
|
float x7 = block[56 + c] * quantization[56 + c];
|
||||||
|
Inverse1D(x0, x1, x2, x3, x4, x5, x6, x7, work, c, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The column pass left every value doubled, the row pass doubles again: a quarter brings them back.
|
||||||
|
var shift = precision == 12 ? 2048.5f : 128.5f;
|
||||||
|
var max = precision == 12 ? 4095 : 255;
|
||||||
|
Span<float> row = stackalloc float[8];
|
||||||
|
for (var r = 0; r < 8; r++)
|
||||||
|
{
|
||||||
|
var w = work.Slice(r * 8, 8);
|
||||||
|
Inverse1D(w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7], row, 0, 1);
|
||||||
|
var o = output.Slice(r * stride, 8);
|
||||||
|
for (var c = 0; c < 8; c++)
|
||||||
|
{
|
||||||
|
var value = (int)((row[c] * 0.25f) + shift);
|
||||||
|
if ((uint)value > (uint)max)
|
||||||
|
{
|
||||||
|
value = value < 0 ? 0 : max;
|
||||||
|
}
|
||||||
|
|
||||||
|
o[c] = precision == 12 ? to8Bit[value] : (byte)value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Like <see cref="Inverse"/>, but writes the block reduced by 2^<paramref name="shift"/> (1 to 3) in each
|
||||||
|
/// direction: every output sample is the mean of a square of the full block's samples (before rounding and
|
||||||
|
/// clamping), computed directly from the coefficients without the full transform.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Averaging two neighbours of the eight-point inverse x[n] = Σ C(k) X[k] cos((2n+1)kπ/16) gives
|
||||||
|
/// Σ C(k) X[k] cos(kπ/16) cos((2m+1)kπ/8). Coefficient 4 drops out (cos((2m+1)π/2) = 0) and coefficient 8 − k
|
||||||
|
/// folds onto k with weight −sin(kπ/16), so the half-size block is a four-point inverse of
|
||||||
|
/// Y0 = C(0) X0, Yk = Xk cos(kπ/16) − X(8−k) sin(kπ/16). Averaging pairs of that once more leaves
|
||||||
|
/// Y0 ± ((C2 + C6) Y1 + (C6 − C2) Y3) / 2, and at an eighth only the DC term remains (S00 / 8 plus the level
|
||||||
|
/// shift: the AC basis functions sum to zero over the block).
|
||||||
|
/// </remarks>
|
||||||
|
public static void InverseReduced(ReadOnlySpan<short> block, ReadOnlySpan<ushort> quantization, Span<byte> output, int stride, int precision, ReadOnlySpan<byte> to8Bit, int shift)
|
||||||
|
{
|
||||||
|
var max = precision == 12 ? 4095 : 255;
|
||||||
|
if (shift >= 3)
|
||||||
|
{
|
||||||
|
var level = precision == 12 ? 2048 : 128;
|
||||||
|
var value = (int)Math.Floor((block[0] * quantization[0] / 8.0) + level + 0.5);
|
||||||
|
value = Math.Clamp(value, 0, max);
|
||||||
|
output[0] = precision == 12 ? to8Bit[value] : (byte)value;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var n = 8 >> shift;
|
||||||
|
Span<float> column = stackalloc float[8];
|
||||||
|
Span<float> work = stackalloc float[32];
|
||||||
|
Span<float> reduced = stackalloc float[4];
|
||||||
|
for (var c = 0; c < 8; c++)
|
||||||
|
{
|
||||||
|
if (block[8 + c] == 0 && block[24 + c] == 0 && block[40 + c] == 0 && block[56 + c] == 0
|
||||||
|
&& (shift == 2 || (block[16 + c] == 0 && block[48 + c] == 0)))
|
||||||
|
{
|
||||||
|
// Only the coefficients that reach the reduced samples are tested (rows 4, and 2 and 6 at a quarter, drop out).
|
||||||
|
var dc = block[c] * quantization[c] * C4;
|
||||||
|
for (var r = 0; r < n; r++)
|
||||||
|
{
|
||||||
|
work[(r * 8) + c] = dc;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var r = 0; r < 8; r++)
|
||||||
|
{
|
||||||
|
column[r] = block[(r * 8) + c] * quantization[(r * 8) + c];
|
||||||
|
}
|
||||||
|
|
||||||
|
Reduce1D(column, reduced, shift);
|
||||||
|
for (var r = 0; r < n; r++)
|
||||||
|
{
|
||||||
|
work[(r * 8) + c] = reduced[r];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each pass doubles the T.81 values, as in Inverse: a quarter brings them back.
|
||||||
|
var levelShift = precision == 12 ? 2048.5f : 128.5f;
|
||||||
|
for (var r = 0; r < n; r++)
|
||||||
|
{
|
||||||
|
Reduce1D(work.Slice(r * 8, 8), reduced, shift);
|
||||||
|
var o = output.Slice(r * stride, n);
|
||||||
|
for (var c = 0; c < n; c++)
|
||||||
|
{
|
||||||
|
var value = (int)((reduced[c] * 0.25f) + levelShift);
|
||||||
|
if ((uint)value > (uint)max)
|
||||||
|
{
|
||||||
|
value = value < 0 ? 0 : max;
|
||||||
|
}
|
||||||
|
|
||||||
|
o[c] = precision == 12 ? to8Bit[value] : (byte)value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The means of 2^<paramref name="shift"/> neighbouring points (shift 1 or 2) of the eight-point inverse of
|
||||||
|
/// <paramref name="x"/> (twice the T.81 inverse, like <see cref="Inverse1D"/>): four or two values.
|
||||||
|
/// </summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static void Reduce1D(ReadOnlySpan<float> x, Span<float> output, int shift)
|
||||||
|
{
|
||||||
|
var y0 = C4 * x[0];
|
||||||
|
var y1 = (C1 * x[1]) - (C7 * x[7]);
|
||||||
|
var y3 = (C3 * x[3]) - (C5 * x[5]);
|
||||||
|
if (shift == 2)
|
||||||
|
{
|
||||||
|
var d = (HalfC2PlusC6 * y1) + (HalfC6MinusC2 * y3);
|
||||||
|
output[0] = y0 + d;
|
||||||
|
output[1] = y0 - d;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var y2 = (C2 * x[2]) - (C6 * x[6]);
|
||||||
|
var e0 = y0 + (C4 * y2);
|
||||||
|
var e1 = y0 - (C4 * y2);
|
||||||
|
var o0 = (C2 * y1) + (C6 * y3);
|
||||||
|
var o1 = (C6 * y1) - (C2 * y3);
|
||||||
|
output[0] = e0 + o0;
|
||||||
|
output[1] = e1 + o1;
|
||||||
|
output[2] = e1 - o1;
|
||||||
|
output[3] = e0 - o0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private const float HalfC2PlusC6 = (C2 + C6) / 2;
|
||||||
|
private const float HalfC6MinusC2 = (C6 - C2) / 2;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order,
|
||||||
|
/// not yet quantized.
|
||||||
|
/// </summary>
|
||||||
|
public static void Forward(ReadOnlySpan<float> samples, Span<float> coefficients)
|
||||||
|
{
|
||||||
|
Span<float> work = stackalloc float[64];
|
||||||
|
for (var r = 0; r < 8; r++)
|
||||||
|
{
|
||||||
|
var s = samples.Slice(r * 8, 8);
|
||||||
|
Forward1D(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], work, r * 8, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var c = 0; c < 8; c++)
|
||||||
|
{
|
||||||
|
Forward1D(work[c], work[8 + c], work[16 + c], work[24 + c], work[32 + c], work[40 + c], work[48 + c], work[56 + c], coefficients, c, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 64; i++)
|
||||||
|
{
|
||||||
|
coefficients[i] *= 0.25f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Eight points of x[n] = Σ C(k) X[k] cos((2n+1)kπ/16), C(0) = 1/√2, C(k) = 1: twice the T.81 inverse.</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static void Inverse1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span<float> output, int start, int step)
|
||||||
|
{
|
||||||
|
var t0 = C4 * (x0 + x4);
|
||||||
|
var t1 = C4 * (x0 - x4);
|
||||||
|
var t2 = (C2 * x2) + (C6 * x6);
|
||||||
|
var t3 = (C6 * x2) - (C2 * x6);
|
||||||
|
var e0 = t0 + t2;
|
||||||
|
var e3 = t0 - t2;
|
||||||
|
var e1 = t1 + t3;
|
||||||
|
var e2 = t1 - t3;
|
||||||
|
|
||||||
|
var o0 = (C1 * x1) + (C3 * x3) + (C5 * x5) + (C7 * x7);
|
||||||
|
var o1 = (C3 * x1) - (C7 * x3) - (C1 * x5) - (C5 * x7);
|
||||||
|
var o2 = (C5 * x1) - (C1 * x3) + (C7 * x5) + (C3 * x7);
|
||||||
|
var o3 = (C7 * x1) - (C5 * x3) + (C3 * x5) - (C1 * x7);
|
||||||
|
|
||||||
|
output[start] = e0 + o0;
|
||||||
|
output[start + step] = e1 + o1;
|
||||||
|
output[start + (2 * step)] = e2 + o2;
|
||||||
|
output[start + (3 * step)] = e3 + o3;
|
||||||
|
output[start + (4 * step)] = e3 - o3;
|
||||||
|
output[start + (5 * step)] = e2 - o2;
|
||||||
|
output[start + (6 * step)] = e1 - o1;
|
||||||
|
output[start + (7 * step)] = e0 - o0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Eight points of X[k] = C(k) Σ x[n] cos((2n+1)kπ/16): twice the T.81 forward transform.</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static void Forward1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span<float> output, int start, int step)
|
||||||
|
{
|
||||||
|
var s0 = x0 + x7;
|
||||||
|
var s1 = x1 + x6;
|
||||||
|
var s2 = x2 + x5;
|
||||||
|
var s3 = x3 + x4;
|
||||||
|
var d0 = x0 - x7;
|
||||||
|
var d1 = x1 - x6;
|
||||||
|
var d2 = x2 - x5;
|
||||||
|
var d3 = x3 - x4;
|
||||||
|
|
||||||
|
output[start] = C4 * (s0 + s1 + s2 + s3);
|
||||||
|
output[start + (4 * step)] = C4 * (s0 - s1 - s2 + s3);
|
||||||
|
output[start + (2 * step)] = (C2 * (s0 - s3)) + (C6 * (s1 - s2));
|
||||||
|
output[start + (6 * step)] = (C6 * (s0 - s3)) - (C2 * (s1 - s2));
|
||||||
|
output[start + step] = (C1 * d0) + (C3 * d1) + (C5 * d2) + (C7 * d3);
|
||||||
|
output[start + (3 * step)] = (C3 * d0) - (C7 * d1) - (C1 * d2) - (C5 * d3);
|
||||||
|
output[start + (5 * step)] = (C5 * d0) - (C1 * d1) + (C7 * d2) + (C3 * d3);
|
||||||
|
output[start + (7 * step)] = (C7 * d0) - (C5 * d1) + (C3 * d2) - (C1 * d3);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads JPEG files (ITU-T T.81): baseline and extended sequential DCT, progressive DCT (spectral selection and
|
||||||
|
/// successive approximation), lossless, each with Huffman or arithmetic coding, 8 and 12 bits (lossless 2-16), any
|
||||||
|
/// sampling factors, restart intervals and DNL. Grey, YCbCr (JFIF), RGB, and with an Adobe APP14 segment CMYK and
|
||||||
|
/// YCCK, all converted to straight RGBA8 (alpha 255). The IDCT is accurate (single precision), chroma is upsampled
|
||||||
|
/// with the triangular filter where the ratio is 2 and replicated otherwise. Metadata: EXIF (with its orientation,
|
||||||
|
/// reported and not applied), the ICC profile from its APP2 chunks, XMP, comments.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged
|
||||||
|
/// (<see cref="ImageDecodeException"/>), as is a Huffman code the table does not have; a missing EOI after complete
|
||||||
|
/// scans, bytes after EOI and stray restart markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused
|
||||||
|
/// with <see cref="ImageFormatNotSupportedException"/>.
|
||||||
|
/// </remarks>
|
||||||
|
public static class JpegDecoder
|
||||||
|
{
|
||||||
|
/// <summary>Whether the bytes start like a JPEG file (SOI and the start of a marker).</summary>
|
||||||
|
public static bool IsJpeg(ReadOnlySpan<byte> data) => data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF;
|
||||||
|
|
||||||
|
/// <summary>Size and metadata of a JPEG, without decoding the pixels.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged or not a JPEG.</exception>
|
||||||
|
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
|
||||||
|
{
|
||||||
|
var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Identify, readMetadata: true);
|
||||||
|
file.Run();
|
||||||
|
return file.ToInfo();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a JPEG to straight RGBA8.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a JPEG.</exception>
|
||||||
|
/// <exception cref="ImageFormatNotSupportedException">The file uses the hierarchical process.</exception>
|
||||||
|
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: false);
|
||||||
|
file.Run();
|
||||||
|
return file.Render(pooled);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a JPEG to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: true);
|
||||||
|
file.Run();
|
||||||
|
var image = file.Render(pooled);
|
||||||
|
info = file.ToInfo();
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes a JPEG reduced by 2^<paramref name="reduction"/> in each direction (0 full size, 1 half, 2 quarter,
|
||||||
|
/// 3 eighth; sizes rounded up), with what <see cref="Identify"/> returns (the full size): each 8×8 block gives the
|
||||||
|
/// means of its squares of samples, which saves memory and, at an eighth, the whole inverse transform. Lossless
|
||||||
|
/// files are always decoded at full size: check the size of the result.
|
||||||
|
/// </summary>
|
||||||
|
public static RgbaImage DecodeReduced(ReadOnlyMemory<byte> data, int reduction, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(reduction);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(reduction, 3);
|
||||||
|
using var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Pixels, readMetadata: true) { ScaleShift = reduction };
|
||||||
|
file.Run();
|
||||||
|
var image = file.Render(pooled);
|
||||||
|
info = file.ToInfo();
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The quantized DCT coefficients of every block of a DCT-based JPEG, as they stand after the last scan, with the
|
||||||
|
/// frame parameters: what tests compare between encodings of the same image (sequential, progressive, restart).
|
||||||
|
/// </summary>
|
||||||
|
internal static JpegCoefficients DecodeCoefficients(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
|
||||||
|
{
|
||||||
|
var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Coefficients, readMetadata: false);
|
||||||
|
file.Run();
|
||||||
|
return file.ToCoefficients();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The coefficients of one component, natural order inside each block, blocks row after row.</summary>
|
||||||
|
/// <param name="Id">Component identifier.</param>
|
||||||
|
/// <param name="H">Horizontal sampling factor.</param>
|
||||||
|
/// <param name="V">Vertical sampling factor.</param>
|
||||||
|
/// <param name="BlocksWide">Blocks that cover the component's samples horizontally.</param>
|
||||||
|
/// <param name="BlocksHigh">Blocks that cover the component's samples vertically.</param>
|
||||||
|
/// <param name="Stride">Blocks per row in <paramref name="Coefficients"/> (the MCU grid, at least <paramref name="BlocksWide"/>).</param>
|
||||||
|
/// <param name="Quantization">The quantization table the component used, natural order.</param>
|
||||||
|
/// <param name="Coefficients">64 coefficients per block.</param>
|
||||||
|
internal sealed record JpegComponentCoefficients(int Id, int H, int V, int BlocksWide, int BlocksHigh, int Stride, ushort[] Quantization, short[] Coefficients)
|
||||||
|
{
|
||||||
|
/// <summary>The DQT table the component refers to.</summary>
|
||||||
|
public int QuantizationTable { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Rows of blocks in <see cref="Coefficients"/>.</summary>
|
||||||
|
public int StoredRows => Coefficients.Length / 64 / Stride;
|
||||||
|
|
||||||
|
/// <summary>The 64 coefficients of block (<paramref name="x"/>, <paramref name="y"/>).</summary>
|
||||||
|
public ReadOnlySpan<short> Block(int x, int y) => Coefficients.AsSpan(((y * Stride) + x) * 64, 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What <see cref="JpegDecoder.DecodeCoefficients"/> returns.</summary>
|
||||||
|
internal sealed record JpegCoefficients(
|
||||||
|
int FrameMarker,
|
||||||
|
int Precision,
|
||||||
|
int Width,
|
||||||
|
int Height,
|
||||||
|
int RestartInterval,
|
||||||
|
int AdobeTransform,
|
||||||
|
bool Jfif,
|
||||||
|
int ScanCount,
|
||||||
|
IReadOnlyList<JpegComponentCoefficients> Components);
|
||||||
@@ -0,0 +1,796 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Chroma sampling of a colour JPEG.</summary>
|
||||||
|
public enum JpegSubsampling
|
||||||
|
{
|
||||||
|
/// <summary>Chroma at half width and half height (H = V = 2 for luma): the usual choice for photos.</summary>
|
||||||
|
Ratio420,
|
||||||
|
|
||||||
|
/// <summary>Chroma at full resolution.</summary>
|
||||||
|
Ratio444,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How <see cref="JpegEncoder"/> writes a file.</summary>
|
||||||
|
public sealed record JpegEncoderOptions
|
||||||
|
{
|
||||||
|
/// <summary>The options used when a caller passes none.</summary>
|
||||||
|
public static JpegEncoderOptions Default { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Quality 1-100: the Annex K tables scaled (50 keeps them as they are).</summary>
|
||||||
|
public int Quality { get; init; } = 85;
|
||||||
|
|
||||||
|
/// <summary>Chroma sampling of a colour image.</summary>
|
||||||
|
public JpegSubsampling Subsampling { get; init; } = JpegSubsampling.Ratio420;
|
||||||
|
|
||||||
|
/// <summary>One component (luma) instead of three.</summary>
|
||||||
|
public bool Grayscale { get; init; }
|
||||||
|
|
||||||
|
/// <summary>MCUs per restart interval (DRI and RSTn markers), 0 for none.</summary>
|
||||||
|
public int RestartInterval { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// EXIF to write in an APP1 segment: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by «Exif\0\0».
|
||||||
|
/// </summary>
|
||||||
|
public byte[]? Exif { get; init; }
|
||||||
|
|
||||||
|
/// <summary>ICC profile to write in APP2 «ICC_PROFILE» chunks.</summary>
|
||||||
|
public byte[]? IccProfile { get; init; }
|
||||||
|
|
||||||
|
/// <summary>XMP packet to write in an APP1 segment (at most one segment: no extended XMP).</summary>
|
||||||
|
public string? Xmp { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Comments to write in COM segments, UTF-8.</summary>
|
||||||
|
public IReadOnlyList<string> Comments { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes baseline JPEG files (T.81 sequential DCT, Huffman, 8 bits): JFIF YCbCr with 4:2:0 or 4:4:4 chroma, or grey;
|
||||||
|
/// quantization from the Annex K tables scaled for the quality, the Annex K Huffman tables, optional restart
|
||||||
|
/// intervals, EXIF, ICC profile, XMP and comments. Alpha is dropped (JPEG has none): the colour under it is encoded.
|
||||||
|
/// The image is encoded one row of MCUs at a time, so memory is the output plus a strip of 16 rows.
|
||||||
|
/// </summary>
|
||||||
|
public static class JpegEncoder
|
||||||
|
{
|
||||||
|
/// <summary>Encodes an image to a JPEG file.</summary>
|
||||||
|
public static byte[] Encode(RgbaImage image, JpegEncoderOptions? options = null)
|
||||||
|
{
|
||||||
|
var output = new JpegOutput();
|
||||||
|
Write(image, options ?? JpegEncoderOptions.Default, output);
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Encodes an image to a JPEG file written to <paramref name="output"/>.</summary>
|
||||||
|
public static void Encode(RgbaImage image, Stream output, JpegEncoderOptions? options = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
var buffer = new JpegOutput();
|
||||||
|
Write(image, options ?? JpegEncoderOptions.Default, buffer);
|
||||||
|
buffer.WriteTo(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The quantized coefficients the encoder would write for <paramref name="image"/>, with its frame layout: what tests
|
||||||
|
/// compare with the decoder and with other entropy codings of the same image.
|
||||||
|
/// </summary>
|
||||||
|
internal static JpegCoefficients Transform(RgbaImage image, JpegEncoderOptions? options = null)
|
||||||
|
{
|
||||||
|
options ??= JpegEncoderOptions.Default;
|
||||||
|
var frame = new FrameLayout(image, options);
|
||||||
|
var components = new JpegComponentCoefficients[frame.Count];
|
||||||
|
for (var i = 0; i < frame.Count; i++)
|
||||||
|
{
|
||||||
|
var c = frame.Components[i];
|
||||||
|
components[i] = new JpegComponentCoefficients(c.Id, c.H, c.V, c.BlocksWide, c.BlocksHigh, c.Stride, frame.Quantization[c.Table], new short[c.Stride * c.Rows * 64])
|
||||||
|
{
|
||||||
|
QuantizationTable = c.Table,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var strip = new Strip(frame);
|
||||||
|
for (var my = 0; my < frame.McusHigh; my++)
|
||||||
|
{
|
||||||
|
strip.Load(image, my);
|
||||||
|
for (var i = 0; i < frame.Count; i++)
|
||||||
|
{
|
||||||
|
var c = frame.Components[i];
|
||||||
|
for (var v = 0; v < c.V; v++)
|
||||||
|
{
|
||||||
|
for (var bx = 0; bx < c.Stride; bx++)
|
||||||
|
{
|
||||||
|
var by = (my * c.V) + v;
|
||||||
|
strip.Quantize(i, bx, v, components[i].Coefficients.AsSpan(((by * c.Stride) + bx) * 64, 64));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new JpegCoefficients(0xC0, 8, image.Width, image.Height, options.RestartInterval, -1, true, 1, components);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Quantized coefficients of arbitrary component planes (tests: CMYK, 12-bit, odd sampling factors). Each plane has
|
||||||
|
/// the component's own size, ceil(width × H / Hmax) × ceil(height × V / Vmax); edges are repeated to fill the blocks.
|
||||||
|
/// </summary>
|
||||||
|
internal static JpegCoefficients TransformPlanes(
|
||||||
|
int width,
|
||||||
|
int height,
|
||||||
|
int precision,
|
||||||
|
IReadOnlyList<(int Id, int H, int V, int Table, int[] Samples)> planes,
|
||||||
|
IReadOnlyList<ushort[]> quantization,
|
||||||
|
int frameMarker)
|
||||||
|
{
|
||||||
|
var maxH = 0;
|
||||||
|
var maxV = 0;
|
||||||
|
foreach (var p in planes)
|
||||||
|
{
|
||||||
|
maxH = Math.Max(maxH, p.H);
|
||||||
|
maxV = Math.Max(maxV, p.V);
|
||||||
|
}
|
||||||
|
|
||||||
|
var mcusWide = (width + (8 * maxH) - 1) / (8 * maxH);
|
||||||
|
var mcusHigh = (height + (8 * maxV) - 1) / (8 * maxV);
|
||||||
|
var shift = 1 << (precision - 1);
|
||||||
|
var result = new JpegComponentCoefficients[planes.Count];
|
||||||
|
Span<float> samples = stackalloc float[64];
|
||||||
|
Span<float> dct = stackalloc float[64];
|
||||||
|
for (var i = 0; i < planes.Count; i++)
|
||||||
|
{
|
||||||
|
var p = planes[i];
|
||||||
|
var cw = ((width * p.H) + maxH - 1) / maxH;
|
||||||
|
var ch = ((height * p.V) + maxV - 1) / maxV;
|
||||||
|
var blocksWide = (cw + 7) / 8;
|
||||||
|
var blocksHigh = (ch + 7) / 8;
|
||||||
|
var stride = planes.Count == 1 ? blocksWide : mcusWide * p.H;
|
||||||
|
var rows = planes.Count == 1 ? blocksHigh : mcusHigh * p.V;
|
||||||
|
var table = quantization[p.Table];
|
||||||
|
var coefficients = new short[stride * rows * 64];
|
||||||
|
for (var by = 0; by < rows; by++)
|
||||||
|
{
|
||||||
|
for (var bx = 0; bx < stride; bx++)
|
||||||
|
{
|
||||||
|
for (var y = 0; y < 8; y++)
|
||||||
|
{
|
||||||
|
var sy = Math.Min((by * 8) + y, ch - 1);
|
||||||
|
for (var x = 0; x < 8; x++)
|
||||||
|
{
|
||||||
|
var sx = Math.Min((bx * 8) + x, cw - 1);
|
||||||
|
samples[(y * 8) + x] = p.Samples[(sy * cw) + sx] - shift;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JpegDct.Forward(samples, dct);
|
||||||
|
var block = coefficients.AsSpan(((by * stride) + bx) * 64, 64);
|
||||||
|
for (var k = 0; k < 64; k++)
|
||||||
|
{
|
||||||
|
block[k] = Round(dct[k] / table[k]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result[i] = new JpegComponentCoefficients(p.Id, p.H, p.V, blocksWide, blocksHigh, stride, table, coefficients) { QuantizationTable = p.Table };
|
||||||
|
}
|
||||||
|
|
||||||
|
return new JpegCoefficients(frameMarker, precision, width, height, 0, -1, false, 1, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static short Round(float value) => (short)Math.Clamp(MathF.Round(value, MidpointRounding.AwayFromZero), short.MinValue, short.MaxValue);
|
||||||
|
|
||||||
|
private static void Write(RgbaImage image, JpegEncoderOptions options, JpegOutput output)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(image);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Width, 65535, nameof(image));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Height, 65535, nameof(image));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(options.RestartInterval, nameof(options));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(options.RestartInterval, 65535, nameof(options));
|
||||||
|
var frame = new FrameLayout(image, options);
|
||||||
|
|
||||||
|
output.Marker(0xD8);
|
||||||
|
JpegSegments.WriteJfif(output);
|
||||||
|
JpegSegments.WriteMetadata(output, options.Exif, options.Xmp, options.IccProfile, options.Comments);
|
||||||
|
JpegSegments.WriteQuantization(output, frame.Quantization);
|
||||||
|
var sof = new List<(int Id, int H, int V, int Table)>();
|
||||||
|
foreach (var c in frame.Components)
|
||||||
|
{
|
||||||
|
sof.Add((c.Id, c.H, c.V, c.Table));
|
||||||
|
}
|
||||||
|
|
||||||
|
JpegSegments.WriteFrame(output, 0xC0, 8, image.Width, image.Height, sof);
|
||||||
|
JpegSegments.WriteHuffman(output, 0, 0, JpegTables.LuminanceDcCounts, JpegTables.LuminanceDcValues);
|
||||||
|
JpegSegments.WriteHuffman(output, 1, 0, JpegTables.LuminanceAcCounts, JpegTables.LuminanceAcValues);
|
||||||
|
if (!options.Grayscale)
|
||||||
|
{
|
||||||
|
JpegSegments.WriteHuffman(output, 0, 1, JpegTables.ChrominanceDcCounts, JpegTables.ChrominanceDcValues);
|
||||||
|
JpegSegments.WriteHuffman(output, 1, 1, JpegTables.ChrominanceAcCounts, JpegTables.ChrominanceAcValues);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.RestartInterval > 0)
|
||||||
|
{
|
||||||
|
JpegSegments.WriteRestartInterval(output, options.RestartInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
var scan = new List<(int Id, int Dc, int Ac)>();
|
||||||
|
foreach (var c in frame.Components)
|
||||||
|
{
|
||||||
|
scan.Add((c.Id, c.Table, c.Table));
|
||||||
|
}
|
||||||
|
|
||||||
|
JpegSegments.WriteScan(output, scan, 0, 63, 0, 0);
|
||||||
|
|
||||||
|
var dc = new[] { StandardTables.LuminanceDc, StandardTables.ChrominanceDc };
|
||||||
|
var ac = new[] { StandardTables.LuminanceAc, StandardTables.ChrominanceAc };
|
||||||
|
var writer = new JpegBitWriter(output);
|
||||||
|
var predictors = new int[frame.Count];
|
||||||
|
var strip = new Strip(frame);
|
||||||
|
Span<short> block = stackalloc short[64];
|
||||||
|
var mcu = 0;
|
||||||
|
var restart = 0;
|
||||||
|
for (var my = 0; my < frame.McusHigh; my++)
|
||||||
|
{
|
||||||
|
strip.Load(image, my);
|
||||||
|
for (var mx = 0; mx < frame.McusWide; mx++, mcu++)
|
||||||
|
{
|
||||||
|
if (options.RestartInterval > 0 && mcu > 0 && mcu % options.RestartInterval == 0)
|
||||||
|
{
|
||||||
|
writer.Flush();
|
||||||
|
output.Marker(0xD0 + (restart++ & 7));
|
||||||
|
Array.Clear(predictors);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < frame.Count; i++)
|
||||||
|
{
|
||||||
|
var c = frame.Components[i];
|
||||||
|
for (var v = 0; v < c.V; v++)
|
||||||
|
{
|
||||||
|
for (var h = 0; h < c.H; h++)
|
||||||
|
{
|
||||||
|
strip.Quantize(i, (mx * c.H) + h, v, block);
|
||||||
|
EncodeBlock(writer, block, ref predictors[i], dc[c.Table], ac[c.Table]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.Flush();
|
||||||
|
output.Marker(0xD9);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One block, baseline: DC difference (F.1.2.1) and run-length coded AC (F.1.2.2).</summary>
|
||||||
|
internal static void EncodeBlock(JpegBitWriter writer, ReadOnlySpan<short> block, ref int predictor, JpegHuffmanTable dc, JpegHuffmanTable ac)
|
||||||
|
{
|
||||||
|
var zigzag = JpegTables.ZigZag;
|
||||||
|
var difference = block[0] - predictor;
|
||||||
|
predictor = block[0];
|
||||||
|
writer.WriteValue(dc, 0, difference);
|
||||||
|
var run = 0;
|
||||||
|
for (var k = 1; k < 64; k++)
|
||||||
|
{
|
||||||
|
int value = block[zigzag[k]];
|
||||||
|
if (value == 0)
|
||||||
|
{
|
||||||
|
run++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (run > 15)
|
||||||
|
{
|
||||||
|
writer.WriteSymbol(ac, 0xF0);
|
||||||
|
run -= 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.WriteValue(ac, run, value);
|
||||||
|
run = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (run > 0)
|
||||||
|
{
|
||||||
|
writer.WriteSymbol(ac, 0x00);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The Annex K Huffman tables, built once.</summary>
|
||||||
|
internal static class StandardTables
|
||||||
|
{
|
||||||
|
public static readonly JpegHuffmanTable LuminanceDc = JpegHuffmanTable.Build(JpegTables.LuminanceDcCounts, JpegTables.LuminanceDcValues);
|
||||||
|
public static readonly JpegHuffmanTable ChrominanceDc = JpegHuffmanTable.Build(JpegTables.ChrominanceDcCounts, JpegTables.ChrominanceDcValues);
|
||||||
|
public static readonly JpegHuffmanTable LuminanceAc = JpegHuffmanTable.Build(JpegTables.LuminanceAcCounts, JpegTables.LuminanceAcValues);
|
||||||
|
public static readonly JpegHuffmanTable ChrominanceAc = JpegHuffmanTable.Build(JpegTables.ChrominanceAcCounts, JpegTables.ChrominanceAcValues);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Components, sampling factors and quantization of the frame the encoder writes.</summary>
|
||||||
|
private sealed class FrameLayout
|
||||||
|
{
|
||||||
|
public FrameLayout(RgbaImage image, JpegEncoderOptions options)
|
||||||
|
{
|
||||||
|
var quality = options.Quality;
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(quality, 1, nameof(options));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(quality, 100, nameof(options));
|
||||||
|
Width = image.Width;
|
||||||
|
Height = image.Height;
|
||||||
|
Quantization = options.Grayscale
|
||||||
|
? [JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, quality)]
|
||||||
|
: [JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, quality), JpegTables.ScaledQuantization(JpegTables.ChrominanceQuantization, quality)];
|
||||||
|
var luma = options.Grayscale || options.Subsampling == JpegSubsampling.Ratio444 ? 1 : 2;
|
||||||
|
MaxH = luma;
|
||||||
|
MaxV = luma;
|
||||||
|
McusWide = (Width + (8 * luma) - 1) / (8 * luma);
|
||||||
|
McusHigh = (Height + (8 * luma) - 1) / (8 * luma);
|
||||||
|
Components = options.Grayscale
|
||||||
|
? [new LayoutComponent(1, 1, 1, 0, this)]
|
||||||
|
: [new LayoutComponent(1, luma, luma, 0, this), new LayoutComponent(2, 1, 1, 1, this), new LayoutComponent(3, 1, 1, 1, this)];
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Width { get; }
|
||||||
|
|
||||||
|
public int Height { get; }
|
||||||
|
|
||||||
|
public int MaxH { get; }
|
||||||
|
|
||||||
|
public int MaxV { get; }
|
||||||
|
|
||||||
|
public int McusWide { get; }
|
||||||
|
|
||||||
|
public int McusHigh { get; }
|
||||||
|
|
||||||
|
public ushort[][] Quantization { get; }
|
||||||
|
|
||||||
|
public LayoutComponent[] Components { get; }
|
||||||
|
|
||||||
|
public int Count => Components.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class LayoutComponent
|
||||||
|
{
|
||||||
|
public LayoutComponent(int id, int h, int v, int table, FrameLayout frame)
|
||||||
|
{
|
||||||
|
Id = id;
|
||||||
|
H = h;
|
||||||
|
V = v;
|
||||||
|
Table = table;
|
||||||
|
Width = ((frame.Width * h) + frame.MaxH - 1) / frame.MaxH;
|
||||||
|
Height = ((frame.Height * v) + frame.MaxV - 1) / frame.MaxV;
|
||||||
|
BlocksWide = (Width + 7) / 8;
|
||||||
|
BlocksHigh = (Height + 7) / 8;
|
||||||
|
Stride = frame.McusWide * h;
|
||||||
|
Rows = frame.McusHigh * v;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Id { get; }
|
||||||
|
|
||||||
|
public int H { get; }
|
||||||
|
|
||||||
|
public int V { get; }
|
||||||
|
|
||||||
|
public int Table { get; }
|
||||||
|
|
||||||
|
public int Width { get; }
|
||||||
|
|
||||||
|
public int Height { get; }
|
||||||
|
|
||||||
|
public int BlocksWide { get; }
|
||||||
|
|
||||||
|
public int BlocksHigh { get; }
|
||||||
|
|
||||||
|
/// <summary>Blocks per row of the MCU grid.</summary>
|
||||||
|
public int Stride { get; }
|
||||||
|
|
||||||
|
/// <summary>Rows of blocks of the MCU grid.</summary>
|
||||||
|
public int Rows { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One row of MCUs as component samples: RGB to YCbCr (T.871), chroma averaged over 2×2 pixels for 4:2:0, edges
|
||||||
|
/// repeated beyond the image; then the forward DCT and quantization of a block on request.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class Strip
|
||||||
|
{
|
||||||
|
// RGB to YCbCr in 16-bit fixed point; each row of weights sums to 0 or 65536, so grey stays grey.
|
||||||
|
private const int YR = 19595;
|
||||||
|
private const int YG = 38470;
|
||||||
|
private const int YB = 7471;
|
||||||
|
private const int CbR = 11059;
|
||||||
|
private const int CbG = 21709;
|
||||||
|
private const int CrG = 27439;
|
||||||
|
private const int CrB = 5329;
|
||||||
|
private const int Half = 32768;
|
||||||
|
|
||||||
|
private readonly FrameLayout _frame;
|
||||||
|
private readonly byte[][] _planes;
|
||||||
|
private readonly int[] _strides;
|
||||||
|
private readonly float[][] _reciprocals;
|
||||||
|
|
||||||
|
public Strip(FrameLayout frame)
|
||||||
|
{
|
||||||
|
_frame = frame;
|
||||||
|
_planes = new byte[frame.Count][];
|
||||||
|
_strides = new int[frame.Count];
|
||||||
|
_reciprocals = new float[frame.Count][];
|
||||||
|
for (var i = 0; i < frame.Count; i++)
|
||||||
|
{
|
||||||
|
var c = frame.Components[i];
|
||||||
|
_strides[i] = c.Stride * 8;
|
||||||
|
_planes[i] = new byte[_strides[i] * c.V * 8];
|
||||||
|
var table = frame.Quantization[c.Table];
|
||||||
|
_reciprocals[i] = new float[64];
|
||||||
|
for (var k = 0; k < 64; k++)
|
||||||
|
{
|
||||||
|
_reciprocals[i][k] = 1f / table[k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Load(RgbaImage image, int mcuRow)
|
||||||
|
{
|
||||||
|
var lastX = image.Width - 1;
|
||||||
|
var lastY = image.Height - 1;
|
||||||
|
var luma = _frame.Components[0];
|
||||||
|
var lumaRows = luma.V * 8;
|
||||||
|
var lumaStride = _strides[0];
|
||||||
|
var top = mcuRow * lumaRows;
|
||||||
|
for (var y = 0; y < lumaRows; y++)
|
||||||
|
{
|
||||||
|
var source = image.GetRow(Math.Min(top + y, lastY));
|
||||||
|
var plane = _planes[0].AsSpan(y * lumaStride, lumaStride);
|
||||||
|
for (var x = 0; x < lumaStride; x++)
|
||||||
|
{
|
||||||
|
var o = Math.Min(x, lastX) * 4;
|
||||||
|
plane[x] = (byte)(((YR * source[o]) + (YG * source[o + 1]) + (YB * source[o + 2]) + Half) >> 16);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_frame.Count == 1)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var factor = _frame.MaxH; // 1 for 4:4:4, 2 for 4:2:0
|
||||||
|
var chromaStride = _strides[1];
|
||||||
|
var chromaTop = mcuRow * 8;
|
||||||
|
for (var y = 0; y < 8; y++)
|
||||||
|
{
|
||||||
|
var cb = _planes[1].AsSpan(y * chromaStride, chromaStride);
|
||||||
|
var cr = _planes[2].AsSpan(y * chromaStride, chromaStride);
|
||||||
|
for (var x = 0; x < chromaStride; x++)
|
||||||
|
{
|
||||||
|
long sumCb = 0;
|
||||||
|
long sumCr = 0;
|
||||||
|
for (var dy = 0; dy < factor; dy++)
|
||||||
|
{
|
||||||
|
var source = image.GetRow(Math.Min(((chromaTop + y) * factor) + dy, lastY));
|
||||||
|
for (var dx = 0; dx < factor; dx++)
|
||||||
|
{
|
||||||
|
var o = Math.Min((x * factor) + dx, lastX) * 4;
|
||||||
|
int r = source[o];
|
||||||
|
int g = source[o + 1];
|
||||||
|
int b = source[o + 2];
|
||||||
|
sumCb += (-CbR * r) - (CbG * g) + (Half * b);
|
||||||
|
sumCr += (Half * r) - (CrG * g) - (CrB * b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var count = factor * factor;
|
||||||
|
var shift = 16 + BitOperations.Log2((uint)count);
|
||||||
|
var round = 1L << (shift - 1);
|
||||||
|
cb[x] = (byte)Math.Clamp(((sumCb + round) >> shift) + 128, 0, 255);
|
||||||
|
cr[x] = (byte)Math.Clamp(((sumCr + round) >> shift) + 128, 0, 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Block (<paramref name="bx"/>, row <paramref name="v"/> of the strip) of component <paramref name="i"/>, quantized.</summary>
|
||||||
|
public void Quantize(int i, int bx, int v, Span<short> block)
|
||||||
|
{
|
||||||
|
Span<float> samples = stackalloc float[64];
|
||||||
|
Span<float> coefficients = stackalloc float[64];
|
||||||
|
var stride = _strides[i];
|
||||||
|
var plane = _planes[i];
|
||||||
|
var start = (v * 8 * stride) + (bx * 8);
|
||||||
|
for (var y = 0; y < 8; y++)
|
||||||
|
{
|
||||||
|
var row = plane.AsSpan(start + (y * stride), 8);
|
||||||
|
for (var x = 0; x < 8; x++)
|
||||||
|
{
|
||||||
|
samples[(y * 8) + x] = row[x] - 128;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JpegDct.Forward(samples, coefficients);
|
||||||
|
var reciprocal = _reciprocals[i];
|
||||||
|
for (var k = 0; k < 64; k++)
|
||||||
|
{
|
||||||
|
var q = coefficients[k] * reciprocal[k];
|
||||||
|
var rounded = (int)(q + (q >= 0 ? 0.5f : -0.5f));
|
||||||
|
|
||||||
|
// Baseline Huffman tables have AC categories up to 10 and DC differences up to 11.
|
||||||
|
block[k] = (short)Math.Clamp(rounded, -1023, 1023);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A growing byte buffer for the encoders.</summary>
|
||||||
|
internal sealed class JpegOutput
|
||||||
|
{
|
||||||
|
private byte[] _buffer = new byte[64 * 1024];
|
||||||
|
private int _length;
|
||||||
|
|
||||||
|
public int Length => _length;
|
||||||
|
|
||||||
|
public void Add(byte value)
|
||||||
|
{
|
||||||
|
if (_length == _buffer.Length)
|
||||||
|
{
|
||||||
|
Array.Resize(ref _buffer, _buffer.Length * 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
_buffer[_length++] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Add(ReadOnlySpan<byte> values)
|
||||||
|
{
|
||||||
|
if (_length + values.Length > _buffer.Length)
|
||||||
|
{
|
||||||
|
Array.Resize(ref _buffer, Math.Max(_buffer.Length * 2, _length + values.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
values.CopyTo(_buffer.AsSpan(_length));
|
||||||
|
_length += values.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Marker(int marker)
|
||||||
|
{
|
||||||
|
Add(0xFF);
|
||||||
|
Add((byte)marker);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Drops bytes from the end (the trailing zeros an arithmetic coder may leave out).</summary>
|
||||||
|
public void Truncate(int length) => _length = length;
|
||||||
|
|
||||||
|
public byte this[int index] => _buffer[index];
|
||||||
|
|
||||||
|
public byte[] ToArray() => _buffer.AsSpan(0, _length).ToArray();
|
||||||
|
|
||||||
|
public void WriteTo(Stream stream) => stream.Write(_buffer, 0, _length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes Huffman codes and extra bits of an entropy-coded segment, stuffing a zero after each 0xFF.</summary>
|
||||||
|
internal sealed class JpegBitWriter
|
||||||
|
{
|
||||||
|
private readonly JpegOutput _output;
|
||||||
|
private ulong _bits;
|
||||||
|
private int _count;
|
||||||
|
|
||||||
|
public JpegBitWriter(JpegOutput output)
|
||||||
|
{
|
||||||
|
_output = output;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void WriteBits(int value, int count)
|
||||||
|
{
|
||||||
|
if (count == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_bits = (_bits << count) | ((uint)value & ((1u << count) - 1));
|
||||||
|
_count += count;
|
||||||
|
while (_count >= 8)
|
||||||
|
{
|
||||||
|
var b = (byte)(_bits >> (_count - 8));
|
||||||
|
_output.Add(b);
|
||||||
|
if (b == 0xFF)
|
||||||
|
{
|
||||||
|
_output.Add(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
_count -= 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
_bits &= (1UL << _count) - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void WriteSymbol(JpegHuffmanTable table, int symbol)
|
||||||
|
{
|
||||||
|
var size = table.Sizes[symbol];
|
||||||
|
if (size == 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"The Huffman table has no code for symbol 0x{symbol:X2}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteBits(table.Codes[symbol], size);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Symbol (run << 4 | category) and the low bits of <paramref name="value"/> (F.1.2.1, F.1.2.2).</summary>
|
||||||
|
public void WriteValue(JpegHuffmanTable table, int run, int value)
|
||||||
|
{
|
||||||
|
var magnitude = Math.Abs(value);
|
||||||
|
var category = magnitude == 0 ? 0 : BitOperations.Log2((uint)magnitude) + 1;
|
||||||
|
WriteSymbol(table, (run << 4) | category);
|
||||||
|
if (category > 0 && category < 16)
|
||||||
|
{
|
||||||
|
WriteBits(value < 0 ? value - 1 : value, category);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Pads the last byte with one bits (F.1.2.3).</summary>
|
||||||
|
public void Flush()
|
||||||
|
{
|
||||||
|
if (_count > 0)
|
||||||
|
{
|
||||||
|
WriteBits((1 << (8 - _count)) - 1, 8 - _count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Marker segments of T.81 Annex B and of JFIF, EXIF, XMP and ICC, for the encoders.</summary>
|
||||||
|
internal static class JpegSegments
|
||||||
|
{
|
||||||
|
private const int MaxPayload = 65533;
|
||||||
|
private const int IccChunk = 65519;
|
||||||
|
|
||||||
|
public static void WriteSegment(JpegOutput output, int marker, ReadOnlySpan<byte> payload)
|
||||||
|
{
|
||||||
|
if (payload.Length > MaxPayload)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"A JPEG segment holds at most {MaxPayload} bytes, not {payload.Length}.", nameof(payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Marker(marker);
|
||||||
|
output.Add((byte)((payload.Length + 2) >> 8));
|
||||||
|
output.Add((byte)(payload.Length + 2));
|
||||||
|
output.Add(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void WriteJfif(JpegOutput output) =>
|
||||||
|
WriteSegment(output, 0xE0, [(byte)'J', (byte)'F', (byte)'I', (byte)'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]);
|
||||||
|
|
||||||
|
public static void WriteMetadata(JpegOutput output, byte[]? exif, string? xmp, byte[]? icc, IReadOnlyList<string>? comments)
|
||||||
|
{
|
||||||
|
if (exif is not null)
|
||||||
|
{
|
||||||
|
ReadOnlySpan<byte> tiff = exif;
|
||||||
|
if (tiff.StartsWith("Exif\0\0"u8))
|
||||||
|
{
|
||||||
|
tiff = tiff[6..];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tiff.StartsWith("II*\0"u8) && !tiff.StartsWith("MM\0*"u8))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("EXIF must be a TIFF structure starting with «II*\\0» or «MM\\0*».", nameof(exif));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tiff.Length + 6 > MaxPayload)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"EXIF of {tiff.Length} bytes does not fit one APP1 segment.", nameof(exif));
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = new byte[tiff.Length + 6];
|
||||||
|
"Exif\0\0"u8.CopyTo(payload);
|
||||||
|
tiff.CopyTo(payload.AsSpan(6));
|
||||||
|
WriteSegment(output, 0xE1, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (xmp is not null)
|
||||||
|
{
|
||||||
|
var packet = Encoding.UTF8.GetBytes(xmp);
|
||||||
|
var ns = JpegFile.XmpNamespace;
|
||||||
|
if (packet.Length + ns.Length > MaxPayload)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"XMP of {packet.Length} bytes does not fit one APP1 segment (extended XMP is not written).", nameof(xmp));
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload = new byte[ns.Length + packet.Length];
|
||||||
|
ns.CopyTo(payload);
|
||||||
|
packet.CopyTo(payload, ns.Length);
|
||||||
|
WriteSegment(output, 0xE1, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (icc is not null)
|
||||||
|
{
|
||||||
|
var chunks = Math.Max(1, (icc.Length + IccChunk - 1) / IccChunk);
|
||||||
|
if (chunks > 255)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"An ICC profile of {icc.Length} bytes needs more than 255 APP2 chunks.", nameof(icc));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < chunks; i++)
|
||||||
|
{
|
||||||
|
var part = icc.AsSpan(i * IccChunk, Math.Min(IccChunk, icc.Length - (i * IccChunk)));
|
||||||
|
var payload = new byte[14 + part.Length];
|
||||||
|
"ICC_PROFILE\0"u8.CopyTo(payload);
|
||||||
|
payload[12] = (byte)(i + 1);
|
||||||
|
payload[13] = (byte)chunks;
|
||||||
|
part.CopyTo(payload.AsSpan(14));
|
||||||
|
WriteSegment(output, 0xE2, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (comments is not null)
|
||||||
|
{
|
||||||
|
foreach (var comment in comments)
|
||||||
|
{
|
||||||
|
WriteSegment(output, 0xFE, Encoding.UTF8.GetBytes(comment));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One DQT segment with every table (8-bit entries when all fit, 16-bit otherwise), zig-zag order.</summary>
|
||||||
|
public static void WriteQuantization(JpegOutput output, IReadOnlyList<ushort[]> tables)
|
||||||
|
{
|
||||||
|
var payload = new List<byte>();
|
||||||
|
var zigzag = JpegTables.ZigZag;
|
||||||
|
for (var id = 0; id < tables.Count; id++)
|
||||||
|
{
|
||||||
|
var table = tables[id];
|
||||||
|
var wide = false;
|
||||||
|
foreach (var q in table)
|
||||||
|
{
|
||||||
|
wide |= q > 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.Add((byte)((wide ? 0x10 : 0) | id));
|
||||||
|
for (var k = 0; k < 64; k++)
|
||||||
|
{
|
||||||
|
var q = table[zigzag[k]];
|
||||||
|
if (wide)
|
||||||
|
{
|
||||||
|
payload.Add((byte)(q >> 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.Add((byte)q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteSegment(output, 0xDB, payload.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void WriteFrame(JpegOutput output, int marker, int precision, int width, int height, IReadOnlyList<(int Id, int H, int V, int Table)> components)
|
||||||
|
{
|
||||||
|
var payload = new byte[6 + (3 * components.Count)];
|
||||||
|
payload[0] = (byte)precision;
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(1), (ushort)height);
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(3), (ushort)width);
|
||||||
|
payload[5] = (byte)components.Count;
|
||||||
|
for (var i = 0; i < components.Count; i++)
|
||||||
|
{
|
||||||
|
var c = components[i];
|
||||||
|
payload[6 + (3 * i)] = (byte)c.Id;
|
||||||
|
payload[7 + (3 * i)] = (byte)((c.H << 4) | c.V);
|
||||||
|
payload[8 + (3 * i)] = (byte)c.Table;
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteSegment(output, marker, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void WriteHuffman(JpegOutput output, int tableClass, int id, ReadOnlySpan<byte> counts, ReadOnlySpan<byte> values)
|
||||||
|
{
|
||||||
|
var payload = new byte[17 + values.Length];
|
||||||
|
payload[0] = (byte)((tableClass << 4) | id);
|
||||||
|
counts.CopyTo(payload.AsSpan(1));
|
||||||
|
values.CopyTo(payload.AsSpan(17));
|
||||||
|
WriteSegment(output, 0xC4, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void WriteRestartInterval(JpegOutput output, int interval) =>
|
||||||
|
WriteSegment(output, 0xDD, [(byte)(interval >> 8), (byte)interval]);
|
||||||
|
|
||||||
|
public static void WriteScan(JpegOutput output, IReadOnlyList<(int Id, int Dc, int Ac)> components, int ss, int se, int ah, int al)
|
||||||
|
{
|
||||||
|
var payload = new byte[4 + (2 * components.Count)];
|
||||||
|
payload[0] = (byte)components.Count;
|
||||||
|
for (var i = 0; i < components.Count; i++)
|
||||||
|
{
|
||||||
|
payload[1 + (2 * i)] = (byte)components[i].Id;
|
||||||
|
payload[2 + (2 * i)] = (byte)((components[i].Dc << 4) | components[i].Ac);
|
||||||
|
}
|
||||||
|
|
||||||
|
payload[^3] = (byte)ss;
|
||||||
|
payload[^2] = (byte)se;
|
||||||
|
payload[^1] = (byte)((ah << 4) | al);
|
||||||
|
WriteSegment(output, 0xDA, payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Arithmetic-coded scans: sequential (T.81 F.2.4), progressive (G.1.3, G.2) and lossless (H.1.2.3).</summary>
|
||||||
|
internal sealed partial class JpegFile
|
||||||
|
{
|
||||||
|
private const int DcStatistics = 64;
|
||||||
|
private const int AcStatistics = 256;
|
||||||
|
private const int LosslessStatistics = 158;
|
||||||
|
|
||||||
|
private int DecodeArithmeticScan(Scan scan, int start)
|
||||||
|
{
|
||||||
|
var decoder = new JpegArithmeticDecoder(Data, start);
|
||||||
|
var pass = PassOf(Progressive, scan);
|
||||||
|
var (perRow, total) = McuLayout(scan);
|
||||||
|
var single = scan.Components.Length == 1;
|
||||||
|
var zigzag = JpegTables.ZigZag;
|
||||||
|
ReadOnlySpan<byte> to8 = Precision == 12 ? Twelve.ToEight : [];
|
||||||
|
var temp = new short[64];
|
||||||
|
var dcStatistics = new byte[4 * DcStatistics];
|
||||||
|
var acStatistics = new byte[4 * AcStatistics];
|
||||||
|
|
||||||
|
for (var mcu = 0; mcu < total; mcu++)
|
||||||
|
{
|
||||||
|
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
|
||||||
|
{
|
||||||
|
decoder.Restart(SkipRestartMarker(decoder.Position));
|
||||||
|
Array.Clear(dcStatistics);
|
||||||
|
Array.Clear(acStatistics);
|
||||||
|
foreach (var c in scan.Components)
|
||||||
|
{
|
||||||
|
c.DcPredictor = 0;
|
||||||
|
c.DcContext = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var mx = mcu % perRow;
|
||||||
|
var my = mcu / perRow;
|
||||||
|
foreach (var c in scan.Components)
|
||||||
|
{
|
||||||
|
var wide = single ? 1 : c.H;
|
||||||
|
var high = single ? 1 : c.V;
|
||||||
|
var dc = dcStatistics.AsSpan(c.DcTable * DcStatistics, DcStatistics);
|
||||||
|
var ac = acStatistics.AsSpan(c.AcTable * AcStatistics, AcStatistics);
|
||||||
|
for (var v = 0; v < high; v++)
|
||||||
|
{
|
||||||
|
for (var h = 0; h < wide; h++)
|
||||||
|
{
|
||||||
|
var bx = single ? mx : (mx * c.H) + h;
|
||||||
|
var by = single ? my : (my * c.V) + v;
|
||||||
|
Span<short> block;
|
||||||
|
if (c.Coefficients is { } coefficients)
|
||||||
|
{
|
||||||
|
block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
block = temp;
|
||||||
|
block.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (pass)
|
||||||
|
{
|
||||||
|
case BlockPass.Sequential:
|
||||||
|
c.DcPredictor += DecodeDifference(ref decoder, dc, ref c.DcContext, 20, _dcL[c.DcTable], _dcU[c.DcTable]);
|
||||||
|
block[0] = (short)c.DcPredictor;
|
||||||
|
DecodeAcArithmetic(ref decoder, ac, _acK[c.AcTable], 1, 63, 0, block, zigzag);
|
||||||
|
if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh)
|
||||||
|
{
|
||||||
|
TransformBlock(c, plane, block, bx, by, to8);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case BlockPass.DcFirst:
|
||||||
|
c.DcPredictor += DecodeDifference(ref decoder, dc, ref c.DcContext, 20, _dcL[c.DcTable], _dcU[c.DcTable]);
|
||||||
|
block[0] = (short)(c.DcPredictor << scan.Al);
|
||||||
|
break;
|
||||||
|
case BlockPass.DcRefine:
|
||||||
|
if (decoder.DecodeFixed() != 0)
|
||||||
|
{
|
||||||
|
block[0] |= (short)(1 << scan.Al);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case BlockPass.AcFirst:
|
||||||
|
DecodeAcArithmetic(ref decoder, ac, _acK[c.AcTable], scan.Ss, scan.Se, scan.Al, block, zigzag);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
DecodeAcRefineArithmetic(ref decoder, ac, scan, block, zigzag);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return FindNextMarker(decoder.Position);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The five classes of a difference for conditioning (T.81 F.1.4.4.1.2): 0 zero, 1 small positive, 2 small
|
||||||
|
/// negative, 3 large positive, 4 large negative.
|
||||||
|
/// </summary>
|
||||||
|
private static int Classify(int difference, int low, int high)
|
||||||
|
{
|
||||||
|
var magnitude = Math.Abs(difference);
|
||||||
|
var lowerBound = low == 0 ? 0 : 1 << (low - 1);
|
||||||
|
if (magnitude <= lowerBound)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var negative = difference < 0 ? 1 : 0;
|
||||||
|
return magnitude <= 1 << high ? 1 + negative : 3 + negative;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decode_DC_DIFF with Decode_V (T.81 F.2.4.1, F.2.4.3): one difference of the DC model whose first four bins
|
||||||
|
/// start at <paramref name="context"/>, magnitude bins from <paramref name="x1"/>. The context of the next
|
||||||
|
/// difference is set from this one.
|
||||||
|
/// </summary>
|
||||||
|
private static int DecodeDifference(ref JpegArithmeticDecoder decoder, Span<byte> statistics, ref int context, int x1, int low, int high)
|
||||||
|
{
|
||||||
|
var s0 = context;
|
||||||
|
var difference = DecodeValue(ref decoder, statistics, s0, x1);
|
||||||
|
context = Classify(difference, low, high) * 4;
|
||||||
|
return difference;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int DecodeValue(ref JpegArithmeticDecoder decoder, Span<byte> statistics, int s0, int x1)
|
||||||
|
{
|
||||||
|
if (decoder.Decode(ref statistics[s0]) == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var sign = decoder.Decode(ref statistics[s0 + 1]);
|
||||||
|
var s = s0 + 2 + sign;
|
||||||
|
var magnitude = 0;
|
||||||
|
if (decoder.Decode(ref statistics[s]) != 0)
|
||||||
|
{
|
||||||
|
var bound = 1;
|
||||||
|
s = x1;
|
||||||
|
while (decoder.Decode(ref statistics[s]) != 0)
|
||||||
|
{
|
||||||
|
bound <<= 1;
|
||||||
|
if (bound == 0x8000)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
s++;
|
||||||
|
}
|
||||||
|
|
||||||
|
magnitude = DecodeMagnitudeBits(ref decoder, statistics, s + 14, bound);
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = magnitude + 1;
|
||||||
|
return sign != 0 ? -value : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decode the bits below the leading one of Sz (Figure F.9 reversed), all with bin <paramref name="s"/>.</summary>
|
||||||
|
private static int DecodeMagnitudeBits(ref JpegArithmeticDecoder decoder, Span<byte> statistics, int s, int bound)
|
||||||
|
{
|
||||||
|
var magnitude = bound;
|
||||||
|
for (var bit = bound >> 1; bit != 0; bit >>= 1)
|
||||||
|
{
|
||||||
|
if (decoder.Decode(ref statistics[s]) != 0)
|
||||||
|
{
|
||||||
|
magnitude |= bit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return magnitude;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>AC coefficients of a sequential block or of the first scan of a band (Figure F.5, Table F.5).</summary>
|
||||||
|
private static void DecodeAcArithmetic(ref JpegArithmeticDecoder decoder, Span<byte> statistics, int kx, int ss, int se, int al, Span<short> block, ReadOnlySpan<byte> zigzag)
|
||||||
|
{
|
||||||
|
for (var k = ss; k <= se; k++)
|
||||||
|
{
|
||||||
|
var se3 = 3 * (k - 1);
|
||||||
|
if (decoder.Decode(ref statistics[se3]) != 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (decoder.Decode(ref statistics[se3 + 1]) == 0)
|
||||||
|
{
|
||||||
|
se3 += 3;
|
||||||
|
k++;
|
||||||
|
if (k > se)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var sign = decoder.DecodeFixed();
|
||||||
|
var s = se3 + 2;
|
||||||
|
var magnitude = 0;
|
||||||
|
if (decoder.Decode(ref statistics[s]) != 0)
|
||||||
|
{
|
||||||
|
var bound = 1;
|
||||||
|
if (decoder.Decode(ref statistics[s]) != 0)
|
||||||
|
{
|
||||||
|
bound = 2;
|
||||||
|
s = k <= kx ? 189 : 217;
|
||||||
|
while (decoder.Decode(ref statistics[s]) != 0)
|
||||||
|
{
|
||||||
|
bound <<= 1;
|
||||||
|
if (bound == 0x8000)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
s++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
magnitude = DecodeMagnitudeBits(ref decoder, statistics, s + 14, bound);
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = magnitude + 1;
|
||||||
|
block[zigzag[k]] = (short)((sign != 0 ? -value : value) * (1 << al));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A later scan of successive approximation of a band (Figures G.10, G.11; Table G.2).</summary>
|
||||||
|
private static void DecodeAcRefineArithmetic(ref JpegArithmeticDecoder decoder, Span<byte> statistics, in Scan scan, Span<short> block, ReadOnlySpan<byte> zigzag)
|
||||||
|
{
|
||||||
|
var plus = 1 << scan.Al;
|
||||||
|
var minus = -1 << scan.Al;
|
||||||
|
|
||||||
|
// EOBx: one past the last coefficient made nonzero by the earlier scans.
|
||||||
|
var endOfBand = scan.Se;
|
||||||
|
while (endOfBand > 0 && block[zigzag[endOfBand]] == 0)
|
||||||
|
{
|
||||||
|
endOfBand--;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var k = scan.Ss; k <= scan.Se; k++)
|
||||||
|
{
|
||||||
|
var se3 = 3 * (k - 1);
|
||||||
|
if (k > endOfBand && decoder.Decode(ref statistics[se3]) != 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
ref var coefficient = ref block[zigzag[k]];
|
||||||
|
if (coefficient != 0)
|
||||||
|
{
|
||||||
|
if (decoder.Decode(ref statistics[se3 + 2]) != 0 && (coefficient & plus) == 0)
|
||||||
|
{
|
||||||
|
coefficient = (short)(coefficient >= 0 ? coefficient + plus : coefficient + minus);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (decoder.Decode(ref statistics[se3 + 1]) != 0)
|
||||||
|
{
|
||||||
|
coefficient = (short)(decoder.DecodeFixed() != 0 ? minus : plus);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
se3 += 3;
|
||||||
|
k++;
|
||||||
|
if (k > scan.Se)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int DecodeLosslessArithmeticScan(Scan scan, int start)
|
||||||
|
{
|
||||||
|
var decoder = new JpegArithmeticDecoder(Data, start);
|
||||||
|
var statistics = new byte[4 * LosslessStatistics];
|
||||||
|
var predictor = new LosslessPredictor(this, scan);
|
||||||
|
var (perRow, total) = McuLayout(scan);
|
||||||
|
var single = scan.Components.Length == 1;
|
||||||
|
|
||||||
|
// The class of the difference coded for every sample (T.81 H.1.2.3.1), for the contexts of its neighbours.
|
||||||
|
var classes = new byte[scan.Components.Length][];
|
||||||
|
for (var i = 0; i < scan.Components.Length; i++)
|
||||||
|
{
|
||||||
|
var c = scan.Components[i];
|
||||||
|
classes[i] = new byte[c.PlaneStride * c.PaddedUnitsHigh];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var mcu = 0; mcu < total; mcu++)
|
||||||
|
{
|
||||||
|
var mx = mcu % perRow;
|
||||||
|
var my = mcu / perRow;
|
||||||
|
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
|
||||||
|
{
|
||||||
|
decoder.Restart(SkipRestartMarker(decoder.Position));
|
||||||
|
Array.Clear(statistics);
|
||||||
|
predictor.Restart(my);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var ci = 0; ci < scan.Components.Length; ci++)
|
||||||
|
{
|
||||||
|
var c = scan.Components[ci];
|
||||||
|
var wide = single ? 1 : c.H;
|
||||||
|
var high = single ? 1 : c.V;
|
||||||
|
var stats = statistics.AsSpan(c.DcTable * LosslessStatistics, LosslessStatistics);
|
||||||
|
int low = _dcL[c.DcTable];
|
||||||
|
int up = _dcU[c.DcTable];
|
||||||
|
var cls = classes[ci];
|
||||||
|
for (var v = 0; v < high; v++)
|
||||||
|
{
|
||||||
|
for (var h = 0; h < wide; h++)
|
||||||
|
{
|
||||||
|
var x = single ? mx : (mx * c.H) + h;
|
||||||
|
var y = single ? my : (my * c.V) + v;
|
||||||
|
var i = (y * c.PlaneStride) + x;
|
||||||
|
|
||||||
|
// At the start of a line the left difference counts as zero, on the first line of the scan or
|
||||||
|
// of a restart interval the one above does.
|
||||||
|
var classA = x == 0 ? 0 : cls[i - 1];
|
||||||
|
var classB = predictor.IsFirstLine(ci, y) ? 0 : cls[i - c.PlaneStride];
|
||||||
|
var s0 = (20 * classB) + (4 * classA);
|
||||||
|
var x1 = classB >= 3 ? 129 : 100;
|
||||||
|
var difference = DecodeValue(ref decoder, stats, s0, x1);
|
||||||
|
cls[i] = (byte)Classify(difference, low, up);
|
||||||
|
predictor.Store(ci, c, x, y, difference);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
predictor.Finish();
|
||||||
|
return FindNextMarker(decoder.Position);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Huffman-coded scans: sequential (T.81 F.2), progressive (G.2) and lossless (H.2).</summary>
|
||||||
|
internal sealed partial class JpegFile
|
||||||
|
{
|
||||||
|
private enum BlockPass
|
||||||
|
{
|
||||||
|
Sequential,
|
||||||
|
DcFirst,
|
||||||
|
DcRefine,
|
||||||
|
AcFirst,
|
||||||
|
AcRefine,
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BlockPass PassOf(bool progressive, in Scan scan) =>
|
||||||
|
!progressive ? BlockPass.Sequential
|
||||||
|
: scan.Ss == 0 ? (scan.Ah == 0 ? BlockPass.DcFirst : BlockPass.DcRefine)
|
||||||
|
: scan.Ah == 0 ? BlockPass.AcFirst : BlockPass.AcRefine;
|
||||||
|
|
||||||
|
private int DecodeHuffmanScan(Scan scan, int start)
|
||||||
|
{
|
||||||
|
var data = Data;
|
||||||
|
var reader = new JpegBitReader(data, start);
|
||||||
|
var pass = PassOf(Progressive, scan);
|
||||||
|
var (perRow, total) = McuLayout(scan);
|
||||||
|
var single = scan.Components.Length == 1;
|
||||||
|
var zigzag = JpegTables.ZigZag;
|
||||||
|
ReadOnlySpan<byte> to8 = Precision == 12 ? Twelve.ToEight : [];
|
||||||
|
var temp = new short[64];
|
||||||
|
var dcTables = new JpegHuffmanTable?[scan.Components.Length];
|
||||||
|
var acTables = new JpegHuffmanTable?[scan.Components.Length];
|
||||||
|
for (var i = 0; i < scan.Components.Length; i++)
|
||||||
|
{
|
||||||
|
var c = scan.Components[i];
|
||||||
|
if (pass is BlockPass.Sequential or BlockPass.DcFirst)
|
||||||
|
{
|
||||||
|
dcTables[i] = DcTable(c.DcTable);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pass is BlockPass.Sequential or BlockPass.AcFirst or BlockPass.AcRefine)
|
||||||
|
{
|
||||||
|
acTables[i] = AcTable(c.AcTable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var eobRun = 0;
|
||||||
|
for (var mcu = 0; mcu < total; mcu++)
|
||||||
|
{
|
||||||
|
// Past the end the reader gives zero bits, which are valid codes: without this check a file cut after
|
||||||
|
// its headers would be decoded to the last MCU before failing. Padding once used stays used until a
|
||||||
|
// restart, so failing at the first MCU row that needed it changes only when the error comes.
|
||||||
|
if (mcu > 0 && mcu % perRow == 0 && reader.UsedPadding)
|
||||||
|
{
|
||||||
|
throw Truncated(reader.ReachedEnd, "blocco");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
|
||||||
|
{
|
||||||
|
if (reader.UsedPadding)
|
||||||
|
{
|
||||||
|
throw InterruptedScan();
|
||||||
|
}
|
||||||
|
|
||||||
|
reader.Seek(SkipRestartMarker(reader.Position));
|
||||||
|
foreach (var c in scan.Components)
|
||||||
|
{
|
||||||
|
c.DcPredictor = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
eobRun = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var mx = mcu % perRow;
|
||||||
|
var my = mcu / perRow;
|
||||||
|
for (var ci = 0; ci < scan.Components.Length; ci++)
|
||||||
|
{
|
||||||
|
var c = scan.Components[ci];
|
||||||
|
var wide = single ? 1 : c.H;
|
||||||
|
var high = single ? 1 : c.V;
|
||||||
|
for (var v = 0; v < high; v++)
|
||||||
|
{
|
||||||
|
for (var h = 0; h < wide; h++)
|
||||||
|
{
|
||||||
|
var bx = single ? mx : (mx * c.H) + h;
|
||||||
|
var by = single ? my : (my * c.V) + v;
|
||||||
|
Span<short> block;
|
||||||
|
if (c.Coefficients is { } coefficients)
|
||||||
|
{
|
||||||
|
block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
block = temp;
|
||||||
|
block.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (pass)
|
||||||
|
{
|
||||||
|
case BlockPass.Sequential:
|
||||||
|
DecodeSequential(ref reader, dcTables[ci]!, acTables[ci]!, ref c.DcPredictor, block, zigzag);
|
||||||
|
if (c.Plane is { } plane && bx < c.UnitsWide && by < c.UnitsHigh)
|
||||||
|
{
|
||||||
|
TransformBlock(c, plane, block, bx, by, to8);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case BlockPass.DcFirst:
|
||||||
|
{
|
||||||
|
var s = reader.DecodeHuffman(dcTables[ci]!);
|
||||||
|
if (s > 16)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
c.DcPredictor += reader.ReceiveExtend(s);
|
||||||
|
block[0] = (short)(c.DcPredictor << scan.Al);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case BlockPass.DcRefine:
|
||||||
|
if (reader.ReadBit() != 0)
|
||||||
|
{
|
||||||
|
block[0] |= (short)(1 << scan.Al);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case BlockPass.AcFirst:
|
||||||
|
DecodeAcFirst(ref reader, acTables[ci]!, scan, ref eobRun, block, zigzag);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
DecodeAcRefine(ref reader, acTables[ci]!, scan, ref eobRun, block, zigzag);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reader.UsedPadding)
|
||||||
|
{
|
||||||
|
throw Truncated(reader.ReachedEnd, "blocco");
|
||||||
|
}
|
||||||
|
|
||||||
|
return FindNextMarker(reader.Position);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The error for a scan that needed bits it did not have: cut short (<paramref name="reachedEnd"/>) or interrupted by a marker.</summary>
|
||||||
|
private static ImageDecodeException Truncated(bool reachedEnd, string unit) =>
|
||||||
|
reachedEnd ? new ImageDecodeException($"JPEG troncato: i dati compressi finiscono prima dell'ultimo {unit}.") : InterruptedScan();
|
||||||
|
|
||||||
|
private static ImageDecodeException InterruptedScan() =>
|
||||||
|
new("JPEG danneggiato: i dati compressi di una scansione si interrompono prima dell'ultimo blocco.");
|
||||||
|
|
||||||
|
private static ImageDecodeException BadValue() => new("JPEG danneggiato: valore compresso non valido.");
|
||||||
|
|
||||||
|
private static void DecodeSequential(ref JpegBitReader reader, JpegHuffmanTable dc, JpegHuffmanTable ac, ref int predictor, Span<short> block, ReadOnlySpan<byte> zigzag)
|
||||||
|
{
|
||||||
|
var s = reader.DecodeHuffman(dc);
|
||||||
|
if (s > 16)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
predictor += reader.ReceiveExtend(s);
|
||||||
|
block[0] = (short)predictor;
|
||||||
|
for (var k = 1; k < 64; k++)
|
||||||
|
{
|
||||||
|
var rs = reader.DecodeHuffman(ac);
|
||||||
|
var run = rs >> 4;
|
||||||
|
s = rs & 15;
|
||||||
|
if (s == 0)
|
||||||
|
{
|
||||||
|
if (run != 15)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
k += 15;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
k += run;
|
||||||
|
if (k > 63)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
block[zigzag[k]] = (short)reader.ReceiveExtend(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DecodeAcFirst(ref JpegBitReader reader, JpegHuffmanTable ac, in Scan scan, ref int eobRun, Span<short> block, ReadOnlySpan<byte> zigzag)
|
||||||
|
{
|
||||||
|
if (eobRun > 0)
|
||||||
|
{
|
||||||
|
eobRun--;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var k = scan.Ss; k <= scan.Se; k++)
|
||||||
|
{
|
||||||
|
var rs = reader.DecodeHuffman(ac);
|
||||||
|
var run = rs >> 4;
|
||||||
|
var s = rs & 15;
|
||||||
|
if (s == 0)
|
||||||
|
{
|
||||||
|
if (run < 15)
|
||||||
|
{
|
||||||
|
eobRun = (1 << run) - 1;
|
||||||
|
if (run > 0)
|
||||||
|
{
|
||||||
|
eobRun += reader.ReadBits(run);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
k += 15;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
k += run;
|
||||||
|
if (k > scan.Se)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
block[zigzag[k]] = (short)(reader.ReceiveExtend(s) * (1 << scan.Al));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DecodeAcRefine(ref JpegBitReader reader, JpegHuffmanTable ac, in Scan scan, ref int eobRun, Span<short> block, ReadOnlySpan<byte> zigzag)
|
||||||
|
{
|
||||||
|
var plus = 1 << scan.Al;
|
||||||
|
var minus = -1 << scan.Al;
|
||||||
|
var k = scan.Ss;
|
||||||
|
if (eobRun == 0)
|
||||||
|
{
|
||||||
|
for (; k <= scan.Se; k++)
|
||||||
|
{
|
||||||
|
var rs = reader.DecodeHuffman(ac);
|
||||||
|
var run = rs >> 4;
|
||||||
|
var s = rs & 15;
|
||||||
|
var value = 0;
|
||||||
|
if (s != 0)
|
||||||
|
{
|
||||||
|
if (s != 1)
|
||||||
|
{
|
||||||
|
throw BadValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
value = reader.ReadBit() != 0 ? plus : minus;
|
||||||
|
}
|
||||||
|
else if (run != 15)
|
||||||
|
{
|
||||||
|
eobRun = 1 << run;
|
||||||
|
if (run > 0)
|
||||||
|
{
|
||||||
|
eobRun += reader.ReadBits(run);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip `run` coefficients that are still zero, refining the nonzero ones met on the way, then place the
|
||||||
|
// new coefficient (none for ZRL) on the next zero.
|
||||||
|
for (; k <= scan.Se; k++)
|
||||||
|
{
|
||||||
|
ref var coefficient = ref block[zigzag[k]];
|
||||||
|
if (coefficient != 0)
|
||||||
|
{
|
||||||
|
Refine(ref reader, ref coefficient, plus, minus);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (run == 0)
|
||||||
|
{
|
||||||
|
if (value != 0)
|
||||||
|
{
|
||||||
|
coefficient = (short)value;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
run--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (eobRun > 0)
|
||||||
|
{
|
||||||
|
// Inside an end-of-band run: only the coefficients that are already nonzero get a correction bit.
|
||||||
|
for (; k <= scan.Se; k++)
|
||||||
|
{
|
||||||
|
ref var coefficient = ref block[zigzag[k]];
|
||||||
|
if (coefficient != 0)
|
||||||
|
{
|
||||||
|
Refine(ref reader, ref coefficient, plus, minus);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
eobRun--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Refine(ref JpegBitReader reader, ref short coefficient, int plus, int minus)
|
||||||
|
{
|
||||||
|
if (reader.ReadBit() != 0 && (coefficient & plus) == 0)
|
||||||
|
{
|
||||||
|
coefficient = (short)(coefficient >= 0 ? coefficient + plus : coefficient + minus);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int DecodeLosslessHuffmanScan(Scan scan, int start)
|
||||||
|
{
|
||||||
|
var reader = new JpegBitReader(Data, start);
|
||||||
|
var tables = new JpegHuffmanTable[scan.Components.Length];
|
||||||
|
for (var i = 0; i < tables.Length; i++)
|
||||||
|
{
|
||||||
|
tables[i] = DcTable(scan.Components[i].DcTable);
|
||||||
|
}
|
||||||
|
|
||||||
|
var predictor = new LosslessPredictor(this, scan);
|
||||||
|
var (perRow, total) = McuLayout(scan);
|
||||||
|
var single = scan.Components.Length == 1;
|
||||||
|
for (var mcu = 0; mcu < total; mcu++)
|
||||||
|
{
|
||||||
|
var mx = mcu % perRow;
|
||||||
|
var my = mcu / perRow;
|
||||||
|
if (mx == 0 && mcu > 0 && reader.UsedPadding)
|
||||||
|
{
|
||||||
|
// As in DecodeHuffmanScan: fail at the first MCU row that ran out of data, not after the last one.
|
||||||
|
throw Truncated(reader.ReachedEnd, "campione");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_restartInterval > 0 && mcu > 0 && mcu % _restartInterval == 0)
|
||||||
|
{
|
||||||
|
if (reader.UsedPadding)
|
||||||
|
{
|
||||||
|
throw InterruptedScan();
|
||||||
|
}
|
||||||
|
|
||||||
|
reader.Seek(SkipRestartMarker(reader.Position));
|
||||||
|
predictor.Restart(my);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var ci = 0; ci < scan.Components.Length; ci++)
|
||||||
|
{
|
||||||
|
var c = scan.Components[ci];
|
||||||
|
var wide = single ? 1 : c.H;
|
||||||
|
var high = single ? 1 : c.V;
|
||||||
|
for (var v = 0; v < high; v++)
|
||||||
|
{
|
||||||
|
for (var h = 0; h < wide; h++)
|
||||||
|
{
|
||||||
|
var x = single ? mx : (mx * c.H) + h;
|
||||||
|
var y = single ? my : (my * c.V) + v;
|
||||||
|
var s = reader.DecodeHuffman(tables[ci]);
|
||||||
|
int difference = s switch
|
||||||
|
{
|
||||||
|
0 => 0,
|
||||||
|
16 => 32768,
|
||||||
|
> 16 => throw BadValue(),
|
||||||
|
_ => reader.ReceiveExtend(s),
|
||||||
|
};
|
||||||
|
predictor.Store(ci, c, x, y, difference);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reader.UsedPadding)
|
||||||
|
{
|
||||||
|
throw Truncated(reader.ReachedEnd, "campione");
|
||||||
|
}
|
||||||
|
|
||||||
|
predictor.Finish();
|
||||||
|
return FindNextMarker(reader.Position);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The predictors of T.81 H.1.2.1 and the samples they reconstruct.</summary>
|
||||||
|
private sealed class LosslessPredictor
|
||||||
|
{
|
||||||
|
private readonly JpegFile _file;
|
||||||
|
private readonly Scan _scan;
|
||||||
|
private readonly int[] _firstRow;
|
||||||
|
private readonly int _initial;
|
||||||
|
private readonly bool _single;
|
||||||
|
|
||||||
|
public LosslessPredictor(JpegFile file, Scan scan)
|
||||||
|
{
|
||||||
|
_file = file;
|
||||||
|
_scan = scan;
|
||||||
|
_firstRow = new int[scan.Components.Length];
|
||||||
|
_initial = 1 << (file.Precision - scan.Al - 1);
|
||||||
|
_single = scan.Components.Length == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A restart interval starts at MCU row <paramref name="mcuRow"/>: its first line predicts like the first line of the scan.</summary>
|
||||||
|
public void Restart(int mcuRow)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < _scan.Components.Length; i++)
|
||||||
|
{
|
||||||
|
_firstRow[i] = _single ? mcuRow : mcuRow * _scan.Components[i].V;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether row <paramref name="y"/> of scan component <paramref name="ci"/> is the first line of the scan or restart interval.</summary>
|
||||||
|
public bool IsFirstLine(int ci, int y) => y == _firstRow[ci];
|
||||||
|
|
||||||
|
/// <summary>The prediction for (x, y) of <paramref name="c"/>, the scan's component <paramref name="ci"/>.</summary>
|
||||||
|
public int Predict(int ci, JpegComponent c, int x, int y)
|
||||||
|
{
|
||||||
|
var samples = c.Samples!;
|
||||||
|
var stride = c.PlaneStride;
|
||||||
|
var i = (y * stride) + x;
|
||||||
|
if (y == _firstRow[ci])
|
||||||
|
{
|
||||||
|
return x == 0 ? _initial : samples[i - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (x == 0)
|
||||||
|
{
|
||||||
|
return samples[i - stride];
|
||||||
|
}
|
||||||
|
|
||||||
|
int a = samples[i - 1];
|
||||||
|
int b = samples[i - stride];
|
||||||
|
int cc = samples[i - stride - 1];
|
||||||
|
return _scan.Ss switch
|
||||||
|
{
|
||||||
|
1 => a,
|
||||||
|
2 => b,
|
||||||
|
3 => cc,
|
||||||
|
4 => a + b - cc,
|
||||||
|
5 => a + ((b - cc) >> 1),
|
||||||
|
6 => b + ((a - cc) >> 1),
|
||||||
|
_ => (a + b) >> 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Store(int ci, JpegComponent c, int x, int y, int difference)
|
||||||
|
{
|
||||||
|
var predicted = Predict(ci, c, x, y);
|
||||||
|
c.Samples![(y * c.PlaneStride) + x] = (ushort)((predicted + difference) & 0xFFFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Undoes the point transform and writes the 8-bit planes.</summary>
|
||||||
|
public void Finish() => _file.FinishLossless(_scan);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FinishLossless(in Scan scan)
|
||||||
|
{
|
||||||
|
if (_mode != Mode.Pixels)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var max = (1 << Precision) - 1;
|
||||||
|
var shift = scan.Al;
|
||||||
|
foreach (var c in scan.Components)
|
||||||
|
{
|
||||||
|
var samples = c.Samples!;
|
||||||
|
var plane = c.Plane!;
|
||||||
|
for (var y = 0; y < c.Height; y++)
|
||||||
|
{
|
||||||
|
var row = y * c.PlaneStride;
|
||||||
|
for (var x = 0; x < c.Width; x++)
|
||||||
|
{
|
||||||
|
var value = Math.Min(samples[row + x] << shift, max);
|
||||||
|
plane[row + x] = Precision == 8 ? (byte)value : (byte)(((value * 255L) + (max >> 1)) / max);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>From the component planes to RGBA: upsampling of the chroma and colour conversion.</summary>
|
||||||
|
internal sealed partial class JpegFile
|
||||||
|
{
|
||||||
|
/// <summary>The colour space of the components, as decoders choose it (JFIF, Adobe APP14, component identifiers).</summary>
|
||||||
|
internal enum ColorModel
|
||||||
|
{
|
||||||
|
Grey,
|
||||||
|
YCbCr,
|
||||||
|
Rgb,
|
||||||
|
Cmyk,
|
||||||
|
Ycck,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal ColorModel Colors
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (Components.Length == 1)
|
||||||
|
{
|
||||||
|
return ColorModel.Grey;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Components.Length == 4)
|
||||||
|
{
|
||||||
|
return _adobeTransform == 2 ? ColorModel.Ycck : ColorModel.Cmyk;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_jfif)
|
||||||
|
{
|
||||||
|
return ColorModel.YCbCr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_adobeTransform >= 0)
|
||||||
|
{
|
||||||
|
return _adobeTransform == 0 ? ColorModel.Rgb : ColorModel.YCbCr;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Components[0].Id == 'R' && Components[1].Id == 'G' && Components[2].Id == 'B' ? ColorModel.Rgb : ColorModel.YCbCr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public RgbaImage Render(bool pooled)
|
||||||
|
{
|
||||||
|
var width = OutputWidth;
|
||||||
|
var height = OutputHeight;
|
||||||
|
var image = RgbaImage.Create(width, height, _limits, pooled);
|
||||||
|
var buffers = new byte[Components.Length][];
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (var i = 0; i < buffers.Length; i++)
|
||||||
|
{
|
||||||
|
buffers[i] = ArrayPool<byte>.Shared.Rent(width + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var model = Colors;
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
var output = image.GetRow(y);
|
||||||
|
var c0 = UpsampleRow(Components[0], y, buffers[0]);
|
||||||
|
switch (model)
|
||||||
|
{
|
||||||
|
case ColorModel.Grey:
|
||||||
|
WriteGrey(c0, output);
|
||||||
|
break;
|
||||||
|
case ColorModel.YCbCr:
|
||||||
|
WriteYCbCr(c0, UpsampleRow(Components[1], y, buffers[1]), UpsampleRow(Components[2], y, buffers[2]), output);
|
||||||
|
break;
|
||||||
|
case ColorModel.Rgb:
|
||||||
|
WriteRgb(c0, UpsampleRow(Components[1], y, buffers[1]), UpsampleRow(Components[2], y, buffers[2]), output);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
WriteCmyk(
|
||||||
|
c0,
|
||||||
|
UpsampleRow(Components[1], y, buffers[1]),
|
||||||
|
UpsampleRow(Components[2], y, buffers[2]),
|
||||||
|
UpsampleRow(Components[3], y, buffers[3]),
|
||||||
|
output,
|
||||||
|
model == ColorModel.Ycck);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
foreach (var buffer in buffers)
|
||||||
|
{
|
||||||
|
if (buffer is not null)
|
||||||
|
{
|
||||||
|
ArrayPool<byte>.Shared.Return(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Row <paramref name="y"/> of the image for component <paramref name="c"/>, <see cref="OutputWidth"/> samples. A ratio
|
||||||
|
/// of 2 to the largest sampling factor uses the triangular ("fancy") filter of the JFIF siting: each output sample
|
||||||
|
/// weighs 3/4 the nearest input sample and 1/4 the next one, the edges repeating; other ratios repeat samples.
|
||||||
|
/// </summary>
|
||||||
|
private ReadOnlySpan<byte> UpsampleRow(JpegComponent c, int y, byte[] buffer)
|
||||||
|
{
|
||||||
|
var plane = c.Plane!;
|
||||||
|
var stride = c.PlaneStride;
|
||||||
|
var width = OutputWidth;
|
||||||
|
if (c.H == MaxH && c.V == MaxV)
|
||||||
|
{
|
||||||
|
return plane.AsSpan(y * stride, width);
|
||||||
|
}
|
||||||
|
|
||||||
|
var output = buffer.AsSpan(0, width);
|
||||||
|
var componentWidth = Reduce(c.Width);
|
||||||
|
var lastX = componentWidth - 1;
|
||||||
|
var lastY = Reduce(c.Height) - 1;
|
||||||
|
var integral = MaxH % c.H == 0 && MaxV % c.V == 0;
|
||||||
|
var hr = MaxH / c.H;
|
||||||
|
var vr = MaxV / c.V;
|
||||||
|
if (!integral || hr > 2 || vr > 2)
|
||||||
|
{
|
||||||
|
var sy = Math.Min((int)((long)y * c.V / MaxV), lastY);
|
||||||
|
var row = plane.AsSpan(sy * stride, componentWidth);
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
output[x] = row[Math.Min((int)((long)x * c.H / MaxH), lastX)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (vr == 1)
|
||||||
|
{
|
||||||
|
// hr == 2.
|
||||||
|
var row = plane.AsSpan(y * stride, componentWidth);
|
||||||
|
for (var i = 0; i <= lastX; i++)
|
||||||
|
{
|
||||||
|
var three = row[i] * 3;
|
||||||
|
var o = 2 * i;
|
||||||
|
output[o] = (byte)((three + row[Math.Max(i - 1, 0)] + 1) >> 2);
|
||||||
|
if (o + 1 < width)
|
||||||
|
{
|
||||||
|
output[o + 1] = (byte)((three + row[Math.Min(i + 1, lastX)] + 2) >> 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
var cy = y >> 1;
|
||||||
|
var farY = (y & 1) == 0 ? Math.Max(cy - 1, 0) : Math.Min(cy + 1, lastY);
|
||||||
|
var near = plane.AsSpan(cy * stride, componentWidth);
|
||||||
|
var far = plane.AsSpan(farY * stride, componentWidth);
|
||||||
|
if (hr == 1)
|
||||||
|
{
|
||||||
|
var bias = (y & 1) == 0 ? 1 : 2;
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
output[x] = (byte)(((near[x] * 3) + far[x] + bias) >> 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
// h2v2: column sums first, then the horizontal triangle (rounding 8 and 7 alternate).
|
||||||
|
var previous = (near[0] * 3) + far[0];
|
||||||
|
var current = previous;
|
||||||
|
for (var i = 0; i <= lastX; i++)
|
||||||
|
{
|
||||||
|
var next = i < lastX ? (near[i + 1] * 3) + far[i + 1] : current;
|
||||||
|
var o = 2 * i;
|
||||||
|
output[o] = (byte)(((current * 3) + previous + 8) >> 4);
|
||||||
|
if (o + 1 < width)
|
||||||
|
{
|
||||||
|
output[o + 1] = (byte)(((current * 3) + next + 7) >> 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
previous = current;
|
||||||
|
current = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteGrey(ReadOnlySpan<byte> grey, Span<byte> output)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < grey.Length; x++)
|
||||||
|
{
|
||||||
|
var o = x * 4;
|
||||||
|
var g = grey[x];
|
||||||
|
output[o] = g;
|
||||||
|
output[o + 1] = g;
|
||||||
|
output[o + 2] = g;
|
||||||
|
output[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteRgb(ReadOnlySpan<byte> r, ReadOnlySpan<byte> g, ReadOnlySpan<byte> b, Span<byte> output)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < r.Length; x++)
|
||||||
|
{
|
||||||
|
var o = x * 4;
|
||||||
|
output[o] = r[x];
|
||||||
|
output[o + 1] = g[x];
|
||||||
|
output[o + 2] = b[x];
|
||||||
|
output[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteYCbCr(ReadOnlySpan<byte> luma, ReadOnlySpan<byte> cb, ReadOnlySpan<byte> cr, Span<byte> output)
|
||||||
|
{
|
||||||
|
var tables = YCbCrTables.Instance;
|
||||||
|
for (var x = 0; x < luma.Length; x++)
|
||||||
|
{
|
||||||
|
var o = x * 4;
|
||||||
|
int y = luma[x];
|
||||||
|
int blue = cb[x];
|
||||||
|
int red = cr[x];
|
||||||
|
output[o] = Clamp(y + tables.CrToR[red]);
|
||||||
|
output[o + 1] = Clamp(y + ((tables.CbToG[blue] + tables.CrToG[red]) >> 16));
|
||||||
|
output[o + 2] = Clamp(y + tables.CbToB[blue]);
|
||||||
|
output[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// CMYK as Adobe writes it (inverted: 255 is no ink) to RGB, R = C × K / 255 and so on; YCCK first gives the
|
||||||
|
/// inverted C, M, Y from its YCbCr part (T.81 has no colour spaces: this is the Adobe convention).
|
||||||
|
/// </summary>
|
||||||
|
private static void WriteCmyk(ReadOnlySpan<byte> c0, ReadOnlySpan<byte> c1, ReadOnlySpan<byte> c2, ReadOnlySpan<byte> k, Span<byte> output, bool ycck)
|
||||||
|
{
|
||||||
|
var tables = YCbCrTables.Instance;
|
||||||
|
for (var x = 0; x < c0.Length; x++)
|
||||||
|
{
|
||||||
|
int c;
|
||||||
|
int m;
|
||||||
|
int yellow;
|
||||||
|
if (ycck)
|
||||||
|
{
|
||||||
|
int y = c0[x];
|
||||||
|
int blue = c1[x];
|
||||||
|
int red = c2[x];
|
||||||
|
c = 255 - Clamp(y + tables.CrToR[red]);
|
||||||
|
m = 255 - Clamp(y + ((tables.CbToG[blue] + tables.CrToG[red]) >> 16));
|
||||||
|
yellow = 255 - Clamp(y + tables.CbToB[blue]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
c = c0[x];
|
||||||
|
m = c1[x];
|
||||||
|
yellow = c2[x];
|
||||||
|
}
|
||||||
|
|
||||||
|
int key = k[x];
|
||||||
|
var o = x * 4;
|
||||||
|
output[o] = MulDiv255(c, key);
|
||||||
|
output[o + 1] = MulDiv255(m, key);
|
||||||
|
output[o + 2] = MulDiv255(yellow, key);
|
||||||
|
output[o + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static byte MulDiv255(int a, int b)
|
||||||
|
{
|
||||||
|
var t = (a * b) + 128;
|
||||||
|
return (byte)((t + (t >> 8)) >> 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static byte Clamp(int value) => (uint)value <= 255 ? (byte)value : value < 0 ? (byte)0 : (byte)255;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// YCbCr to RGB of JFIF (ITU-T T.871): R = Y + 1.402 (Cr − 128), G = Y − 0.344136 (Cb − 128) − 0.714136 (Cr − 128),
|
||||||
|
/// B = Y + 1.772 (Cb − 128), in 16-bit fixed point with rounding.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class YCbCrTables
|
||||||
|
{
|
||||||
|
public static readonly YCbCrTables Instance = new();
|
||||||
|
|
||||||
|
private YCbCrTables()
|
||||||
|
{
|
||||||
|
const int one = 1 << 16;
|
||||||
|
const int half = 1 << 15;
|
||||||
|
for (var i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
var x = i - 128;
|
||||||
|
CrToR[i] = ((Fix(1.402) * x) + half) >> 16;
|
||||||
|
CbToB[i] = ((Fix(1.772) * x) + half) >> 16;
|
||||||
|
CrToG[i] = -Fix(0.714136) * x;
|
||||||
|
CbToG[i] = (-Fix(0.344136) * x) + half;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int Fix(double value) => (int)((value * one) + 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] CrToR { get; } = new int[256];
|
||||||
|
|
||||||
|
public int[] CbToB { get; } = new int[256];
|
||||||
|
|
||||||
|
public int[] CrToG { get; } = new int[256];
|
||||||
|
|
||||||
|
public int[] CbToG { get; } = new int[256];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A Huffman table of T.81 (Annex C): the canonical codes built from the counts per length, with a lookup of the
|
||||||
|
/// first <see cref="LookupBits"/> bits for decoding and the code of every symbol for encoding.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class JpegHuffmanTable
|
||||||
|
{
|
||||||
|
/// <summary>Bits looked up at once; longer codes take the slow path of T.81 F.2.2.3.</summary>
|
||||||
|
public const int LookupBits = 9;
|
||||||
|
|
||||||
|
private JpegHuffmanTable(byte[] counts, byte[] values)
|
||||||
|
{
|
||||||
|
Counts = counts;
|
||||||
|
Values = values;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Codes of each length 1-16.</summary>
|
||||||
|
public byte[] Counts { get; }
|
||||||
|
|
||||||
|
/// <summary>The symbols, in code order.</summary>
|
||||||
|
public byte[] Values { get; }
|
||||||
|
|
||||||
|
/// <summary>For each value of the next <see cref="LookupBits"/> bits: (length << 8) | symbol, or 0.</summary>
|
||||||
|
public ushort[] Lookup { get; } = new ushort[1 << LookupBits];
|
||||||
|
|
||||||
|
/// <summary>Largest code of each length (index 1-16), -1 when there is none.</summary>
|
||||||
|
public int[] MaxCode { get; } = new int[17];
|
||||||
|
|
||||||
|
/// <summary>For each length, the index in <see cref="Values"/> of its first code minus that code.</summary>
|
||||||
|
public int[] ValueOffset { get; } = new int[17];
|
||||||
|
|
||||||
|
/// <summary>The code of each symbol (encoding).</summary>
|
||||||
|
public ushort[] Codes { get; } = new ushort[256];
|
||||||
|
|
||||||
|
/// <summary>The length of the code of each symbol, 0 when the table has no code for it (encoding).</summary>
|
||||||
|
public byte[] Sizes { get; } = new byte[256];
|
||||||
|
|
||||||
|
/// <summary>Builds a table from the 16 counts and the symbols of a DHT segment.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The counts describe more codes than fit, or do not match the symbols.</exception>
|
||||||
|
public static JpegHuffmanTable Build(ReadOnlySpan<byte> counts, ReadOnlySpan<byte> values)
|
||||||
|
{
|
||||||
|
if (counts.Length != 16)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("Tabella di Huffman JPEG non valida.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var total = 0;
|
||||||
|
foreach (var count in counts)
|
||||||
|
{
|
||||||
|
total += count;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (total > 256 || total != values.Length)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("Tabella di Huffman JPEG non valida: troppi simboli.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var table = new JpegHuffmanTable(counts.ToArray(), values.ToArray());
|
||||||
|
var code = 0;
|
||||||
|
var k = 0;
|
||||||
|
for (var length = 1; length <= 16; length++)
|
||||||
|
{
|
||||||
|
int count = counts[length - 1];
|
||||||
|
if (code + count > 1 << length)
|
||||||
|
{
|
||||||
|
// Checked before any entry is written: an oversubscribed length would otherwise index past the lookup.
|
||||||
|
throw new ImageDecodeException("Tabella di Huffman JPEG non valida: i codici non stanno nella loro lunghezza.");
|
||||||
|
}
|
||||||
|
|
||||||
|
table.ValueOffset[length] = k - code;
|
||||||
|
for (var i = 0; i < count; i++, k++, code++)
|
||||||
|
{
|
||||||
|
var symbol = values[k];
|
||||||
|
if (table.Sizes[symbol] == 0)
|
||||||
|
{
|
||||||
|
table.Codes[symbol] = (ushort)code;
|
||||||
|
table.Sizes[symbol] = (byte)length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (length <= LookupBits)
|
||||||
|
{
|
||||||
|
var shift = LookupBits - length;
|
||||||
|
var first = code << shift;
|
||||||
|
var entry = (ushort)((length << 8) | symbol);
|
||||||
|
table.Lookup.AsSpan(first, 1 << shift).Fill(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table.MaxCode[length] = count == 0 ? -1 : code - 1;
|
||||||
|
code <<= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the bits of an entropy-coded segment (T.81 F.2.2.5): undoes the 0xFF 0x00 stuffing and stops at the first
|
||||||
|
/// marker or at the end of the data, after which it gives zero bits and counts them, so that a scan that needed bits
|
||||||
|
/// it did not have can be told apart from one that ended on its last byte.
|
||||||
|
/// </summary>
|
||||||
|
internal ref struct JpegBitReader
|
||||||
|
{
|
||||||
|
private readonly ReadOnlySpan<byte> _data;
|
||||||
|
private int _position;
|
||||||
|
private ulong _bits;
|
||||||
|
private int _count;
|
||||||
|
private int _padBits;
|
||||||
|
|
||||||
|
public JpegBitReader(ReadOnlySpan<byte> data, int position)
|
||||||
|
{
|
||||||
|
_data = data;
|
||||||
|
_position = position;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Position of the next byte not yet read.</summary>
|
||||||
|
public readonly int Position => _position;
|
||||||
|
|
||||||
|
/// <summary>Whether the reader ran out of data (not at a marker).</summary>
|
||||||
|
public bool ReachedEnd { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Whether a decoded symbol used bits past the end of the segment.</summary>
|
||||||
|
public readonly bool UsedPadding => _padBits > _count;
|
||||||
|
|
||||||
|
/// <summary>Drops the bits of the current byte and those buffered, for a restart marker or the end of a scan.</summary>
|
||||||
|
public void Reset()
|
||||||
|
{
|
||||||
|
_bits = 0;
|
||||||
|
_count = 0;
|
||||||
|
_padBits = 0;
|
||||||
|
ReachedEnd = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Moves to <paramref name="position"/>, with no buffered bits.</summary>
|
||||||
|
public void Seek(int position)
|
||||||
|
{
|
||||||
|
Reset();
|
||||||
|
_position = position;
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public int ReadBit()
|
||||||
|
{
|
||||||
|
if (_count < 1)
|
||||||
|
{
|
||||||
|
Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
var bit = (int)(_bits >> 63);
|
||||||
|
_bits <<= 1;
|
||||||
|
_count--;
|
||||||
|
return bit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The next <paramref name="n"/> bits (0-16) as an unsigned number.</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public int ReadBits(int n)
|
||||||
|
{
|
||||||
|
if (n == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_count < n)
|
||||||
|
{
|
||||||
|
Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = (int)(_bits >> (64 - n));
|
||||||
|
_bits <<= n;
|
||||||
|
_count -= n;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>RECEIVE and EXTEND of T.81 F.2.2.1: <paramref name="s"/> bits as a signed value of category s.</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public int ReceiveExtend(int s)
|
||||||
|
{
|
||||||
|
if (s == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = ReadBits(s);
|
||||||
|
return value < 1 << (s - 1) ? value - (1 << s) + 1 : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes one symbol with <paramref name="table"/>.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The bits are no code of the table.</exception>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public int DecodeHuffman(JpegHuffmanTable table)
|
||||||
|
{
|
||||||
|
if (_count < 16)
|
||||||
|
{
|
||||||
|
Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
var entry = table.Lookup[(int)(_bits >> (64 - JpegHuffmanTable.LookupBits))];
|
||||||
|
if (entry != 0)
|
||||||
|
{
|
||||||
|
var length = entry >> 8;
|
||||||
|
_bits <<= length;
|
||||||
|
_count -= length;
|
||||||
|
return entry & 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DecodeSlow(table);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int DecodeSlow(JpegHuffmanTable table)
|
||||||
|
{
|
||||||
|
for (var length = JpegHuffmanTable.LookupBits + 1; length <= 16; length++)
|
||||||
|
{
|
||||||
|
var code = (int)(_bits >> (64 - length));
|
||||||
|
if (code <= table.MaxCode[length])
|
||||||
|
{
|
||||||
|
_bits <<= length;
|
||||||
|
_count -= length;
|
||||||
|
return table.Values[table.ValueOffset[length] + code];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ImageDecodeException("JPEG danneggiato: un codice di Huffman non esiste nella tabella.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Fill()
|
||||||
|
{
|
||||||
|
while (_count <= 56)
|
||||||
|
{
|
||||||
|
int value;
|
||||||
|
if (_padBits > 0)
|
||||||
|
{
|
||||||
|
value = 0;
|
||||||
|
_padBits += 8;
|
||||||
|
}
|
||||||
|
else if (_position >= _data.Length)
|
||||||
|
{
|
||||||
|
ReachedEnd = true;
|
||||||
|
value = 0;
|
||||||
|
_padBits = 8;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
value = _data[_position];
|
||||||
|
if (value == 0xFF)
|
||||||
|
{
|
||||||
|
if (_position + 1 < _data.Length && _data[_position + 1] == 0)
|
||||||
|
{
|
||||||
|
_position += 2;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// A marker (or the end of the data right after 0xFF): no more bits in this segment.
|
||||||
|
if (_position + 1 >= _data.Length)
|
||||||
|
{
|
||||||
|
ReachedEnd = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
value = 0;
|
||||||
|
_padBits = 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_position++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_bits |= (ulong)value << (56 - _count);
|
||||||
|
_count += 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Fixed tables of ITU-T T.81: the zig-zag order and the example tables of Annex K.</summary>
|
||||||
|
internal static class JpegTables
|
||||||
|
{
|
||||||
|
/// <summary>Coefficients in a block.</summary>
|
||||||
|
public const int BlockSize = 64;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// For each position of the zig-zag sequence (T.81 Figure A.6), the index of the coefficient in natural (row-major)
|
||||||
|
/// order. Built by walking the anti-diagonals, so it cannot be mistyped.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly byte[] ZigZag = BuildZigZag();
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.1, luminance quantization, natural order.</summary>
|
||||||
|
public static ReadOnlySpan<byte> LuminanceQuantization =>
|
||||||
|
[
|
||||||
|
16, 11, 10, 16, 24, 40, 51, 61,
|
||||||
|
12, 12, 14, 19, 26, 58, 60, 55,
|
||||||
|
14, 13, 16, 24, 40, 57, 69, 56,
|
||||||
|
14, 17, 22, 29, 51, 87, 80, 62,
|
||||||
|
18, 22, 37, 56, 68, 109, 103, 77,
|
||||||
|
24, 35, 55, 64, 81, 104, 113, 92,
|
||||||
|
49, 64, 78, 87, 103, 121, 120, 101,
|
||||||
|
72, 92, 95, 98, 112, 100, 103, 99,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.2, chrominance quantization, natural order.</summary>
|
||||||
|
public static ReadOnlySpan<byte> ChrominanceQuantization =>
|
||||||
|
[
|
||||||
|
17, 18, 24, 47, 99, 99, 99, 99,
|
||||||
|
18, 21, 26, 66, 99, 99, 99, 99,
|
||||||
|
24, 26, 56, 99, 99, 99, 99, 99,
|
||||||
|
47, 66, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
99, 99, 99, 99, 99, 99, 99, 99,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.3 as code counts per length 1-16.</summary>
|
||||||
|
public static ReadOnlySpan<byte> LuminanceDcCounts => [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.3 symbols.</summary>
|
||||||
|
public static ReadOnlySpan<byte> LuminanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.4 as code counts per length 1-16.</summary>
|
||||||
|
public static ReadOnlySpan<byte> ChrominanceDcCounts => [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.4 symbols.</summary>
|
||||||
|
public static ReadOnlySpan<byte> ChrominanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.5 as code counts per length 1-16.</summary>
|
||||||
|
public static ReadOnlySpan<byte> LuminanceAcCounts => [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.5 symbols (run/size), in code order.</summary>
|
||||||
|
public static ReadOnlySpan<byte> LuminanceAcValues =>
|
||||||
|
[
|
||||||
|
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
|
||||||
|
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0,
|
||||||
|
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
|
||||||
|
0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
|
||||||
|
0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
|
||||||
|
0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
|
||||||
|
0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
|
||||||
|
0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5,
|
||||||
|
0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
|
||||||
|
0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
|
||||||
|
0xF9, 0xFA,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.6 as code counts per length 1-16.</summary>
|
||||||
|
public static ReadOnlySpan<byte> ChrominanceAcCounts => [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
|
||||||
|
|
||||||
|
/// <summary>T.81 Table K.6 symbols (run/size), in code order.</summary>
|
||||||
|
public static ReadOnlySpan<byte> ChrominanceAcValues =>
|
||||||
|
[
|
||||||
|
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
|
||||||
|
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0,
|
||||||
|
0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26,
|
||||||
|
0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
|
||||||
|
0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
|
||||||
|
0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
|
||||||
|
0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5,
|
||||||
|
0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3,
|
||||||
|
0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA,
|
||||||
|
0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
|
||||||
|
0xF9, 0xFA,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An Annex K quantization table scaled for a quality of 1-100: 50 keeps the table, higher divides it, lower
|
||||||
|
/// multiplies it (scale 5000/q below 50, 200 - 2q above), each entry rounded and kept within 1-255 so the table
|
||||||
|
/// fits a baseline (8-bit) DQT. Natural order.
|
||||||
|
/// </summary>
|
||||||
|
public static ushort[] ScaledQuantization(ReadOnlySpan<byte> table, int quality)
|
||||||
|
{
|
||||||
|
quality = Math.Clamp(quality, 1, 100);
|
||||||
|
var scale = quality < 50 ? 5000 / quality : 200 - (quality * 2);
|
||||||
|
var result = new ushort[BlockSize];
|
||||||
|
for (var i = 0; i < BlockSize; i++)
|
||||||
|
{
|
||||||
|
result[i] = (ushort)Math.Clamp(((table[i] * scale) + 50) / 100, 1, 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] BuildZigZag()
|
||||||
|
{
|
||||||
|
var order = new byte[BlockSize];
|
||||||
|
var k = 0;
|
||||||
|
for (var diagonal = 0; diagonal < 15; diagonal++)
|
||||||
|
{
|
||||||
|
var low = Math.Max(0, diagonal - 7);
|
||||||
|
var high = Math.Min(diagonal, 7);
|
||||||
|
if ((diagonal & 1) == 1)
|
||||||
|
{
|
||||||
|
// Odd diagonals go down-left: the row grows.
|
||||||
|
for (var row = low; row <= high; row++)
|
||||||
|
{
|
||||||
|
order[k++] = (byte)((row * 8) + (diagonal - row));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (var row = high; row >= low; row--)
|
||||||
|
{
|
||||||
|
order[k++] = (byte)((row * 8) + (diagonal - row));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,938 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads PNG files (W3C PNG specification, third edition): every colour type and bit depth, palettes with tRNS,
|
||||||
|
/// colour keys, Adam7 interlacing, the five row filters. The pixels come out as straight RGBA8; 16-bit samples keep
|
||||||
|
/// their high byte. Gamma, chromaticities and colour profiles are not applied (the profile is returned in the
|
||||||
|
/// metadata). The CRC of every chunk is checked: a damaged critical chunk stops the decoding, a damaged ancillary chunk
|
||||||
|
/// is skipped.
|
||||||
|
/// </summary>
|
||||||
|
public static class PngDecoder
|
||||||
|
{
|
||||||
|
private const int MaxChunkLength = int.MaxValue;
|
||||||
|
private const string XmpKeyword = "XML:com.adobe.xmp";
|
||||||
|
|
||||||
|
// Adam7: first column, first row, column step, row step of the seven passes.
|
||||||
|
private static ReadOnlySpan<byte> Adam7 =>
|
||||||
|
[
|
||||||
|
0, 0, 8, 8,
|
||||||
|
4, 0, 8, 8,
|
||||||
|
0, 4, 4, 8,
|
||||||
|
2, 0, 4, 4,
|
||||||
|
0, 2, 2, 4,
|
||||||
|
1, 0, 2, 2,
|
||||||
|
0, 1, 1, 2,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Whether the bytes start with the PNG signature.</summary>
|
||||||
|
public static bool IsPng(ReadOnlySpan<byte> data) => data.Length >= 8 && data[..8].SequenceEqual(ImageFormatSniffer.PngSignature);
|
||||||
|
|
||||||
|
/// <summary>Size, frames and metadata of a PNG, without decoding the pixels.</summary>
|
||||||
|
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
|
||||||
|
{
|
||||||
|
var file = Parse(data, limits ?? ImageLimits.Default, readMetadata: true);
|
||||||
|
return file.ToInfo();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a PNG to straight RGBA8.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a PNG.</exception>
|
||||||
|
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
limits ??= ImageLimits.Default;
|
||||||
|
var file = Parse(data, limits, readMetadata: false);
|
||||||
|
return DecodePixels(data, file, limits, pooled);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a PNG to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false)
|
||||||
|
{
|
||||||
|
limits ??= ImageLimits.Default;
|
||||||
|
var file = Parse(data, limits, readMetadata: true);
|
||||||
|
var image = DecodePixels(data, file, limits, pooled);
|
||||||
|
info = file.ToInfo();
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class PngFile
|
||||||
|
{
|
||||||
|
public int Width;
|
||||||
|
public int Height;
|
||||||
|
public int BitDepth;
|
||||||
|
public int ColorType;
|
||||||
|
public bool Interlaced;
|
||||||
|
|
||||||
|
/// <summary>256 RGBA entries; entries the file does not give are opaque black.</summary>
|
||||||
|
public byte[]? Palette;
|
||||||
|
public int PaletteCount;
|
||||||
|
|
||||||
|
public bool HasColorKey;
|
||||||
|
public ushort KeyRed;
|
||||||
|
public ushort KeyGreen;
|
||||||
|
public ushort KeyBlue;
|
||||||
|
public bool HasPaletteAlpha;
|
||||||
|
|
||||||
|
public readonly List<(int Start, int Length)> Idat = [];
|
||||||
|
public int FrameCount = 1;
|
||||||
|
|
||||||
|
public byte[]? Exif;
|
||||||
|
public byte[]? Icc;
|
||||||
|
public string? IccName;
|
||||||
|
public string? Xmp;
|
||||||
|
public List<ImageText>? Texts;
|
||||||
|
public List<string>? ColorChunks;
|
||||||
|
|
||||||
|
public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 };
|
||||||
|
|
||||||
|
public int BitsPerPixel => Channels * BitDepth;
|
||||||
|
|
||||||
|
public ImageInfo ToInfo() => new(
|
||||||
|
ImageFormat.Png,
|
||||||
|
Width,
|
||||||
|
Height,
|
||||||
|
FrameCount,
|
||||||
|
ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha,
|
||||||
|
Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null
|
||||||
|
? ImageMetadata.Empty
|
||||||
|
: new ImageMetadata
|
||||||
|
{
|
||||||
|
Exif = Exif,
|
||||||
|
Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif),
|
||||||
|
IccProfile = Icc,
|
||||||
|
IccProfileName = IccName,
|
||||||
|
Xmp = Xmp,
|
||||||
|
Texts = Texts ?? [],
|
||||||
|
ColorChunks = ColorChunks ?? [],
|
||||||
|
})
|
||||||
|
{
|
||||||
|
BitsPerSample = ColorType == 3 ? 8 : BitDepth,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PngFile Parse(ReadOnlyMemory<byte> memory, ImageLimits limits, bool readMetadata)
|
||||||
|
{
|
||||||
|
var data = memory.Span;
|
||||||
|
if (!IsPng(data))
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("Non è un file PNG.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var file = new PngFile();
|
||||||
|
var seenHeader = false;
|
||||||
|
var seenPalette = false;
|
||||||
|
var seenTransparency = false;
|
||||||
|
var idatState = 0; // 0 none yet, 1 inside the IDAT run, 2 after it
|
||||||
|
var metadataBudget = limits.MaxMetadataBytes;
|
||||||
|
var pos = 8;
|
||||||
|
while (pos < data.Length)
|
||||||
|
{
|
||||||
|
if (data.Length - pos < 12)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG troncato: un blocco finisce prima della fine del file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var length = BinaryPrimitives.ReadUInt32BigEndian(data[pos..]);
|
||||||
|
if (length > MaxChunkLength || length > data.Length - pos - 12)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG troncato: un blocco dichiara più byte di quelli che il file contiene.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var type = data.Slice(pos + 4, 4);
|
||||||
|
var payloadStart = pos + 8;
|
||||||
|
var payload = data.Slice(payloadStart, (int)length);
|
||||||
|
var storedCrc = BinaryPrimitives.ReadUInt32BigEndian(data[(payloadStart + (int)length)..]);
|
||||||
|
pos = payloadStart + (int)length + 4;
|
||||||
|
if (!IsChunkType(type))
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: tipo di blocco non valido.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = Encoding.ASCII.GetString(type);
|
||||||
|
var critical = (type[0] & 0x20) == 0;
|
||||||
|
if (Crc32.Compute(data.Slice(payloadStart - 4, (int)length + 4)) != storedCrc)
|
||||||
|
{
|
||||||
|
if (critical)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException($"PNG danneggiato: il CRC del blocco {name} non corrisponde.");
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!seenHeader && name != "IHDR")
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: il primo blocco non è IHDR.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (idatState == 1 && name != "IDAT")
|
||||||
|
{
|
||||||
|
idatState = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (name)
|
||||||
|
{
|
||||||
|
case "IHDR":
|
||||||
|
if (seenHeader)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: IHDR ripetuto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
ReadHeader(file, payload);
|
||||||
|
seenHeader = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "PLTE":
|
||||||
|
if (seenPalette || idatState != 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: PLTE ripetuto o dopo i dati dell'immagine.");
|
||||||
|
}
|
||||||
|
|
||||||
|
seenPalette = true;
|
||||||
|
ReadPalette(file, payload);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "tRNS":
|
||||||
|
if (!seenTransparency && idatState == 0)
|
||||||
|
{
|
||||||
|
seenTransparency = true;
|
||||||
|
ReadTransparency(file, payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "IDAT":
|
||||||
|
if (idatState == 2)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: i blocchi IDAT non sono uno dopo l'altro.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.ColorType == 3 && file.Palette is null)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: immagine a tavolozza senza PLTE.");
|
||||||
|
}
|
||||||
|
|
||||||
|
idatState = 1;
|
||||||
|
if (length > 0)
|
||||||
|
{
|
||||||
|
file.Idat.Add((payloadStart, (int)length));
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "IEND":
|
||||||
|
pos = data.Length;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "acTL":
|
||||||
|
if (payload.Length >= 8 && idatState == 0)
|
||||||
|
{
|
||||||
|
var frames = BinaryPrimitives.ReadUInt32BigEndian(payload);
|
||||||
|
file.FrameCount = frames is > 0 and <= int.MaxValue ? (int)frames : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "gAMA" or "cHRM" or "sRGB":
|
||||||
|
if (readMetadata && !(file.ColorChunks ??= []).Contains(name))
|
||||||
|
{
|
||||||
|
file.ColorChunks.Add(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "tEXt" or "zTXt" or "iTXt" or "iCCP" or "eXIf":
|
||||||
|
if (readMetadata)
|
||||||
|
{
|
||||||
|
ReadMetadata(file, name, payload, ref metadataBudget);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
if (critical)
|
||||||
|
{
|
||||||
|
throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!seenHeader)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG troncato: manca IHDR.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (idatState == 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG senza dati dell'immagine (IDAT).");
|
||||||
|
}
|
||||||
|
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsChunkType(ReadOnlySpan<byte> type)
|
||||||
|
{
|
||||||
|
foreach (var c in type)
|
||||||
|
{
|
||||||
|
if (!char.IsAsciiLetter((char)c))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ReadHeader(PngFile file, ReadOnlySpan<byte> payload)
|
||||||
|
{
|
||||||
|
if (payload.Length != 13)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: IHDR della lunghezza sbagliata.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var width = BinaryPrimitives.ReadUInt32BigEndian(payload);
|
||||||
|
var height = BinaryPrimitives.ReadUInt32BigEndian(payload[4..]);
|
||||||
|
if (width == 0 || height == 0 || width > int.MaxValue || height > int.MaxValue)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException($"PNG danneggiato: misura non valida ({width}×{height}).");
|
||||||
|
}
|
||||||
|
|
||||||
|
int depth = payload[8];
|
||||||
|
int colorType = payload[9];
|
||||||
|
var valid = colorType switch
|
||||||
|
{
|
||||||
|
0 => depth is 1 or 2 or 4 or 8 or 16,
|
||||||
|
3 => depth is 1 or 2 or 4 or 8,
|
||||||
|
2 or 4 or 6 => depth is 8 or 16,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if (!valid)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException($"PNG danneggiato: profondità {depth} non ammessa per il tipo di colore {colorType}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload[10] != 0 || payload[11] != 0 || payload[12] > 1)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: metodo di compressione, di filtro o d'interlacciamento sconosciuto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
file.Width = (int)width;
|
||||||
|
file.Height = (int)height;
|
||||||
|
file.BitDepth = depth;
|
||||||
|
file.ColorType = colorType;
|
||||||
|
file.Interlaced = payload[12] == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ReadPalette(PngFile file, ReadOnlySpan<byte> payload)
|
||||||
|
{
|
||||||
|
if (payload.Length == 0 || payload.Length % 3 != 0 || payload.Length > 256 * 3)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: PLTE della lunghezza sbagliata.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.ColorType is 0 or 4)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: PLTE in un'immagine in scala di grigi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.ColorType != 3)
|
||||||
|
{
|
||||||
|
// A suggested palette for an RGB image: nothing to do with the pixels.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var palette = new byte[256 * 4];
|
||||||
|
for (var i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
palette[(i * 4) + 3] = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
var count = payload.Length / 3;
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
palette[i * 4] = payload[i * 3];
|
||||||
|
palette[(i * 4) + 1] = payload[(i * 3) + 1];
|
||||||
|
palette[(i * 4) + 2] = payload[(i * 3) + 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
file.Palette = palette;
|
||||||
|
file.PaletteCount = count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ReadTransparency(PngFile file, ReadOnlySpan<byte> payload)
|
||||||
|
{
|
||||||
|
switch (file.ColorType)
|
||||||
|
{
|
||||||
|
case 0 when payload.Length >= 2:
|
||||||
|
file.HasColorKey = true;
|
||||||
|
file.KeyRed = file.KeyGreen = file.KeyBlue = BinaryPrimitives.ReadUInt16BigEndian(payload);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 2 when payload.Length >= 6:
|
||||||
|
file.HasColorKey = true;
|
||||||
|
file.KeyRed = BinaryPrimitives.ReadUInt16BigEndian(payload);
|
||||||
|
file.KeyGreen = BinaryPrimitives.ReadUInt16BigEndian(payload[2..]);
|
||||||
|
file.KeyBlue = BinaryPrimitives.ReadUInt16BigEndian(payload[4..]);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 3:
|
||||||
|
if (file.Palette is not { } palette)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: tRNS prima di PLTE.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries beyond the palette are ignored, as libpng does.
|
||||||
|
var count = Math.Min(payload.Length, file.PaletteCount);
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
palette[(i * 4) + 3] = payload[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
file.HasPaletteAlpha = count > 0;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
// tRNS is not allowed with an alpha channel; a short one is ignored.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ReadMetadata(PngFile file, string name, ReadOnlySpan<byte> payload, ref int budget)
|
||||||
|
{
|
||||||
|
// Damaged or oversized metadata is skipped: it must never stop an image from being shown.
|
||||||
|
switch (name)
|
||||||
|
{
|
||||||
|
case "eXIf":
|
||||||
|
if (file.Exif is null && payload.Length >= 4 && (payload[..4].SequenceEqual("II*\0"u8) || payload[..4].SequenceEqual("MM\0*"u8)) && Spend(ref budget, payload.Length))
|
||||||
|
{
|
||||||
|
file.Exif = payload.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "iCCP":
|
||||||
|
{
|
||||||
|
var zero = payload.IndexOf((byte)0);
|
||||||
|
if (file.Icc is not null || zero is < 1 or > 79 || payload.Length < zero + 2 || payload[zero + 1] != 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Inflate(payload[(zero + 2)..], budget) is { } profile && Spend(ref budget, profile.Length))
|
||||||
|
{
|
||||||
|
file.Icc = profile;
|
||||||
|
file.IccName = Encoding.Latin1.GetString(payload[..zero]);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tEXt":
|
||||||
|
{
|
||||||
|
var zero = payload.IndexOf((byte)0);
|
||||||
|
if (zero is < 1 or > 79 || !Spend(ref budget, payload.Length))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
AddText(file, new ImageText(Encoding.Latin1.GetString(payload[..zero]), Encoding.Latin1.GetString(payload[(zero + 1)..])));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "zTXt":
|
||||||
|
{
|
||||||
|
var zero = payload.IndexOf((byte)0);
|
||||||
|
if (zero is < 1 or > 79 || payload.Length < zero + 2 || payload[zero + 1] != 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Inflate(payload[(zero + 2)..], budget) is { } text && Spend(ref budget, text.Length))
|
||||||
|
{
|
||||||
|
AddText(file, new ImageText(Encoding.Latin1.GetString(payload[..zero]), Encoding.Latin1.GetString(text)));
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "iTXt":
|
||||||
|
ReadInternationalText(file, payload, ref budget);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ReadInternationalText(PngFile file, ReadOnlySpan<byte> payload, ref int budget)
|
||||||
|
{
|
||||||
|
var zero = payload.IndexOf((byte)0);
|
||||||
|
if (zero is < 1 or > 79 || payload.Length < zero + 3)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var keyword = Encoding.Latin1.GetString(payload[..zero]);
|
||||||
|
var compressed = payload[zero + 1];
|
||||||
|
var method = payload[zero + 2];
|
||||||
|
var rest = payload[(zero + 3)..];
|
||||||
|
var languageEnd = rest.IndexOf((byte)0);
|
||||||
|
if (languageEnd < 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var language = Encoding.ASCII.GetString(rest[..languageEnd]);
|
||||||
|
rest = rest[(languageEnd + 1)..];
|
||||||
|
var translatedEnd = rest.IndexOf((byte)0);
|
||||||
|
if (translatedEnd < 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string translated;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
translated = StrictUtf8.GetString(rest[..translatedEnd]);
|
||||||
|
}
|
||||||
|
catch (DecoderFallbackException)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
rest = rest[(translatedEnd + 1)..];
|
||||||
|
byte[]? raw;
|
||||||
|
if (compressed == 0)
|
||||||
|
{
|
||||||
|
raw = Spend(ref budget, rest.Length) ? rest.ToArray() : null;
|
||||||
|
}
|
||||||
|
else if (compressed == 1 && method == 0)
|
||||||
|
{
|
||||||
|
raw = Inflate(rest, budget);
|
||||||
|
if (raw is not null && !Spend(ref budget, raw.Length))
|
||||||
|
{
|
||||||
|
raw = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (raw is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string text;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
text = StrictUtf8.GetString(raw);
|
||||||
|
}
|
||||||
|
catch (DecoderFallbackException)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (keyword == XmpKeyword)
|
||||||
|
{
|
||||||
|
file.Xmp ??= text;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
AddText(file, new ImageText(keyword, text, language, translated));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
|
||||||
|
|
||||||
|
private static void AddText(PngFile file, ImageText text) => (file.Texts ??= []).Add(text);
|
||||||
|
|
||||||
|
private static bool Spend(ref int budget, int bytes)
|
||||||
|
{
|
||||||
|
if (bytes > budget)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
budget -= bytes;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Inflates a zlib stream of metadata; null when it is damaged or longer than <paramref name="maxBytes"/>.</summary>
|
||||||
|
internal static byte[]? Inflate(ReadOnlySpan<byte> compressed, int maxBytes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var input = new MemoryStream(compressed.ToArray(), writable: false);
|
||||||
|
using var zlib = new ZLibStream(input, CompressionMode.Decompress);
|
||||||
|
using var output = new MemoryStream();
|
||||||
|
var buffer = new byte[16 * 1024];
|
||||||
|
int read;
|
||||||
|
while ((read = zlib.Read(buffer)) > 0)
|
||||||
|
{
|
||||||
|
if (output.Length + read > maxBytes)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Write(buffer, 0, read);
|
||||||
|
}
|
||||||
|
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
catch (InvalidDataException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long RowBytes(PngFile file, int width) => (((long)width * file.BitsPerPixel) + 7) / 8;
|
||||||
|
|
||||||
|
private static RgbaImage DecodePixels(ReadOnlyMemory<byte> data, PngFile file, ImageLimits limits, bool pooled)
|
||||||
|
{
|
||||||
|
limits.CheckSize(file.Width, file.Height);
|
||||||
|
var maxRow = RowBytes(file, file.Width);
|
||||||
|
limits.CheckWorkingBytes(2 * (maxRow + 1));
|
||||||
|
var image = RgbaImage.Create(file.Width, file.Height, limits, pooled);
|
||||||
|
var current = ArrayPool<byte>.Shared.Rent((int)maxRow + 1);
|
||||||
|
var previous = ArrayPool<byte>.Shared.Rent((int)maxRow + 1);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var zlib = new ZLibStream(new SegmentStream(data, file.Idat), CompressionMode.Decompress);
|
||||||
|
var bpp = Math.Max(1, file.BitsPerPixel / 8);
|
||||||
|
var pixels = image.Pixels;
|
||||||
|
var stride = image.Stride;
|
||||||
|
if (!file.Interlaced)
|
||||||
|
{
|
||||||
|
DecodePass(zlib, file, file.Width, file.Height, bpp, current, previous, pixels, 0, stride, RgbaImage.BytesPerPixel);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var adam7 = Adam7;
|
||||||
|
for (var pass = 0; pass < 7; pass++)
|
||||||
|
{
|
||||||
|
int x0 = adam7[pass * 4], y0 = adam7[(pass * 4) + 1], dx = adam7[(pass * 4) + 2], dy = adam7[(pass * 4) + 3];
|
||||||
|
var passWidth = file.Width > x0 ? (file.Width - x0 + dx - 1) / dx : 0;
|
||||||
|
var passHeight = file.Height > y0 ? (file.Height - y0 + dy - 1) / dy : 0;
|
||||||
|
if (passWidth == 0 || passHeight == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
DecodePass(zlib, file, passWidth, passHeight, bpp, current, previous, pixels, (y0 * stride) + (x0 * RgbaImage.BytesPerPixel), dy * stride, dx * RgbaImage.BytesPerPixel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
catch (InvalidDataException ex)
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw new ImageDecodeException("PNG danneggiato: i dati compressi dell'immagine non sono validi.", ex);
|
||||||
|
}
|
||||||
|
catch (EndOfStreamException ex)
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw new ImageDecodeException("PNG troncato: i dati dell'immagine finiscono prima dell'ultima riga.", ex);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<byte>.Shared.Return(current);
|
||||||
|
ArrayPool<byte>.Shared.Return(previous);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DecodePass(
|
||||||
|
ZLibStream zlib,
|
||||||
|
PngFile file,
|
||||||
|
int width,
|
||||||
|
int height,
|
||||||
|
int bpp,
|
||||||
|
byte[] current,
|
||||||
|
byte[] previous,
|
||||||
|
Span<byte> pixels,
|
||||||
|
int firstOffset,
|
||||||
|
int rowStep,
|
||||||
|
int pixelStep)
|
||||||
|
{
|
||||||
|
var rowBytes = (int)RowBytes(file, width);
|
||||||
|
var prev = previous.AsSpan(0, rowBytes + 1);
|
||||||
|
var cur = current.AsSpan(0, rowBytes + 1);
|
||||||
|
prev.Clear();
|
||||||
|
var offset = firstOffset;
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
zlib.ReadExactly(cur);
|
||||||
|
var filter = cur[0];
|
||||||
|
var row = cur[1..];
|
||||||
|
Unfilter(filter, row, prev[1..], bpp);
|
||||||
|
ConvertRow(file, row, width, pixels[offset..], pixelStep);
|
||||||
|
offset += rowStep;
|
||||||
|
|
||||||
|
var swap = cur;
|
||||||
|
cur = prev;
|
||||||
|
prev = swap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Undoes the row filter (PNG specification §7.3, §9.2): <paramref name="row"/> is changed in place.</summary>
|
||||||
|
internal static void Unfilter(byte filter, Span<byte> row, ReadOnlySpan<byte> previous, int bpp)
|
||||||
|
{
|
||||||
|
var n = row.Length;
|
||||||
|
switch (filter)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
for (var i = bpp; i < n; i++)
|
||||||
|
{
|
||||||
|
row[i] += row[i - bpp];
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
{
|
||||||
|
var i = 0;
|
||||||
|
if (Vector.IsHardwareAccelerated)
|
||||||
|
{
|
||||||
|
var width = Vector<byte>.Count;
|
||||||
|
for (; i + width <= n; i += width)
|
||||||
|
{
|
||||||
|
(new Vector<byte>(row[i..]) + new Vector<byte>(previous[i..])).CopyTo(row[i..]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (; i < n; i++)
|
||||||
|
{
|
||||||
|
row[i] += previous[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 3:
|
||||||
|
for (var i = 0; i < bpp && i < n; i++)
|
||||||
|
{
|
||||||
|
row[i] += (byte)(previous[i] >> 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = bpp; i < n; i++)
|
||||||
|
{
|
||||||
|
row[i] += (byte)((row[i - bpp] + previous[i]) >> 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 4:
|
||||||
|
for (var i = 0; i < bpp && i < n; i++)
|
||||||
|
{
|
||||||
|
row[i] += previous[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = bpp; i < n; i++)
|
||||||
|
{
|
||||||
|
row[i] += Paeth(row[i - bpp], previous[i], previous[i - bpp]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new ImageDecodeException($"PNG danneggiato: filtro di riga sconosciuto ({filter}).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The Paeth predictor (PNG specification §9.4).</summary>
|
||||||
|
internal static byte Paeth(byte a, byte b, byte c)
|
||||||
|
{
|
||||||
|
var pa = Math.Abs(b - c);
|
||||||
|
var pb = Math.Abs(a - c);
|
||||||
|
var pc = Math.Abs(a + b - c - c);
|
||||||
|
if (pa <= pb && pa <= pc)
|
||||||
|
{
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
return pb <= pc ? b : c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Converts <paramref name="count"/> pixels of an unfiltered row to RGBA8, one pixel every <paramref name="step"/> bytes.</summary>
|
||||||
|
private static void ConvertRow(PngFile file, ReadOnlySpan<byte> row, int count, Span<byte> dest, int step)
|
||||||
|
{
|
||||||
|
var depth = file.BitDepth;
|
||||||
|
switch (file.ColorType)
|
||||||
|
{
|
||||||
|
case 3:
|
||||||
|
ConvertIndexed(row, count, dest, step, depth, file.Palette!);
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 0 when depth < 8:
|
||||||
|
ConvertLowGrey(row, count, dest, step, depth, file.HasColorKey ? file.KeyGreen : -1);
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 0 when depth == 8:
|
||||||
|
{
|
||||||
|
var key = file.HasColorKey ? file.KeyGreen : -1;
|
||||||
|
for (int i = 0, d = 0; i < count; i++, d += step)
|
||||||
|
{
|
||||||
|
var g = row[i];
|
||||||
|
dest[d] = g;
|
||||||
|
dest[d + 1] = g;
|
||||||
|
dest[d + 2] = g;
|
||||||
|
dest[d + 3] = g == key ? (byte)0 : (byte)255;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 0:
|
||||||
|
{
|
||||||
|
var key = file.HasColorKey ? file.KeyGreen : -1;
|
||||||
|
for (int i = 0, d = 0; i < count; i++, d += step)
|
||||||
|
{
|
||||||
|
var v = BinaryPrimitives.ReadUInt16BigEndian(row[(i * 2)..]);
|
||||||
|
var g = (byte)(v >> 8);
|
||||||
|
dest[d] = g;
|
||||||
|
dest[d + 1] = g;
|
||||||
|
dest[d + 2] = g;
|
||||||
|
dest[d + 3] = v == key ? (byte)0 : (byte)255;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 2 when depth == 8:
|
||||||
|
{
|
||||||
|
var hasKey = file.HasColorKey;
|
||||||
|
int kr = file.KeyRed, kg = file.KeyGreen, kb = file.KeyBlue;
|
||||||
|
for (int i = 0, s = 0, d = 0; i < count; i++, s += 3, d += step)
|
||||||
|
{
|
||||||
|
byte r = row[s], g = row[s + 1], b = row[s + 2];
|
||||||
|
dest[d] = r;
|
||||||
|
dest[d + 1] = g;
|
||||||
|
dest[d + 2] = b;
|
||||||
|
dest[d + 3] = hasKey && r == kr && g == kg && b == kb ? (byte)0 : (byte)255;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
{
|
||||||
|
var hasKey = file.HasColorKey;
|
||||||
|
int kr = file.KeyRed, kg = file.KeyGreen, kb = file.KeyBlue;
|
||||||
|
for (int i = 0, s = 0, d = 0; i < count; i++, s += 6, d += step)
|
||||||
|
{
|
||||||
|
var r = BinaryPrimitives.ReadUInt16BigEndian(row[s..]);
|
||||||
|
var g = BinaryPrimitives.ReadUInt16BigEndian(row[(s + 2)..]);
|
||||||
|
var b = BinaryPrimitives.ReadUInt16BigEndian(row[(s + 4)..]);
|
||||||
|
dest[d] = (byte)(r >> 8);
|
||||||
|
dest[d + 1] = (byte)(g >> 8);
|
||||||
|
dest[d + 2] = (byte)(b >> 8);
|
||||||
|
dest[d + 3] = hasKey && r == kr && g == kg && b == kb ? (byte)0 : (byte)255;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 4 when depth == 8:
|
||||||
|
for (int i = 0, s = 0, d = 0; i < count; i++, s += 2, d += step)
|
||||||
|
{
|
||||||
|
var g = row[s];
|
||||||
|
dest[d] = g;
|
||||||
|
dest[d + 1] = g;
|
||||||
|
dest[d + 2] = g;
|
||||||
|
dest[d + 3] = row[s + 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 4:
|
||||||
|
for (int i = 0, s = 0, d = 0; i < count; i++, s += 4, d += step)
|
||||||
|
{
|
||||||
|
var g = row[s];
|
||||||
|
dest[d] = g;
|
||||||
|
dest[d + 1] = g;
|
||||||
|
dest[d + 2] = g;
|
||||||
|
dest[d + 3] = row[s + 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 6 when depth == 8:
|
||||||
|
if (step == RgbaImage.BytesPerPixel)
|
||||||
|
{
|
||||||
|
row[..(count * 4)].CopyTo(dest);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0, s = 0, d = 0; i < count; i++, s += 4, d += step)
|
||||||
|
{
|
||||||
|
MemoryMarshal.Write(dest[d..], MemoryMarshal.Read<uint>(row[s..]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
|
||||||
|
default:
|
||||||
|
for (int i = 0, s = 0, d = 0; i < count; i++, s += 8, d += step)
|
||||||
|
{
|
||||||
|
dest[d] = row[s];
|
||||||
|
dest[d + 1] = row[s + 2];
|
||||||
|
dest[d + 2] = row[s + 4];
|
||||||
|
dest[d + 3] = row[s + 6];
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ConvertIndexed(ReadOnlySpan<byte> row, int count, Span<byte> dest, int step, int depth, byte[] palette)
|
||||||
|
{
|
||||||
|
if (depth == 8)
|
||||||
|
{
|
||||||
|
for (int i = 0, d = 0; i < count; i++, d += step)
|
||||||
|
{
|
||||||
|
MemoryMarshal.Write(dest[d..], MemoryMarshal.Read<uint>(palette.AsSpan(row[i] * 4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var mask = (1 << depth) - 1;
|
||||||
|
var perByte = 8 / depth;
|
||||||
|
for (int i = 0, d = 0; i < count; i++, d += step)
|
||||||
|
{
|
||||||
|
var shift = 8 - depth - ((i % perByte) * depth);
|
||||||
|
var index = (row[i / perByte] >> shift) & mask;
|
||||||
|
MemoryMarshal.Write(dest[d..], MemoryMarshal.Read<uint>(palette.AsSpan(index * 4)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ConvertLowGrey(ReadOnlySpan<byte> row, int count, Span<byte> dest, int step, int depth, int key)
|
||||||
|
{
|
||||||
|
var mask = (1 << depth) - 1;
|
||||||
|
var scale = 255 / mask;
|
||||||
|
var perByte = 8 / depth;
|
||||||
|
for (int i = 0, d = 0; i < count; i++, d += step)
|
||||||
|
{
|
||||||
|
var shift = 8 - depth - ((i % perByte) * depth);
|
||||||
|
var v = (row[i / perByte] >> shift) & mask;
|
||||||
|
var g = (byte)(v * scale);
|
||||||
|
dest[d] = g;
|
||||||
|
dest[d + 1] = g;
|
||||||
|
dest[d + 2] = g;
|
||||||
|
dest[d + 3] = v == key ? (byte)0 : (byte)255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,475 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>What <see cref="PngEncoder"/> writes for the pixels.</summary>
|
||||||
|
public enum PngColorMode
|
||||||
|
{
|
||||||
|
/// <summary>RGB when every pixel is opaque, RGBA otherwise.</summary>
|
||||||
|
Auto,
|
||||||
|
|
||||||
|
/// <summary>8-bit RGB (colour type 2): alpha is dropped.</summary>
|
||||||
|
Rgb,
|
||||||
|
|
||||||
|
/// <summary>8-bit RGBA (colour type 6).</summary>
|
||||||
|
Rgba,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How <see cref="PngEncoder"/> picks the filter of each row.</summary>
|
||||||
|
public enum PngFilterStrategy
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// For each row the filter whose output has the smallest sum of absolute values, read as signed bytes (the
|
||||||
|
/// heuristic the PNG specification suggests in §12.8).
|
||||||
|
/// </summary>
|
||||||
|
Adaptive,
|
||||||
|
None,
|
||||||
|
Sub,
|
||||||
|
Up,
|
||||||
|
Average,
|
||||||
|
Paeth,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Options of <see cref="PngEncoder"/>.</summary>
|
||||||
|
public sealed record PngEncoderOptions
|
||||||
|
{
|
||||||
|
/// <summary>The options used when a caller passes none.</summary>
|
||||||
|
public static PngEncoderOptions Default { get; } = new();
|
||||||
|
|
||||||
|
public PngColorMode ColorMode { get; init; } = PngColorMode.Auto;
|
||||||
|
|
||||||
|
public PngFilterStrategy Filter { get; init; } = PngFilterStrategy.Adaptive;
|
||||||
|
|
||||||
|
public CompressionLevel CompressionLevel { get; init; } = CompressionLevel.Optimal;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// EXIF to write in an eXIf chunk: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by the «Exif\0\0»
|
||||||
|
/// of a JPEG APP1 segment, which is removed.
|
||||||
|
/// </summary>
|
||||||
|
public byte[]? Exif { get; init; }
|
||||||
|
|
||||||
|
/// <summary>ICC profile to write, compressed, in an iCCP chunk.</summary>
|
||||||
|
public byte[]? IccProfile { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Name of the profile in the iCCP chunk: 1 to 79 Latin-1 characters.</summary>
|
||||||
|
public string IccProfileName { get; init; } = "ICC Profile";
|
||||||
|
|
||||||
|
/// <summary>XMP packet to write in an uncompressed iTXt chunk with the keyword «XML:com.adobe.xmp».</summary>
|
||||||
|
public string? Xmp { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Texts to write, in order, after the pixels: a tEXt chunk when keyword and text are Latin-1 and there is no
|
||||||
|
/// language, an uncompressed iTXt chunk otherwise. Keywords: 1 to 79 printable Latin-1 characters.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<ImageText> Texts { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes 8-bit RGB or RGBA PNG files (W3C PNG specification): one zlib stream (System.IO.Compression) split into IDAT
|
||||||
|
/// chunks of 64 KiB, the filter of each row chosen by <see cref="PngFilterStrategy"/>, optional eXIf, iCCP and XMP.
|
||||||
|
/// </summary>
|
||||||
|
public static class PngEncoder
|
||||||
|
{
|
||||||
|
private const int IdatChunkSize = 64 * 1024;
|
||||||
|
|
||||||
|
/// <summary>The PNG file of <paramref name="image"/>.</summary>
|
||||||
|
public static byte[] Encode(RgbaImage image, PngEncoderOptions? options = null)
|
||||||
|
{
|
||||||
|
using var output = new MemoryStream();
|
||||||
|
Encode(image, output, options);
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the PNG file of <paramref name="image"/> to <paramref name="output"/>.</summary>
|
||||||
|
public static void Encode(RgbaImage image, Stream output, PngEncoderOptions? options = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(image);
|
||||||
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
options ??= PngEncoderOptions.Default;
|
||||||
|
var exif = options.Exif is { } givenExif ? ExifPayload(givenExif) : null;
|
||||||
|
var iccName = options.IccProfile is null ? null : IccName(options.IccProfileName);
|
||||||
|
foreach (var text in options.Texts)
|
||||||
|
{
|
||||||
|
if (!IsValidKeyword(text.Keyword))
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"«{text.Keyword}» is not a valid PNG keyword.", nameof(options));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var alpha = options.ColorMode switch
|
||||||
|
{
|
||||||
|
PngColorMode.Rgb => false,
|
||||||
|
PngColorMode.Rgba => true,
|
||||||
|
_ => !image.IsOpaque(),
|
||||||
|
};
|
||||||
|
|
||||||
|
output.Write(ImageFormatSniffer.PngSignature);
|
||||||
|
|
||||||
|
Span<byte> header = stackalloc byte[13];
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)image.Width);
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(header[4..], (uint)image.Height);
|
||||||
|
header[8] = 8;
|
||||||
|
header[9] = alpha ? (byte)6 : (byte)2;
|
||||||
|
header[10] = 0;
|
||||||
|
header[11] = 0;
|
||||||
|
header[12] = 0;
|
||||||
|
WriteChunk(output, "IHDR"u8, header);
|
||||||
|
|
||||||
|
if (options.IccProfile is { } profile)
|
||||||
|
{
|
||||||
|
using var payload = new MemoryStream();
|
||||||
|
payload.Write(iccName);
|
||||||
|
payload.WriteByte(0);
|
||||||
|
payload.WriteByte(0);
|
||||||
|
using (var zlib = new ZLibStream(payload, options.CompressionLevel, leaveOpen: true))
|
||||||
|
{
|
||||||
|
zlib.Write(profile);
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteChunk(output, "iCCP"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exif is not null)
|
||||||
|
{
|
||||||
|
WriteChunk(output, "eXIf"u8, exif);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.Xmp is { } xmp)
|
||||||
|
{
|
||||||
|
using var payload = new MemoryStream();
|
||||||
|
payload.Write("XML:com.adobe.xmp"u8);
|
||||||
|
payload.Write([0, 0, 0, 0, 0]); // end of keyword, not compressed, method, empty language, empty translation
|
||||||
|
payload.Write(Encoding.UTF8.GetBytes(xmp));
|
||||||
|
WriteChunk(output, "iTXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var idat = new IdatStream(output))
|
||||||
|
{
|
||||||
|
using (var zlib = new ZLibStream(idat, options.CompressionLevel, leaveOpen: true))
|
||||||
|
{
|
||||||
|
WriteRows(image, zlib, alpha, options.Filter);
|
||||||
|
}
|
||||||
|
|
||||||
|
idat.Complete();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var text in options.Texts)
|
||||||
|
{
|
||||||
|
WriteText(output, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteChunk(output, "IEND"u8, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteRows(RgbaImage image, Stream zlib, bool alpha, PngFilterStrategy strategy)
|
||||||
|
{
|
||||||
|
var bpp = alpha ? 4 : 3;
|
||||||
|
var rowBytes = image.Width * bpp;
|
||||||
|
var pool = ArrayPool<byte>.Shared;
|
||||||
|
var raw = pool.Rent(rowBytes);
|
||||||
|
var previous = pool.Rent(rowBytes);
|
||||||
|
var candidates = pool.Rent((rowBytes + 1) * 5);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var prev = previous.AsSpan(0, rowBytes);
|
||||||
|
prev.Clear();
|
||||||
|
for (var y = 0; y < image.Height; y++)
|
||||||
|
{
|
||||||
|
var source = image.GetRow(y);
|
||||||
|
var row = raw.AsSpan(0, rowBytes);
|
||||||
|
if (alpha)
|
||||||
|
{
|
||||||
|
source.CopyTo(row);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (int s = 0, d = 0; d < rowBytes; s += 4, d += 3)
|
||||||
|
{
|
||||||
|
row[d] = source[s];
|
||||||
|
row[d + 1] = source[s + 1];
|
||||||
|
row[d + 2] = source[s + 2];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ReadOnlySpan<byte> chosen;
|
||||||
|
if (strategy == PngFilterStrategy.Adaptive)
|
||||||
|
{
|
||||||
|
var best = -1L;
|
||||||
|
chosen = default;
|
||||||
|
for (var filter = 0; filter < 5; filter++)
|
||||||
|
{
|
||||||
|
var output = candidates.AsSpan(filter * (rowBytes + 1), rowBytes + 1);
|
||||||
|
var sum = Filter((byte)filter, row, prev, bpp, output);
|
||||||
|
if (best < 0 || sum < best)
|
||||||
|
{
|
||||||
|
best = sum;
|
||||||
|
chosen = output;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var output = candidates.AsSpan(0, rowBytes + 1);
|
||||||
|
Filter((byte)(strategy - PngFilterStrategy.None), row, prev, bpp, output);
|
||||||
|
chosen = output;
|
||||||
|
}
|
||||||
|
|
||||||
|
zlib.Write(chosen);
|
||||||
|
row.CopyTo(prev);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
pool.Return(raw);
|
||||||
|
pool.Return(previous);
|
||||||
|
pool.Return(candidates);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes the filter byte and the filtered row to <paramref name="output"/> and returns the sum of the absolute
|
||||||
|
/// values of the filtered bytes, read as signed.
|
||||||
|
/// </summary>
|
||||||
|
internal static long Filter(byte filter, ReadOnlySpan<byte> row, ReadOnlySpan<byte> previous, int bpp, Span<byte> output)
|
||||||
|
{
|
||||||
|
output[0] = filter;
|
||||||
|
var o = output[1..];
|
||||||
|
var n = row.Length;
|
||||||
|
long sum = 0;
|
||||||
|
switch (filter)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
row.CopyTo(o);
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
sum += Math.Abs((int)(sbyte)row[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
var v = (byte)(row[i] - (i >= bpp ? row[i - bpp] : 0));
|
||||||
|
o[i] = v;
|
||||||
|
sum += Math.Abs((int)(sbyte)v);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
var v = (byte)(row[i] - previous[i]);
|
||||||
|
o[i] = v;
|
||||||
|
sum += Math.Abs((int)(sbyte)v);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 3:
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
var left = i >= bpp ? row[i - bpp] : 0;
|
||||||
|
var v = (byte)(row[i] - ((left + previous[i]) >> 1));
|
||||||
|
o[i] = v;
|
||||||
|
sum += Math.Abs((int)(sbyte)v);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
var left = i >= bpp ? row[i - bpp] : (byte)0;
|
||||||
|
var upLeft = i >= bpp ? previous[i - bpp] : (byte)0;
|
||||||
|
var v = (byte)(row[i] - PngDecoder.Paeth(left, previous[i], upLeft));
|
||||||
|
o[i] = v;
|
||||||
|
sum += Math.Abs((int)(sbyte)v);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] ExifPayload(byte[] exif)
|
||||||
|
{
|
||||||
|
ReadOnlySpan<byte> span = exif;
|
||||||
|
if (span.StartsWith("Exif\0\0"u8))
|
||||||
|
{
|
||||||
|
span = span[6..];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (span.Length < 8 || !(span.StartsWith("II*\0"u8) || span.StartsWith("MM\0*"u8)))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("EXIF must be a TIFF structure starting with «II*\\0» or «MM\\0*».", nameof(exif));
|
||||||
|
}
|
||||||
|
|
||||||
|
return span.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether <paramref name="keyword"/> can name a PNG text chunk: 1-79 printable Latin-1, no outer or double spaces.</summary>
|
||||||
|
public static bool IsValidKeyword(string keyword)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(keyword) || keyword.Length > 79 || keyword[0] == ' ' || keyword[^1] == ' ' || keyword.Contains(" ", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var c in keyword)
|
||||||
|
{
|
||||||
|
if (c is < ' ' or (> '~' and < '¡') or > 'ÿ')
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteText(Stream output, ImageText text)
|
||||||
|
{
|
||||||
|
using var payload = new MemoryStream();
|
||||||
|
payload.Write(Encoding.Latin1.GetBytes(text.Keyword));
|
||||||
|
payload.WriteByte(0);
|
||||||
|
var latin1 = text.Language.Length == 0 && text.TranslatedKeyword.Length == 0 && IsLatin1(text.Text);
|
||||||
|
if (latin1)
|
||||||
|
{
|
||||||
|
payload.Write(Encoding.Latin1.GetBytes(text.Text));
|
||||||
|
WriteChunk(output, "tEXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.WriteByte(0); // not compressed
|
||||||
|
payload.WriteByte(0); // method
|
||||||
|
payload.Write(Encoding.ASCII.GetBytes(text.Language));
|
||||||
|
payload.WriteByte(0);
|
||||||
|
payload.Write(Encoding.UTF8.GetBytes(text.TranslatedKeyword));
|
||||||
|
payload.WriteByte(0);
|
||||||
|
payload.Write(Encoding.UTF8.GetBytes(text.Text));
|
||||||
|
WriteChunk(output, "iTXt"u8, payload.GetBuffer().AsSpan(0, (int)payload.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsLatin1(string text)
|
||||||
|
{
|
||||||
|
foreach (var c in text)
|
||||||
|
{
|
||||||
|
if (c > '\u00FF' || c == '\0')
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] IccName(string name)
|
||||||
|
{
|
||||||
|
if (name.Length is < 1 or > 79 || name[0] == ' ' || name[^1] == ' ')
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The profile name must have 1 to 79 characters, without leading or trailing spaces.", nameof(name));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var c in name)
|
||||||
|
{
|
||||||
|
if (c is < ' ' or (> '~' and < '¡') or > 'ÿ')
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The profile name must be printable Latin-1.", nameof(name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Encoding.Latin1.GetBytes(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteChunk(Stream output, ReadOnlySpan<byte> type, ReadOnlySpan<byte> payload)
|
||||||
|
{
|
||||||
|
Span<byte> word = stackalloc byte[4];
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(word, (uint)payload.Length);
|
||||||
|
output.Write(word);
|
||||||
|
output.Write(type);
|
||||||
|
output.Write(payload);
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(word, Crc32.Append(Crc32.Compute(type), payload));
|
||||||
|
output.Write(word);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Collects the zlib stream and writes it out as IDAT chunks of <see cref="IdatChunkSize"/> bytes.</summary>
|
||||||
|
private sealed class IdatStream(Stream output) : Stream
|
||||||
|
{
|
||||||
|
private readonly byte[] _buffer = ArrayPool<byte>.Shared.Rent(IdatChunkSize);
|
||||||
|
private int _count;
|
||||||
|
private bool _returned;
|
||||||
|
|
||||||
|
public override bool CanRead => false;
|
||||||
|
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
|
||||||
|
public override bool CanWrite => true;
|
||||||
|
|
||||||
|
public override long Length => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Position
|
||||||
|
{
|
||||||
|
get => throw new NotSupportedException();
|
||||||
|
set => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
|
||||||
|
|
||||||
|
public override void Write(ReadOnlySpan<byte> buffer)
|
||||||
|
{
|
||||||
|
while (buffer.Length > 0)
|
||||||
|
{
|
||||||
|
var n = Math.Min(IdatChunkSize - _count, buffer.Length);
|
||||||
|
buffer[..n].CopyTo(_buffer.AsSpan(_count));
|
||||||
|
_count += n;
|
||||||
|
buffer = buffer[n..];
|
||||||
|
if (_count == IdatChunkSize)
|
||||||
|
{
|
||||||
|
Emit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the last, shorter chunk.</summary>
|
||||||
|
public void Complete()
|
||||||
|
{
|
||||||
|
if (_count > 0)
|
||||||
|
{
|
||||||
|
Emit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Flush()
|
||||||
|
{
|
||||||
|
// Chunks are written when full or at Complete: a flush of the zlib stream must not cut a chunk.
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void SetLength(long value) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
protected override void Dispose(bool disposing)
|
||||||
|
{
|
||||||
|
if (!_returned)
|
||||||
|
{
|
||||||
|
_returned = true;
|
||||||
|
ArrayPool<byte>.Shared.Return(_buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
base.Dispose(disposing);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Emit()
|
||||||
|
{
|
||||||
|
WriteChunk(output, "IDAT"u8, _buffer.AsSpan(0, _count));
|
||||||
|
_count = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A decoded image: <see cref="Width"/> × <see cref="Height"/> pixels, top row first, each pixel four bytes R, G, B, A
|
||||||
|
/// (8 bits each, alpha not premultiplied: the colour under an alpha of 0 is kept as the file had it).
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// The pixels live either in an array of exactly the right size (<see cref="RgbaImage(int, int)"/>) or in a rented
|
||||||
|
/// array (<see cref="Rent"/>: from <see cref="ArrayPool{T}.Shared"/> up to 16 MiB, a plain array above, so that very
|
||||||
|
/// large pictures are not kept by the pool), which <see cref="Dispose"/> gives back; a rented image must not be used
|
||||||
|
/// after that. Disposing an image that owns its array does nothing, so callers can always
|
||||||
|
/// dispose.
|
||||||
|
/// </remarks>
|
||||||
|
public sealed class RgbaImage : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>Bytes of one pixel.</summary>
|
||||||
|
public const int BytesPerPixel = 4;
|
||||||
|
|
||||||
|
private byte[]? _buffer;
|
||||||
|
private readonly bool _pooled;
|
||||||
|
|
||||||
|
/// <summary>A new image, every pixel (0, 0, 0, 0).</summary>
|
||||||
|
public RgbaImage(int width, int height)
|
||||||
|
: this(width, height, new byte[CheckedLength(width, height)], pooled: false)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An image over <paramref name="pixels"/>, which must hold exactly width × height × 4 bytes; not copied.</summary>
|
||||||
|
public RgbaImage(int width, int height, byte[] pixels)
|
||||||
|
: this(width, height, pixels ?? throw new ArgumentNullException(nameof(pixels)), pooled: false)
|
||||||
|
{
|
||||||
|
if (pixels.Length != CheckedLength(width, height))
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"Expected {CheckedLength(width, height)} bytes, got {pixels.Length}.", nameof(pixels));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private RgbaImage(int width, int height, byte[] buffer, bool pooled)
|
||||||
|
{
|
||||||
|
Width = width;
|
||||||
|
Height = height;
|
||||||
|
Length = width * height * BytesPerPixel;
|
||||||
|
_buffer = buffer;
|
||||||
|
_pooled = pooled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A new image whose pixels are rented (the shared array pool up to 16 MiB), every pixel (0, 0, 0, 0). Give it
|
||||||
|
/// back with <see cref="Dispose"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static RgbaImage Rent(int width, int height)
|
||||||
|
{
|
||||||
|
var length = CheckedLength(width, height);
|
||||||
|
var buffer = ImageBuffers.Rent<byte>(length);
|
||||||
|
buffer.AsSpan(0, length).Clear();
|
||||||
|
return new RgbaImage(width, height, buffer, pooled: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A new image for a decoder: size checked against <paramref name="limits"/>, pooled or not.</summary>
|
||||||
|
internal static RgbaImage Create(int width, int height, ImageLimits limits, bool pooled)
|
||||||
|
{
|
||||||
|
limits.CheckSize(width, height);
|
||||||
|
return pooled ? Rent(width, height) : new RgbaImage(width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Width in pixels.</summary>
|
||||||
|
public int Width { get; }
|
||||||
|
|
||||||
|
/// <summary>Height in pixels.</summary>
|
||||||
|
public int Height { get; }
|
||||||
|
|
||||||
|
/// <summary>Bytes of one row (<see cref="Width"/> × 4).</summary>
|
||||||
|
public int Stride => Width * BytesPerPixel;
|
||||||
|
|
||||||
|
/// <summary>Bytes of the whole image.</summary>
|
||||||
|
public int Length { get; }
|
||||||
|
|
||||||
|
/// <summary>Whether the pixels were rented with <see cref="Rent"/> (and must not be used after <see cref="Dispose"/>).</summary>
|
||||||
|
public bool IsPooled => _pooled;
|
||||||
|
|
||||||
|
/// <summary>All the pixels, row after row.</summary>
|
||||||
|
public Span<byte> Pixels => Buffer.AsSpan(0, Length);
|
||||||
|
|
||||||
|
/// <summary>The pixels of row <paramref name="y"/> (0 is the top row).</summary>
|
||||||
|
public Span<byte> GetRow(int y)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(y);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(y, Height);
|
||||||
|
return Buffer.AsSpan(y * Stride, Stride);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The pixel at (<paramref name="x"/>, <paramref name="y"/>) as R, G, B, A.</summary>
|
||||||
|
public (byte R, byte G, byte B, byte A) GetPixel(int x, int y)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(x);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(x, Width);
|
||||||
|
var row = GetRow(y);
|
||||||
|
var i = x * BytesPerPixel;
|
||||||
|
return (row[i], row[i + 1], row[i + 2], row[i + 3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether every pixel has alpha 255.</summary>
|
||||||
|
public bool IsOpaque()
|
||||||
|
{
|
||||||
|
var pixels = Pixels;
|
||||||
|
for (var i = 3; i < pixels.Length; i += BytesPerPixel)
|
||||||
|
{
|
||||||
|
if (pixels[i] != 255)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A copy of the pixels in an array of exactly <see cref="Length"/> bytes.</summary>
|
||||||
|
public byte[] ToArray() => Pixels.ToArray();
|
||||||
|
|
||||||
|
/// <summary>Gives a rented array back; the image cannot be used afterwards.</summary>
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_pooled && _buffer is { } buffer)
|
||||||
|
{
|
||||||
|
_buffer = null;
|
||||||
|
ImageBuffers.Return(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] Buffer => _buffer ?? throw new ObjectDisposedException(nameof(RgbaImage));
|
||||||
|
|
||||||
|
private static int CheckedLength(int width, int height)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height);
|
||||||
|
var length = (long)width * height * BytesPerPixel;
|
||||||
|
if (length > Array.MaxLength)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(width), $"An image of {width}×{height} does not fit in one array.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int)length;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A read-only stream over pieces of one buffer read one after the other, without copying them: the IDAT chunks of a
|
||||||
|
/// PNG, which together are a single zlib stream.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class SegmentStream(ReadOnlyMemory<byte> data, IReadOnlyList<(int Start, int Length)> segments) : Stream
|
||||||
|
{
|
||||||
|
private int _segment;
|
||||||
|
private int _offset;
|
||||||
|
|
||||||
|
public override bool CanRead => true;
|
||||||
|
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
|
||||||
|
public override bool CanWrite => false;
|
||||||
|
|
||||||
|
public override long Length => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Position
|
||||||
|
{
|
||||||
|
get => throw new NotSupportedException();
|
||||||
|
set => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
|
||||||
|
|
||||||
|
public override int Read(Span<byte> buffer)
|
||||||
|
{
|
||||||
|
var written = 0;
|
||||||
|
while (written < buffer.Length && _segment < segments.Count)
|
||||||
|
{
|
||||||
|
var (start, length) = segments[_segment];
|
||||||
|
var available = length - _offset;
|
||||||
|
if (available == 0)
|
||||||
|
{
|
||||||
|
_segment++;
|
||||||
|
_offset = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var n = Math.Min(available, buffer.Length - written);
|
||||||
|
data.Span.Slice(start + _offset, n).CopyTo(buffer[written..]);
|
||||||
|
_offset += n;
|
||||||
|
written += n;
|
||||||
|
}
|
||||||
|
|
||||||
|
return written;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int ReadByte()
|
||||||
|
{
|
||||||
|
Span<byte> one = stackalloc byte[1];
|
||||||
|
return Read(one) == 1 ? one[0] : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Flush()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void SetLength(long value) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The boolean entropy decoder of VP8 (RFC 6386 §7): each call decodes one bit whose probability of being 0 is
|
||||||
|
/// <c>prob</c>/256. The bytes are loaded several at a time into a 64-bit window; past the end of the data the decoder
|
||||||
|
/// reads zeros and counts them, so a caller can tell a stream that was cut short.
|
||||||
|
/// </summary>
|
||||||
|
internal struct Vp8BoolDecoder
|
||||||
|
{
|
||||||
|
private readonly byte[] _data;
|
||||||
|
private readonly int _end;
|
||||||
|
private int _pos;
|
||||||
|
|
||||||
|
// The bits loaded and not yet consumed: the low 8 + _bits bits of _value; the top 8 of them are the window that
|
||||||
|
// is compared with the split.
|
||||||
|
private ulong _value;
|
||||||
|
private int _bits;
|
||||||
|
private uint _range;
|
||||||
|
private int _padding;
|
||||||
|
|
||||||
|
public Vp8BoolDecoder(byte[] data, int start, int length)
|
||||||
|
{
|
||||||
|
_data = data;
|
||||||
|
_pos = start;
|
||||||
|
_end = start + length;
|
||||||
|
_value = 0;
|
||||||
|
_bits = -8;
|
||||||
|
_range = 255;
|
||||||
|
_padding = 0;
|
||||||
|
Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the decoder needed bytes past the end of its data. A stream that ends cleanly never does; one byte of
|
||||||
|
/// tolerance is given to writers that flush a little short.
|
||||||
|
/// </summary>
|
||||||
|
public readonly bool Overrun => _padding > 1;
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public int GetBit(int prob)
|
||||||
|
{
|
||||||
|
if (_bits < 0)
|
||||||
|
{
|
||||||
|
Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
var split = 1 + (((_range - 1) * (uint)prob) >> 8);
|
||||||
|
var window = (uint)(_value >> _bits);
|
||||||
|
int bit;
|
||||||
|
if (window >= split)
|
||||||
|
{
|
||||||
|
_range -= split;
|
||||||
|
_value -= (ulong)split << _bits;
|
||||||
|
bit = 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_range = split;
|
||||||
|
bit = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var shift = BitOperations.LeadingZeroCount(_range) - 24;
|
||||||
|
_range <<= shift;
|
||||||
|
_bits -= shift;
|
||||||
|
return bit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An unsigned value of <paramref name="bits"/> bits, most significant first, each with probability ½ (L(n)).</summary>
|
||||||
|
public int GetLiteral(int bits)
|
||||||
|
{
|
||||||
|
var v = 0;
|
||||||
|
while (bits-- > 0)
|
||||||
|
{
|
||||||
|
v = (v << 1) | GetBit(128);
|
||||||
|
}
|
||||||
|
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A magnitude of <paramref name="bits"/> bits followed by a sign bit, as the frame header writes deltas.</summary>
|
||||||
|
public int GetSignedLiteral(int bits)
|
||||||
|
{
|
||||||
|
var v = GetLiteral(bits);
|
||||||
|
return GetBit(128) == 1 ? -v : v;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An optional signed delta: a flag, then <see cref="GetSignedLiteral"/>; 0 when the flag is clear.</summary>
|
||||||
|
public int GetOptionalSigned(int bits) => GetBit(128) == 1 ? GetSignedLiteral(bits) : 0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A value read with a tree of RFC 6386 §8.1: pairs of children, a child ≤ 0 being the leaf −value; the
|
||||||
|
/// probability of node pair i is <c>probs[offset + i/2]</c>.
|
||||||
|
/// </summary>
|
||||||
|
public int ReadTree(ReadOnlySpan<sbyte> tree, ReadOnlySpan<byte> probs, int offset = 0)
|
||||||
|
{
|
||||||
|
var i = 0;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
i = tree[i + GetBit(probs[offset + (i >> 1)])];
|
||||||
|
}
|
||||||
|
while (i > 0);
|
||||||
|
|
||||||
|
return -i;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Fill()
|
||||||
|
{
|
||||||
|
while (_bits <= 40)
|
||||||
|
{
|
||||||
|
if (_pos < _end)
|
||||||
|
{
|
||||||
|
_value = (_value << 8) | _data[_pos++];
|
||||||
|
_bits += 8;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (_bits < 0)
|
||||||
|
{
|
||||||
|
_value <<= 8;
|
||||||
|
_bits += 8;
|
||||||
|
_padding++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,871 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes a VP8 key frame (RFC 6386), the lossy picture of a WebP file: frame header, segmentation, the intra modes of
|
||||||
|
/// every macroblock, the DCT tokens of the partitions, dequantization, the inverse WHT and DCT, intra prediction, the
|
||||||
|
/// simple or normal loop filter, then YUV 4:2:0 to RGB (BT.601) with the chroma upsampled by the triangular filter
|
||||||
|
/// ("fancy upsampling"). Alpha is not part of VP8: the pixels come out opaque.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Intra prediction reads the reconstructed pixels before the loop filter (as RFC 6386 §15 prescribes), so the whole
|
||||||
|
/// frame is reconstructed first and filtered afterwards, macroblock after macroblock in raster order.
|
||||||
|
/// </remarks>
|
||||||
|
internal sealed class Vp8Decoder
|
||||||
|
{
|
||||||
|
private const int WorkStride = 32;
|
||||||
|
private const int ChromaWorkStride = 16;
|
||||||
|
|
||||||
|
private readonly byte[] _data;
|
||||||
|
private readonly int _start;
|
||||||
|
private readonly int _length;
|
||||||
|
private readonly ImageLimits _limits;
|
||||||
|
|
||||||
|
private int _width;
|
||||||
|
private int _height;
|
||||||
|
private int _mbWidth;
|
||||||
|
private int _mbHeight;
|
||||||
|
|
||||||
|
// Header.
|
||||||
|
private bool _segmentation;
|
||||||
|
private bool _updateMap;
|
||||||
|
private bool _absoluteDeltas;
|
||||||
|
private readonly int[] _segmentQuant = new int[4];
|
||||||
|
private readonly int[] _segmentFilter = new int[4];
|
||||||
|
private readonly byte[] _segmentProbs = [255, 255, 255];
|
||||||
|
private bool _simpleFilter;
|
||||||
|
private int _filterLevel;
|
||||||
|
private int _sharpness;
|
||||||
|
private bool _useLfDelta;
|
||||||
|
private readonly int[] _refLfDelta = new int[4];
|
||||||
|
private readonly int[] _modeLfDelta = new int[4];
|
||||||
|
private bool _useSkipProb;
|
||||||
|
private int _skipProb;
|
||||||
|
private readonly byte[] _probs = new byte[Vp8Tables.CoefficientProbCount];
|
||||||
|
|
||||||
|
// Dequantization factors per segment: Y1 DC, Y1 AC, Y2 DC, Y2 AC, UV DC, UV AC.
|
||||||
|
private readonly int[] _dequant = new int[4 * 6];
|
||||||
|
|
||||||
|
// Loop filter parameters per segment and per "is B_PRED": edge limit, interior limit, high edge variance threshold.
|
||||||
|
private readonly int[] _filterParams = new int[4 * 2 * 3];
|
||||||
|
|
||||||
|
private Vp8BoolDecoder[] _partitions = [];
|
||||||
|
|
||||||
|
// Planes, macroblock aligned.
|
||||||
|
private byte[] _y = [];
|
||||||
|
private byte[] _u = [];
|
||||||
|
private byte[] _v = [];
|
||||||
|
private int _yStride;
|
||||||
|
private int _uvStride;
|
||||||
|
|
||||||
|
// Per macroblock state for the loop filter: segment, B_PRED, inner edges.
|
||||||
|
private byte[] _mbSegment = [];
|
||||||
|
private byte[] _mbFlags = [];
|
||||||
|
|
||||||
|
// Contexts.
|
||||||
|
private byte[] _intraTop = [];
|
||||||
|
private readonly byte[] _intraLeft = new byte[4];
|
||||||
|
private byte[] _nzTop = [];
|
||||||
|
private readonly byte[] _nzLeft = new byte[9];
|
||||||
|
|
||||||
|
// Current macroblock.
|
||||||
|
private int _segment;
|
||||||
|
private bool _isI4x4;
|
||||||
|
private int _yMode;
|
||||||
|
private int _uvMode;
|
||||||
|
private readonly byte[] _bModes = new byte[16];
|
||||||
|
private readonly short[] _coeffs = new short[25 * 16];
|
||||||
|
private readonly byte[] _blockData = new byte[24];
|
||||||
|
private readonly byte[] _yWork = new byte[WorkStride * 17];
|
||||||
|
private readonly byte[] _uWork = new byte[ChromaWorkStride * 9];
|
||||||
|
private readonly byte[] _vWork = new byte[ChromaWorkStride * 9];
|
||||||
|
|
||||||
|
private Vp8Decoder(byte[] data, int start, int length, ImageLimits limits)
|
||||||
|
{
|
||||||
|
_data = data;
|
||||||
|
_start = start;
|
||||||
|
_length = length;
|
||||||
|
_limits = limits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The size of a VP8 key frame, after checking its frame tag and start code.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The bytes are not a VP8 key frame that can be shown.</exception>
|
||||||
|
public static (int Width, int Height) ReadSize(ReadOnlySpan<byte> frame)
|
||||||
|
{
|
||||||
|
if (frame.Length < 10)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: l'intestazione del fotogramma VP8 è incompleta.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var tag = frame[0] | (frame[1] << 8) | (frame[2] << 16);
|
||||||
|
if ((tag & 1) != 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: il fotogramma VP8 non è un fotogramma chiave.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (((tag >> 1) & 7) > 3)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: versione VP8 sconosciuta.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (((tag >> 4) & 1) == 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: il fotogramma VP8 è segnato come da non mostrare.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (frame[3] != 0x9D || frame[4] != 0x01 || frame[5] != 0x2A)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: manca il codice d'inizio del fotogramma VP8.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var width = (frame[6] | (frame[7] << 8)) & 0x3FFF;
|
||||||
|
var height = (frame[8] | (frame[9] << 8)) & 0x3FFF;
|
||||||
|
if (width == 0 || height == 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: il fotogramma VP8 ha misura nulla.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((tag >> 5) > frame.Length - 10)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: la prima partizione VP8 finisce oltre i dati.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes the VP8 frame in <paramref name="data"/>[<paramref name="start"/>..+<paramref name="length"/>] into
|
||||||
|
/// <paramref name="target"/>, which must have the frame's size; every alpha byte is set to 255.
|
||||||
|
/// </summary>
|
||||||
|
public static void Decode(byte[] data, int start, int length, ImageLimits limits, RgbaImage target)
|
||||||
|
{
|
||||||
|
var (width, height) = ReadSize(data.AsSpan(start, length));
|
||||||
|
if (target.Width != width || target.Height != height)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The target does not have the size of the frame.", nameof(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
var decoder = new Vp8Decoder(data, start, length, limits) { _width = width, _height = height };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
decoder.Run(target);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
decoder.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Y, U and V planes of a frame after the loop filter, macroblock aligned (for tests of prediction and
|
||||||
|
/// filtering, which the RGB conversion would blur).
|
||||||
|
/// </summary>
|
||||||
|
internal static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) DecodePlanes(byte[] data, int start, int length, ImageLimits limits)
|
||||||
|
{
|
||||||
|
var (width, height) = ReadSize(data.AsSpan(start, length));
|
||||||
|
var decoder = new Vp8Decoder(data, start, length, limits) { _width = width, _height = height };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
decoder.DecodeFrame();
|
||||||
|
var luma = decoder._yStride * decoder._mbHeight * 16;
|
||||||
|
var chroma = decoder._uvStride * decoder._mbHeight * 8;
|
||||||
|
return (decoder._y.AsSpan(0, luma).ToArray(), decoder._u.AsSpan(0, chroma).ToArray(), decoder._v.AsSpan(0, chroma).ToArray(), decoder._yStride, decoder._uvStride);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
decoder.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Run(RgbaImage target)
|
||||||
|
{
|
||||||
|
DecodeFrame();
|
||||||
|
WriteRgba(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DecodeFrame()
|
||||||
|
{
|
||||||
|
_mbWidth = (_width + 15) >> 4;
|
||||||
|
_mbHeight = (_height + 15) >> 4;
|
||||||
|
_yStride = _mbWidth * 16;
|
||||||
|
_uvStride = _mbWidth * 8;
|
||||||
|
var lumaBytes = (long)_yStride * _mbHeight * 16;
|
||||||
|
_limits.CheckWorkingBytes((lumaBytes * 3 / 2) + ((long)_mbWidth * _mbHeight * 2) + (_mbWidth * 13L));
|
||||||
|
|
||||||
|
var tag = _data[_start] | (_data[_start + 1] << 8) | (_data[_start + 2] << 16);
|
||||||
|
var firstSize = tag >> 5;
|
||||||
|
var header = new Vp8BoolDecoder(_data, _start + 10, firstSize);
|
||||||
|
ParseHeader(ref header);
|
||||||
|
SetUpPartitions(_start + 10 + firstSize, _length - 10 - firstSize);
|
||||||
|
|
||||||
|
_y = ImageBuffers.Rent<byte>((int)lumaBytes);
|
||||||
|
_u = ImageBuffers.Rent<byte>((int)(lumaBytes / 4));
|
||||||
|
_v = ImageBuffers.Rent<byte>((int)(lumaBytes / 4));
|
||||||
|
_mbSegment = ImageBuffers.Rent<byte>(_mbWidth * _mbHeight);
|
||||||
|
_mbFlags = ImageBuffers.Rent<byte>(_mbWidth * _mbHeight);
|
||||||
|
_intraTop = ImageBuffers.Rent<byte>(_mbWidth * 4);
|
||||||
|
_nzTop = ImageBuffers.Rent<byte>(_mbWidth * 9);
|
||||||
|
_intraTop.AsSpan(0, _mbWidth * 4).Fill(Vp8Tables.BDc);
|
||||||
|
_nzTop.AsSpan(0, _mbWidth * 9).Clear();
|
||||||
|
|
||||||
|
for (var mbY = 0; mbY < _mbHeight; mbY++)
|
||||||
|
{
|
||||||
|
ref var tokens = ref _partitions[mbY & (_partitions.Length - 1)];
|
||||||
|
_intraLeft.AsSpan().Fill(Vp8Tables.BDc);
|
||||||
|
_nzLeft.AsSpan().Clear();
|
||||||
|
for (var mbX = 0; mbX < _mbWidth; mbX++)
|
||||||
|
{
|
||||||
|
var skip = ParseModes(ref header, mbX);
|
||||||
|
var nonZero = !skip && ParseResiduals(ref tokens, mbX);
|
||||||
|
if (skip)
|
||||||
|
{
|
||||||
|
SkipResiduals(mbX);
|
||||||
|
}
|
||||||
|
|
||||||
|
var index = (mbY * _mbWidth) + mbX;
|
||||||
|
_mbSegment[index] = (byte)_segment;
|
||||||
|
_mbFlags[index] = (byte)((_isI4x4 ? 1 : 0) | (_isI4x4 || nonZero ? 2 : 0));
|
||||||
|
Reconstruct(mbX, mbY, nonZero);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (header.Overrun || tokens.Overrun)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: i dati VP8 finiscono prima dell'ultimo macroblocco.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_filterLevel > 0)
|
||||||
|
{
|
||||||
|
Vp8LoopFilter.Apply(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Release()
|
||||||
|
{
|
||||||
|
foreach (var array in new[] { _y, _u, _v, _mbSegment, _mbFlags, _intraTop, _nzTop })
|
||||||
|
{
|
||||||
|
if (array.Length > 0)
|
||||||
|
{
|
||||||
|
ImageBuffers.Return(array);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_y = _u = _v = _mbSegment = _mbFlags = _intraTop = _nzTop = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ParseHeader(ref Vp8BoolDecoder br)
|
||||||
|
{
|
||||||
|
br.GetBit(128); // colour space: only 0 (YUV) is defined, and decoders ignore it
|
||||||
|
br.GetBit(128); // clamping type: clamping is always done
|
||||||
|
|
||||||
|
_segmentation = br.GetBit(128) == 1;
|
||||||
|
if (_segmentation)
|
||||||
|
{
|
||||||
|
_updateMap = br.GetBit(128) == 1;
|
||||||
|
var updateData = br.GetBit(128) == 1;
|
||||||
|
if (updateData)
|
||||||
|
{
|
||||||
|
_absoluteDeltas = br.GetBit(128) == 1;
|
||||||
|
for (var s = 0; s < 4; s++)
|
||||||
|
{
|
||||||
|
_segmentQuant[s] = br.GetOptionalSigned(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var s = 0; s < 4; s++)
|
||||||
|
{
|
||||||
|
_segmentFilter[s] = br.GetOptionalSigned(6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_updateMap)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 3; i++)
|
||||||
|
{
|
||||||
|
_segmentProbs[i] = br.GetBit(128) == 1 ? (byte)br.GetLiteral(8) : (byte)255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_simpleFilter = br.GetBit(128) == 1;
|
||||||
|
_filterLevel = br.GetLiteral(6);
|
||||||
|
_sharpness = br.GetLiteral(3);
|
||||||
|
_useLfDelta = br.GetBit(128) == 1;
|
||||||
|
if (_useLfDelta && br.GetBit(128) == 1)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
if (br.GetBit(128) == 1)
|
||||||
|
{
|
||||||
|
_refLfDelta[i] = br.GetSignedLiteral(6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
if (br.GetBit(128) == 1)
|
||||||
|
{
|
||||||
|
_modeLfDelta[i] = br.GetSignedLiteral(6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var partitionCount = 1 << br.GetLiteral(2);
|
||||||
|
_partitions = new Vp8BoolDecoder[partitionCount];
|
||||||
|
|
||||||
|
var baseQ = br.GetLiteral(7);
|
||||||
|
var yDc = br.GetOptionalSigned(4);
|
||||||
|
var y2Dc = br.GetOptionalSigned(4);
|
||||||
|
var y2Ac = br.GetOptionalSigned(4);
|
||||||
|
var uvDc = br.GetOptionalSigned(4);
|
||||||
|
var uvAc = br.GetOptionalSigned(4);
|
||||||
|
for (var s = 0; s < 4; s++)
|
||||||
|
{
|
||||||
|
var q = !_segmentation ? baseQ : _absoluteDeltas ? _segmentQuant[s] : baseQ + _segmentQuant[s];
|
||||||
|
var d = _dequant.AsSpan(s * 6, 6);
|
||||||
|
d[0] = Vp8Tables.DcQuant[QIndex(q + yDc)];
|
||||||
|
d[1] = Vp8Tables.AcQuant[QIndex(q)];
|
||||||
|
d[2] = Vp8Tables.DcQuant[QIndex(q + y2Dc)] * 2;
|
||||||
|
d[3] = Math.Max(8, Vp8Tables.AcQuant[QIndex(q + y2Ac)] * 155 / 100);
|
||||||
|
d[4] = Math.Min(132, (int)Vp8Tables.DcQuant[QIndex(q + uvDc)]);
|
||||||
|
d[5] = Vp8Tables.AcQuant[QIndex(q + uvAc)];
|
||||||
|
}
|
||||||
|
|
||||||
|
br.GetBit(128); // refresh_entropy_probs: there is no later frame to keep them for
|
||||||
|
|
||||||
|
Vp8Tables.DefaultCoefficientProbs.CopyTo(_probs);
|
||||||
|
var update = Vp8Tables.CoefficientUpdateProbs;
|
||||||
|
for (var i = 0; i < _probs.Length; i++)
|
||||||
|
{
|
||||||
|
if (br.GetBit(update[i]) == 1)
|
||||||
|
{
|
||||||
|
_probs[i] = (byte)br.GetLiteral(8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_useSkipProb = br.GetBit(128) == 1;
|
||||||
|
_skipProb = _useSkipProb ? br.GetLiteral(8) : 0;
|
||||||
|
|
||||||
|
if (br.Overrun)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: l'intestazione VP8 finisce prima del tempo.");
|
||||||
|
}
|
||||||
|
|
||||||
|
ComputeFilterParams();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int QIndex(int q) => Math.Clamp(q, 0, 127);
|
||||||
|
|
||||||
|
private void ComputeFilterParams()
|
||||||
|
{
|
||||||
|
if (_filterLevel == 0)
|
||||||
|
{
|
||||||
|
// A frame loop_filter_level of 0 turns the filter off for the whole frame, whatever the segment levels and
|
||||||
|
// the deltas would give (as libvpx, libwebp and the RFC 6386 reference decoder do).
|
||||||
|
Array.Clear(_filterParams);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var s = 0; s < 4; s++)
|
||||||
|
{
|
||||||
|
var baseLevel = !_segmentation ? _filterLevel : _absoluteDeltas ? _segmentFilter[s] : _filterLevel + _segmentFilter[s];
|
||||||
|
for (var i4x4 = 0; i4x4 < 2; i4x4++)
|
||||||
|
{
|
||||||
|
var level = baseLevel;
|
||||||
|
if (_useLfDelta)
|
||||||
|
{
|
||||||
|
level += _refLfDelta[0];
|
||||||
|
if (i4x4 == 1)
|
||||||
|
{
|
||||||
|
level += _modeLfDelta[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
level = Math.Clamp(level, 0, 63);
|
||||||
|
var p = _filterParams.AsSpan(((s * 2) + i4x4) * 3, 3);
|
||||||
|
if (level == 0)
|
||||||
|
{
|
||||||
|
p.Clear();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var interior = level;
|
||||||
|
if (_sharpness > 0)
|
||||||
|
{
|
||||||
|
interior >>= _sharpness > 4 ? 2 : 1;
|
||||||
|
interior = Math.Min(interior, 9 - _sharpness);
|
||||||
|
}
|
||||||
|
|
||||||
|
interior = Math.Max(interior, 1);
|
||||||
|
p[0] = (2 * level) + interior;
|
||||||
|
p[1] = interior;
|
||||||
|
p[2] = level >= 40 ? 2 : level >= 15 ? 1 : 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetUpPartitions(int start, int length)
|
||||||
|
{
|
||||||
|
var count = _partitions.Length;
|
||||||
|
var sizesLength = 3 * (count - 1);
|
||||||
|
if (length < sizesLength)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: mancano le misure delle partizioni VP8.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var pos = start + sizesLength;
|
||||||
|
var left = length - sizesLength;
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
int size;
|
||||||
|
if (i < count - 1)
|
||||||
|
{
|
||||||
|
var at = start + (3 * i);
|
||||||
|
size = _data[at] | (_data[at + 1] << 8) | (_data[at + 2] << 16);
|
||||||
|
if (size > left)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: una partizione VP8 finisce oltre i dati.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
size = left;
|
||||||
|
}
|
||||||
|
|
||||||
|
_partitions[i] = new Vp8BoolDecoder(_data, pos, size);
|
||||||
|
pos += size;
|
||||||
|
left -= size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reads the segment, skip flag and modes of a macroblock from the first partition; returns the skip flag.
|
||||||
|
private bool ParseModes(ref Vp8BoolDecoder br, int mbX)
|
||||||
|
{
|
||||||
|
if (_updateMap)
|
||||||
|
{
|
||||||
|
_segment = br.GetBit(_segmentProbs[0]) == 0 ? br.GetBit(_segmentProbs[1]) : 2 + br.GetBit(_segmentProbs[2]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_segment = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var skip = _useSkipProb && br.GetBit(_skipProb) == 1;
|
||||||
|
var top = _intraTop.AsSpan(mbX * 4, 4);
|
||||||
|
_isI4x4 = br.GetBit(145) == 0;
|
||||||
|
if (!_isI4x4)
|
||||||
|
{
|
||||||
|
_yMode = br.GetBit(156) == 1
|
||||||
|
? (br.GetBit(128) == 1 ? Vp8Tables.TmPred : Vp8Tables.HPred)
|
||||||
|
: (br.GetBit(163) == 1 ? Vp8Tables.VPred : Vp8Tables.DcPred);
|
||||||
|
var implied = (byte)(_yMode switch
|
||||||
|
{
|
||||||
|
Vp8Tables.VPred => Vp8Tables.BVe,
|
||||||
|
Vp8Tables.HPred => Vp8Tables.BHe,
|
||||||
|
Vp8Tables.TmPred => Vp8Tables.BTm,
|
||||||
|
_ => Vp8Tables.BDc,
|
||||||
|
});
|
||||||
|
top.Fill(implied);
|
||||||
|
_intraLeft.AsSpan().Fill(implied);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_yMode = Vp8Tables.BPred;
|
||||||
|
var probs = Vp8Tables.KeyFrameBModeProbs;
|
||||||
|
for (var row = 0; row < 4; row++)
|
||||||
|
{
|
||||||
|
for (var col = 0; col < 4; col++)
|
||||||
|
{
|
||||||
|
var mode = br.ReadTree(Vp8Tables.BModeTree, probs, ((top[col] * Vp8Tables.NumBModes) + _intraLeft[row]) * 9);
|
||||||
|
top[col] = (byte)mode;
|
||||||
|
_intraLeft[row] = (byte)mode;
|
||||||
|
_bModes[(row * 4) + col] = (byte)mode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_uvMode = br.GetBit(142) == 0 ? Vp8Tables.DcPred
|
||||||
|
: br.GetBit(114) == 0 ? Vp8Tables.VPred
|
||||||
|
: br.GetBit(183) == 1 ? Vp8Tables.TmPred : Vp8Tables.HPred;
|
||||||
|
return skip;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SkipResiduals(int mbX)
|
||||||
|
{
|
||||||
|
var top = _nzTop.AsSpan(mbX * 9, 9);
|
||||||
|
top[..8].Clear();
|
||||||
|
_nzLeft.AsSpan(0, 8).Clear();
|
||||||
|
if (!_isI4x4)
|
||||||
|
{
|
||||||
|
top[8] = 0;
|
||||||
|
_nzLeft[8] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
_blockData.AsSpan().Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reads the DCT tokens of a macroblock, dequantized, into _coeffs; returns whether any block has data.
|
||||||
|
private bool ParseResiduals(ref Vp8BoolDecoder br, int mbX)
|
||||||
|
{
|
||||||
|
var coeffs = _coeffs.AsSpan();
|
||||||
|
coeffs.Clear();
|
||||||
|
var top = _nzTop.AsSpan(mbX * 9, 9);
|
||||||
|
var left = _nzLeft.AsSpan();
|
||||||
|
var q = _dequant.AsSpan(_segment * 6, 6);
|
||||||
|
var any = false;
|
||||||
|
|
||||||
|
int first;
|
||||||
|
int yType;
|
||||||
|
if (!_isI4x4)
|
||||||
|
{
|
||||||
|
var dc = coeffs.Slice(24 * 16, 16);
|
||||||
|
var nz = GetCoefficients(ref br, 1, top[8] + left[8], 0, q[2], q[3], dc);
|
||||||
|
top[8] = left[8] = (byte)(nz > 0 ? 1 : 0);
|
||||||
|
Vp8Transforms.InverseWht(dc, coeffs);
|
||||||
|
first = 1;
|
||||||
|
yType = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
first = 0;
|
||||||
|
yType = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var row = 0; row < 4; row++)
|
||||||
|
{
|
||||||
|
for (var col = 0; col < 4; col++)
|
||||||
|
{
|
||||||
|
var block = coeffs.Slice(((row * 4) + col) * 16, 16);
|
||||||
|
var nz = GetCoefficients(ref br, yType, top[col] + left[row], first, q[0], q[1], block);
|
||||||
|
var flag = nz > first;
|
||||||
|
top[col] = left[row] = (byte)(flag ? 1 : 0);
|
||||||
|
var data = nz > 1 ? 2 : block[0] != 0 ? 1 : 0;
|
||||||
|
_blockData[(row * 4) + col] = (byte)data;
|
||||||
|
any |= data != 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var plane = 0; plane < 2; plane++)
|
||||||
|
{
|
||||||
|
for (var row = 0; row < 2; row++)
|
||||||
|
{
|
||||||
|
for (var col = 0; col < 2; col++)
|
||||||
|
{
|
||||||
|
var index = 16 + (plane * 4) + (row * 2) + col;
|
||||||
|
var block = coeffs.Slice(index * 16, 16);
|
||||||
|
var t = 4 + (plane * 2) + col;
|
||||||
|
var l = 4 + (plane * 2) + row;
|
||||||
|
var nz = GetCoefficients(ref br, 2, top[t] + left[l], 0, q[4], q[5], block);
|
||||||
|
top[t] = left[l] = (byte)(nz > 0 ? 1 : 0);
|
||||||
|
var data = nz > 1 ? 2 : nz == 1 ? 1 : 0;
|
||||||
|
_blockData[index] = (byte)data;
|
||||||
|
any |= data != 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 6386 §13: the tokens of one block, from position `first`; returns the position after the last token read
|
||||||
|
// that was not an end of block (`first` when the block is empty).
|
||||||
|
private int GetCoefficients(ref Vp8BoolDecoder br, int type, int context, int first, int dcQuant, int acQuant, Span<short> block)
|
||||||
|
{
|
||||||
|
var probs = _probs;
|
||||||
|
var typeBase = type * 8 * 3 * 11;
|
||||||
|
var bands = Vp8Tables.Bands;
|
||||||
|
var zigzag = Vp8Tables.Zigzag;
|
||||||
|
var n = first;
|
||||||
|
var p = typeBase + (((bands[n] * 3) + context) * 11);
|
||||||
|
while (n < 16)
|
||||||
|
{
|
||||||
|
if (br.GetBit(probs[p]) == 0)
|
||||||
|
{
|
||||||
|
return n; // end of block
|
||||||
|
}
|
||||||
|
|
||||||
|
while (br.GetBit(probs[p + 1]) == 0)
|
||||||
|
{
|
||||||
|
// DCT_0: the next token cannot be an end of block.
|
||||||
|
if (++n == 16)
|
||||||
|
{
|
||||||
|
return 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
p = typeBase + (bands[n] * 3 * 11);
|
||||||
|
}
|
||||||
|
|
||||||
|
int value;
|
||||||
|
int next;
|
||||||
|
if (br.GetBit(probs[p + 2]) == 0)
|
||||||
|
{
|
||||||
|
value = 1;
|
||||||
|
next = 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
value = LargeValue(ref br, probs.AsSpan(p, 11));
|
||||||
|
next = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (br.GetBit(128) == 1)
|
||||||
|
{
|
||||||
|
value = -value;
|
||||||
|
}
|
||||||
|
|
||||||
|
block[zigzag[n]] = (short)Math.Clamp(value * (n > 0 ? acQuant : dcQuant), short.MinValue, short.MaxValue);
|
||||||
|
n++;
|
||||||
|
p = typeBase + (((bands[n] * 3) + next) * 11);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tokens above DCT_1 (RFC 6386 §13.2): DCT_2 to DCT_4 and the categories with their extra bits.
|
||||||
|
private static int LargeValue(ref Vp8BoolDecoder br, ReadOnlySpan<byte> p)
|
||||||
|
{
|
||||||
|
if (br.GetBit(p[3]) == 0)
|
||||||
|
{
|
||||||
|
return br.GetBit(p[4]) == 0 ? 2 : 3 + br.GetBit(p[5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (br.GetBit(p[6]) == 0)
|
||||||
|
{
|
||||||
|
if (br.GetBit(p[7]) == 0)
|
||||||
|
{
|
||||||
|
return 5 + br.GetBit(159); // DCT_CAT1
|
||||||
|
}
|
||||||
|
|
||||||
|
var v = 7 + (2 * br.GetBit(165)); // DCT_CAT2
|
||||||
|
return v + br.GetBit(145);
|
||||||
|
}
|
||||||
|
|
||||||
|
var high = br.GetBit(p[8]);
|
||||||
|
var low = br.GetBit(p[9 + high]);
|
||||||
|
var category = (2 * high) + low;
|
||||||
|
var extra = category switch
|
||||||
|
{
|
||||||
|
0 => Vp8Tables.Cat3,
|
||||||
|
1 => Vp8Tables.Cat4,
|
||||||
|
2 => Vp8Tables.Cat5,
|
||||||
|
_ => Vp8Tables.Cat6,
|
||||||
|
};
|
||||||
|
var value = 0;
|
||||||
|
foreach (var prob in extra)
|
||||||
|
{
|
||||||
|
value = (value << 1) | br.GetBit(prob);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value + 3 + (8 << category);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Reconstruct(int mbX, int mbY, bool hasCoefficients)
|
||||||
|
{
|
||||||
|
LoadEdges(mbX, mbY);
|
||||||
|
var y = _yWork.AsSpan();
|
||||||
|
var coeffs = _coeffs.AsSpan();
|
||||||
|
if (_isI4x4)
|
||||||
|
{
|
||||||
|
// Subblocks of the right column use the pixels above-right of the macroblock in every row.
|
||||||
|
var topRight = y.Slice(17, 4);
|
||||||
|
topRight.CopyTo(y.Slice((4 * WorkStride) + 17, 4));
|
||||||
|
topRight.CopyTo(y.Slice((8 * WorkStride) + 17, 4));
|
||||||
|
topRight.CopyTo(y.Slice((12 * WorkStride) + 17, 4));
|
||||||
|
for (var b = 0; b < 16; b++)
|
||||||
|
{
|
||||||
|
var at = ((1 + ((b >> 2) * 4)) * WorkStride) + 1 + ((b & 3) * 4);
|
||||||
|
Vp8Predict.Sub4x4(y, at, WorkStride, _bModes[b]);
|
||||||
|
if (hasCoefficients)
|
||||||
|
{
|
||||||
|
Vp8Transforms.AddBlock(coeffs.Slice(b * 16, 16), _blockData[b], y, at, WorkStride);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Vp8Predict.Block(y, WorkStride + 1, WorkStride, 16, _yMode, mbX > 0, mbY > 0);
|
||||||
|
if (hasCoefficients)
|
||||||
|
{
|
||||||
|
for (var b = 0; b < 16; b++)
|
||||||
|
{
|
||||||
|
var at = ((1 + ((b >> 2) * 4)) * WorkStride) + 1 + ((b & 3) * 4);
|
||||||
|
Vp8Transforms.AddBlock(coeffs.Slice(b * 16, 16), _blockData[b], y, at, WorkStride);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Vp8Predict.Block(_uWork, ChromaWorkStride + 1, ChromaWorkStride, 8, _uvMode, mbX > 0, mbY > 0);
|
||||||
|
Vp8Predict.Block(_vWork, ChromaWorkStride + 1, ChromaWorkStride, 8, _uvMode, mbX > 0, mbY > 0);
|
||||||
|
if (hasCoefficients)
|
||||||
|
{
|
||||||
|
for (var b = 0; b < 4; b++)
|
||||||
|
{
|
||||||
|
var at = ((1 + ((b >> 1) * 4)) * ChromaWorkStride) + 1 + ((b & 1) * 4);
|
||||||
|
Vp8Transforms.AddBlock(coeffs.Slice((16 + b) * 16, 16), _blockData[16 + b], _uWork, at, ChromaWorkStride);
|
||||||
|
Vp8Transforms.AddBlock(coeffs.Slice((20 + b) * 16, 16), _blockData[20 + b], _vWork, at, ChromaWorkStride);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
StoreBlock(_yWork, WorkStride, 16, _y, _yStride, mbX * 16, mbY * 16);
|
||||||
|
StoreBlock(_uWork, ChromaWorkStride, 8, _u, _uvStride, mbX * 8, mbY * 8);
|
||||||
|
StoreBlock(_vWork, ChromaWorkStride, 8, _v, _uvStride, mbX * 8, mbY * 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fills the row above (with the above-left pixel and, for luma, four above-right pixels) and the column to the
|
||||||
|
// left of the work buffers: neighbouring pixels where they exist, 127 above the frame and 129 left of it.
|
||||||
|
private void LoadEdges(int mbX, int mbY)
|
||||||
|
{
|
||||||
|
LoadEdges(_yWork, WorkStride, 16, _y, _yStride, mbX, mbY, topRight: true);
|
||||||
|
LoadEdges(_uWork, ChromaWorkStride, 8, _u, _uvStride, mbX, mbY, topRight: false);
|
||||||
|
LoadEdges(_vWork, ChromaWorkStride, 8, _v, _uvStride, mbX, mbY, topRight: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadEdges(byte[] work, int workStride, int size, byte[] plane, int stride, int mbX, int mbY, bool topRight)
|
||||||
|
{
|
||||||
|
var x = mbX * size;
|
||||||
|
var y = mbY * size;
|
||||||
|
var extra = topRight ? 4 : 0;
|
||||||
|
if (mbY == 0)
|
||||||
|
{
|
||||||
|
work.AsSpan(0, 1 + size + extra).Fill(127);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var above = (y - 1) * stride;
|
||||||
|
work[0] = mbX > 0 ? plane[above + x - 1] : (byte)129;
|
||||||
|
plane.AsSpan(above + x, size).CopyTo(work.AsSpan(1, size));
|
||||||
|
if (topRight)
|
||||||
|
{
|
||||||
|
if (mbX < _mbWidth - 1)
|
||||||
|
{
|
||||||
|
plane.AsSpan(above + x + size, 4).CopyTo(work.AsSpan(1 + size, 4));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
work.AsSpan(1 + size, 4).Fill(plane[above + x + size - 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var r = 0; r < size; r++)
|
||||||
|
{
|
||||||
|
work[((r + 1) * workStride)] = mbX > 0 ? plane[((y + r) * stride) + x - 1] : (byte)129;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StoreBlock(byte[] work, int workStride, int size, byte[] plane, int stride, int x, int y)
|
||||||
|
{
|
||||||
|
for (var r = 0; r < size; r++)
|
||||||
|
{
|
||||||
|
work.AsSpan(((r + 1) * workStride) + 1, size).CopyTo(plane.AsSpan(((y + r) * stride) + x, size));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// YUV 4:2:0 to RGBA, BT.601 with the studio range of VP8; each chroma sample is interpolated from the four
|
||||||
|
// nearest with weights 9, 3, 3, 1 (chroma sited between the luma samples, edges replicated).
|
||||||
|
private void WriteRgba(RgbaImage target)
|
||||||
|
{
|
||||||
|
var width = _width;
|
||||||
|
var height = _height;
|
||||||
|
var chromaWidth = (width + 1) >> 1;
|
||||||
|
var chromaHeight = (height + 1) >> 1;
|
||||||
|
var pool = ArrayPool<int>.Shared;
|
||||||
|
var rowU = pool.Rent(chromaWidth);
|
||||||
|
var rowV = pool.Rent(chromaWidth);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
var cy = y >> 1;
|
||||||
|
var cy2 = (y & 1) == 1 ? Math.Min(cy + 1, chromaHeight - 1) : Math.Max(cy - 1, 0);
|
||||||
|
var u0 = _u.AsSpan(cy * _uvStride, chromaWidth);
|
||||||
|
var u1 = _u.AsSpan(cy2 * _uvStride, chromaWidth);
|
||||||
|
var v0 = _v.AsSpan(cy * _uvStride, chromaWidth);
|
||||||
|
var v1 = _v.AsSpan(cy2 * _uvStride, chromaWidth);
|
||||||
|
var ru = rowU.AsSpan(0, chromaWidth);
|
||||||
|
var rv = rowV.AsSpan(0, chromaWidth);
|
||||||
|
for (var i = 0; i < chromaWidth; i++)
|
||||||
|
{
|
||||||
|
ru[i] = (3 * u0[i]) + u1[i];
|
||||||
|
rv[i] = (3 * v0[i]) + v1[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
var luma = _y.AsSpan(y * _yStride, width);
|
||||||
|
var output = target.GetRow(y);
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
var cx = x >> 1;
|
||||||
|
var cx2 = (x & 1) == 1 ? Math.Min(cx + 1, chromaWidth - 1) : Math.Max(cx - 1, 0);
|
||||||
|
var u = ((3 * ru[cx]) + ru[cx2] + 8) >> 4;
|
||||||
|
var v = ((3 * rv[cx]) + rv[cx2] + 8) >> 4;
|
||||||
|
YuvToRgb.Write(luma[x], u, v, output.Slice(x * 4, 4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
pool.Return(rowU);
|
||||||
|
pool.Return(rowV);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Accessors for the loop filter.
|
||||||
|
internal int MbWidth => _mbWidth;
|
||||||
|
|
||||||
|
internal int MbHeight => _mbHeight;
|
||||||
|
|
||||||
|
internal bool SimpleFilter => _simpleFilter;
|
||||||
|
|
||||||
|
internal byte[] YPlane => _y;
|
||||||
|
|
||||||
|
internal byte[] UPlane => _u;
|
||||||
|
|
||||||
|
internal byte[] VPlane => _v;
|
||||||
|
|
||||||
|
internal int YStride => _yStride;
|
||||||
|
|
||||||
|
internal int UvStride => _uvStride;
|
||||||
|
|
||||||
|
/// <summary>Edge limit, interior limit and threshold for a macroblock, and whether its inner edges are filtered.</summary>
|
||||||
|
internal (int Limit, int Interior, int HevThreshold, bool Inner) FilterOf(int mbIndex)
|
||||||
|
{
|
||||||
|
var flags = _mbFlags[mbIndex];
|
||||||
|
var p = _filterParams.AsSpan(((_mbSegment[mbIndex] * 2) + (flags & 1)) * 3, 3);
|
||||||
|
return (p[0], p[1], p[2], (flags & 2) != 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>BT.601 YUV (studio range) to RGB in 16-bit fixed point.</summary>
|
||||||
|
internal static class YuvToRgb
|
||||||
|
{
|
||||||
|
private static readonly int[] YTerm = Table(i => (76309 * (i - 16)) + 32768);
|
||||||
|
private static readonly int[] RFromV = Table(i => 104597 * (i - 128));
|
||||||
|
private static readonly int[] GFromU = Table(i => -25675 * (i - 128));
|
||||||
|
private static readonly int[] GFromV = Table(i => -53279 * (i - 128));
|
||||||
|
private static readonly int[] BFromU = Table(i => 132201 * (i - 128));
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
public static void Write(int y, int u, int v, Span<byte> rgba)
|
||||||
|
{
|
||||||
|
var yy = YTerm[y];
|
||||||
|
rgba[0] = Clamp((yy + RFromV[v]) >> 16);
|
||||||
|
rgba[1] = Clamp((yy + GFromU[u] + GFromV[v]) >> 16);
|
||||||
|
rgba[2] = Clamp((yy + BFromU[u]) >> 16);
|
||||||
|
rgba[3] = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static byte Clamp(int v) => (uint)v <= 255 ? (byte)v : v < 0 ? (byte)0 : (byte)255;
|
||||||
|
|
||||||
|
private static int[] Table(Func<int, int> f)
|
||||||
|
{
|
||||||
|
var table = new int[256];
|
||||||
|
for (var i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
table[i] = f(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,721 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes WebP lossless (VP8L, RFC 9649 §3): transforms (predictor, colour, subtract green, colour indexing with
|
||||||
|
/// pixel bundling), the colour cache, meta prefix codes and the LZ77 backward references of the entropy-coded
|
||||||
|
/// image. Also decodes the headerless image stream that carries compressed alpha in an ALPH chunk.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class Vp8LDecoder
|
||||||
|
{
|
||||||
|
/// <summary>The byte every VP8L bitstream starts with.</summary>
|
||||||
|
public const byte Signature = 0x2F;
|
||||||
|
|
||||||
|
private const int NumLengthCodes = 24;
|
||||||
|
private const int NumDistanceCodes = 40;
|
||||||
|
private const int MaxCacheBits = 11;
|
||||||
|
private const uint HashMultiplier = 0x1E35A7BD;
|
||||||
|
|
||||||
|
private static ReadOnlySpan<byte> CodeLengthOrder => [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
|
||||||
|
|
||||||
|
// RFC 9649 §3.6: the 120 short distance codes as (dx, dy), dx first: distance = dx + dy * width.
|
||||||
|
private static ReadOnlySpan<sbyte> DistanceMap =>
|
||||||
|
[
|
||||||
|
0, 1, 1, 0, 1, 1, -1, 1, 0, 2, 2, 0, 1, 2,
|
||||||
|
-1, 2, 2, 1, -2, 1, 2, 2, -2, 2, 0, 3, 3, 0,
|
||||||
|
1, 3, -1, 3, 3, 1, -3, 1, 2, 3, -2, 3, 3, 2,
|
||||||
|
-3, 2, 0, 4, 4, 0, 1, 4, -1, 4, 4, 1, -4, 1,
|
||||||
|
3, 3, -3, 3, 2, 4, -2, 4, 4, 2, -4, 2, 0, 5,
|
||||||
|
3, 4, -3, 4, 4, 3, -4, 3, 5, 0, 1, 5, -1, 5,
|
||||||
|
5, 1, -5, 1, 2, 5, -2, 5, 5, 2, -5, 2, 4, 4,
|
||||||
|
-4, 4, 3, 5, -3, 5, 5, 3, -5, 3, 0, 6, 6, 0,
|
||||||
|
1, 6, -1, 6, 6, 1, -6, 1, 2, 6, -2, 6, 6, 2,
|
||||||
|
-6, 2, 4, 5, -4, 5, 5, 4, -5, 4, 3, 6, -3, 6,
|
||||||
|
6, 3, -6, 3, 0, 7, 7, 0, 1, 7, -1, 7, 5, 5,
|
||||||
|
-5, 5, 7, 1, -7, 1, 4, 6, -4, 6, 6, 4, -6, 4,
|
||||||
|
2, 7, -2, 7, 7, 2, -7, 2, 3, 7, -3, 7, 7, 3,
|
||||||
|
-7, 3, 5, 6, -5, 6, 6, 5, -6, 5, 8, 0, 4, 7,
|
||||||
|
-4, 7, 7, 4, -7, 4, 8, 1, 8, 2, 6, 6, -6, 6,
|
||||||
|
8, 3, 5, 7, -5, 7, 7, 5, -7, 5, 8, 4, 6, 7,
|
||||||
|
-6, 7, 7, 6, -7, 6, 8, 5, 7, 7, -7, 7, 8, 6,
|
||||||
|
8, 7,
|
||||||
|
];
|
||||||
|
|
||||||
|
private readonly Vp8LBitReader _br;
|
||||||
|
private readonly ImageLimits _limits;
|
||||||
|
private long _budget;
|
||||||
|
|
||||||
|
private Vp8LDecoder(byte[] data, int start, int length, ImageLimits limits)
|
||||||
|
{
|
||||||
|
_br = new Vp8LBitReader(data, start, length);
|
||||||
|
_limits = limits;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Size and alpha hint of a VP8L bitstream, from its five-byte header.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The bytes are not a VP8L header.</exception>
|
||||||
|
public static (int Width, int Height, bool AlphaUsed) ReadHeader(ReadOnlySpan<byte> data)
|
||||||
|
{
|
||||||
|
if (data.Length < 5)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: l'intestazione VP8L è incompleta.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data[0] != Signature)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: manca la firma del flusso VP8L.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var bits = (uint)(data[1] | (data[2] << 8) | (data[3] << 16) | (data[4] << 24));
|
||||||
|
if (bits >> 29 != 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: versione VP8L sconosciuta.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return ((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1, ((bits >> 28) & 1) == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a whole VP8L bitstream into <paramref name="target"/>, which must have its size.</summary>
|
||||||
|
public static void Decode(byte[] data, int start, int length, ImageLimits limits, RgbaImage target)
|
||||||
|
{
|
||||||
|
var (width, height, _) = ReadHeader(data.AsSpan(start, length));
|
||||||
|
if (target.Width != width || target.Height != height)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The target does not have the size of the image.", nameof(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
var decoder = new Vp8LDecoder(data, start + 5, length - 5, limits);
|
||||||
|
var argb = decoder.DecodeImage(width, height);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pixels = argb.AsSpan(0, width * height);
|
||||||
|
var output = target.Pixels;
|
||||||
|
for (var i = 0; i < pixels.Length; i++)
|
||||||
|
{
|
||||||
|
var p = pixels[i];
|
||||||
|
var o = i * 4;
|
||||||
|
output[o] = (byte)(p >> 16);
|
||||||
|
output[o + 1] = (byte)(p >> 8);
|
||||||
|
output[o + 2] = (byte)p;
|
||||||
|
output[o + 3] = (byte)(p >> 24);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ImageBuffers.Return(argb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes the image stream of an ALPH chunk compressed with VP8L (no signature, no size: the size is the
|
||||||
|
/// frame's); the alpha values are the green channel.
|
||||||
|
/// </summary>
|
||||||
|
public static void DecodeAlpha(byte[] data, int start, int length, int width, int height, ImageLimits limits, Span<byte> alpha)
|
||||||
|
{
|
||||||
|
var decoder = new Vp8LDecoder(data, start, length, limits);
|
||||||
|
var argb = decoder.DecodeImage(width, height);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pixels = argb.AsSpan(0, width * height);
|
||||||
|
for (var i = 0; i < pixels.Length; i++)
|
||||||
|
{
|
||||||
|
alpha[i] = (byte)(pixels[i] >> 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ImageBuffers.Return(argb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum TransformType
|
||||||
|
{
|
||||||
|
Predictor = 0,
|
||||||
|
Color = 1,
|
||||||
|
SubtractGreen = 2,
|
||||||
|
ColorIndexing = 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record Transform(TransformType Type, int Bits, int Width, int PackedWidth, uint[] Data);
|
||||||
|
|
||||||
|
// The image of RFC 9649 §3.5 "spatially-coded image" with its transforms; a pooled array of width × height.
|
||||||
|
private uint[] DecodeImage(int width, int height)
|
||||||
|
{
|
||||||
|
_limits.CheckSize(width, height);
|
||||||
|
var pixelCount = (long)width * height;
|
||||||
|
Charge(pixelCount * 4);
|
||||||
|
var transforms = new List<Transform>(4);
|
||||||
|
var seen = 0;
|
||||||
|
var xsize = width;
|
||||||
|
while (_br.ReadBits(1) == 1)
|
||||||
|
{
|
||||||
|
var type = (TransformType)_br.ReadBits(2);
|
||||||
|
if ((seen & (1 << (int)type)) != 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: una trasformata VP8L compare due volte.");
|
||||||
|
}
|
||||||
|
|
||||||
|
seen |= 1 << (int)type;
|
||||||
|
switch (type)
|
||||||
|
{
|
||||||
|
case TransformType.Predictor:
|
||||||
|
case TransformType.Color:
|
||||||
|
{
|
||||||
|
var bits = _br.ReadBits(3) + 2;
|
||||||
|
var sub = DecodeEntropyImage(DivRoundUp(xsize, bits), DivRoundUp(height, bits));
|
||||||
|
transforms.Add(new Transform(type, bits, xsize, xsize, sub));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case TransformType.SubtractGreen:
|
||||||
|
transforms.Add(new Transform(type, 0, xsize, xsize, []));
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
var colors = _br.ReadBits(8) + 1;
|
||||||
|
var bits = colors > 16 ? 0 : colors > 4 ? 1 : colors > 2 ? 2 : 3;
|
||||||
|
var raw = DecodeEntropyImage(colors, 1);
|
||||||
|
var palette = new uint[256];
|
||||||
|
palette[0] = raw[0];
|
||||||
|
for (var i = 1; i < colors; i++)
|
||||||
|
{
|
||||||
|
palette[i] = AddPixels(raw[i], palette[i - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var packed = DivRoundUp(xsize, bits);
|
||||||
|
transforms.Add(new Transform(type, bits, xsize, packed, palette));
|
||||||
|
xsize = packed;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
var argb = ImageBuffers.Rent<uint>((int)pixelCount);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DecodeSpatial(xsize, height, argb, allowMeta: true);
|
||||||
|
for (var i = transforms.Count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
var t = transforms[i];
|
||||||
|
switch (t.Type)
|
||||||
|
{
|
||||||
|
case TransformType.Predictor:
|
||||||
|
InversePredictor(argb, t.Width, height, t.Bits, t.Data);
|
||||||
|
break;
|
||||||
|
case TransformType.Color:
|
||||||
|
InverseColor(argb, t.Width, height, t.Bits, t.Data);
|
||||||
|
break;
|
||||||
|
case TransformType.SubtractGreen:
|
||||||
|
AddGreen(argb.AsSpan(0, t.Width * height));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
InverseColorIndexing(argb, t.Width, t.PackedWidth, height, t.Bits, t.Data);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return argb;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
ImageBuffers.Return(argb);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A sub-image (transform data, entropy image, palette): colour cache allowed, no meta prefix codes.
|
||||||
|
private uint[] DecodeEntropyImage(int width, int height)
|
||||||
|
{
|
||||||
|
var count = (long)width * height;
|
||||||
|
Charge(count * 4);
|
||||||
|
var pixels = new uint[count];
|
||||||
|
DecodeSpatial(width, height, pixels, allowMeta: false);
|
||||||
|
return pixels;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DecodeSpatial(int width, int height, uint[] output, bool allowMeta)
|
||||||
|
{
|
||||||
|
var cacheBits = 0;
|
||||||
|
if (_br.ReadBits(1) == 1)
|
||||||
|
{
|
||||||
|
cacheBits = _br.ReadBits(4);
|
||||||
|
if (cacheBits is < 1 or > MaxCacheBits)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: misura della cache dei colori VP8L non valida.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var metaBits = 0;
|
||||||
|
uint[]? meta = null;
|
||||||
|
var metaWidth = 0;
|
||||||
|
var groupCount = 1;
|
||||||
|
var codedGroups = 1;
|
||||||
|
int[]? remap = null;
|
||||||
|
if (allowMeta && _br.ReadBits(1) == 1)
|
||||||
|
{
|
||||||
|
metaBits = _br.ReadBits(3) + 2;
|
||||||
|
metaWidth = DivRoundUp(width, metaBits);
|
||||||
|
meta = DecodeEntropyImage(metaWidth, DivRoundUp(height, metaBits));
|
||||||
|
var max = 0;
|
||||||
|
for (var i = 0; i < meta.Length; i++)
|
||||||
|
{
|
||||||
|
var g = (int)((meta[i] >> 8) & 0xFFFF);
|
||||||
|
meta[i] = (uint)g;
|
||||||
|
max = Math.Max(max, g);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The stream holds the codes of groups 0 to max, but the meta image may name only a few of them (one
|
||||||
|
// pixel of value 65535 asks for 65,536 groups): only the groups it names are built, renumbered densely;
|
||||||
|
// the codes of the others are read and checked, then dropped, as libwebp does.
|
||||||
|
codedGroups = max + 1;
|
||||||
|
Charge(codedGroups * 4L);
|
||||||
|
remap = new int[codedGroups];
|
||||||
|
remap.AsSpan().Fill(-1);
|
||||||
|
groupCount = 0;
|
||||||
|
for (var i = 0; i < meta.Length; i++)
|
||||||
|
{
|
||||||
|
ref var dense = ref remap[(int)meta[i]];
|
||||||
|
if (dense < 0)
|
||||||
|
{
|
||||||
|
dense = groupCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
meta[i] = (uint)dense;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckStream();
|
||||||
|
var cacheSize = cacheBits > 0 ? 1 << cacheBits : 0;
|
||||||
|
var groups = new Vp8LHuffman[groupCount * 5];
|
||||||
|
Span<int> alphabets = [256 + NumLengthCodes + cacheSize, 256, 256, 256, NumDistanceCodes];
|
||||||
|
var lengths = new byte[alphabets[0]];
|
||||||
|
for (var g = 0; g < codedGroups; g++)
|
||||||
|
{
|
||||||
|
var dense = remap is null ? g : remap[g];
|
||||||
|
for (var k = 0; k < 5; k++)
|
||||||
|
{
|
||||||
|
var code = ReadCode(alphabets[k], lengths, build: dense >= 0);
|
||||||
|
if (code is not null)
|
||||||
|
{
|
||||||
|
Charge(code.TableSize * 4L);
|
||||||
|
groups[(dense * 5) + k] = code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
DecodePixels(width, height, output, groups, meta, metaBits, metaWidth, cacheBits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads one prefix code; with <paramref name="build"/> false it is only checked, and null comes back.</summary>
|
||||||
|
private Vp8LHuffman? ReadCode(int alphabet, byte[] buffer, bool build = true)
|
||||||
|
{
|
||||||
|
var lengths = buffer.AsSpan(0, alphabet);
|
||||||
|
lengths.Clear();
|
||||||
|
if (_br.ReadBits(1) == 1)
|
||||||
|
{
|
||||||
|
// Simple code: one or two symbols, each of length 1 (a single symbol is read with zero bits).
|
||||||
|
var symbols = _br.ReadBits(1) + 1;
|
||||||
|
var first = _br.ReadBits(_br.ReadBits(1) == 1 ? 8 : 1);
|
||||||
|
if (first >= alphabet)
|
||||||
|
{
|
||||||
|
throw Damaged();
|
||||||
|
}
|
||||||
|
|
||||||
|
lengths[first] = 1;
|
||||||
|
if (symbols == 2)
|
||||||
|
{
|
||||||
|
var second = _br.ReadBits(8);
|
||||||
|
if (second >= alphabet)
|
||||||
|
{
|
||||||
|
throw Damaged();
|
||||||
|
}
|
||||||
|
|
||||||
|
lengths[second] = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Span<byte> codeLengthLengths = stackalloc byte[19];
|
||||||
|
codeLengthLengths.Clear();
|
||||||
|
var count = 4 + _br.ReadBits(4);
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
codeLengthLengths[CodeLengthOrder[i]] = (byte)_br.ReadBits(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
var codeLengthCode = Vp8LHuffman.Build(codeLengthLengths) ?? throw Damaged();
|
||||||
|
var maxSymbol = alphabet;
|
||||||
|
if (_br.ReadBits(1) == 1)
|
||||||
|
{
|
||||||
|
var lengthBits = 2 + (2 * _br.ReadBits(3));
|
||||||
|
maxSymbol = 2 + _br.ReadBits(lengthBits);
|
||||||
|
if (maxSymbol > alphabet)
|
||||||
|
{
|
||||||
|
throw Damaged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var previous = 8;
|
||||||
|
var symbol = 0;
|
||||||
|
while (symbol < alphabet)
|
||||||
|
{
|
||||||
|
if (maxSymbol-- == 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var len = codeLengthCode.Read(_br);
|
||||||
|
if (len < 16)
|
||||||
|
{
|
||||||
|
lengths[symbol++] = (byte)len;
|
||||||
|
if (len != 0)
|
||||||
|
{
|
||||||
|
previous = len;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var repeat = len switch
|
||||||
|
{
|
||||||
|
16 => 3 + _br.ReadBits(2),
|
||||||
|
17 => 3 + _br.ReadBits(3),
|
||||||
|
_ => 11 + _br.ReadBits(7),
|
||||||
|
};
|
||||||
|
if (symbol + repeat > alphabet)
|
||||||
|
{
|
||||||
|
throw Damaged();
|
||||||
|
}
|
||||||
|
|
||||||
|
lengths.Slice(symbol, repeat).Fill(len == 16 ? (byte)previous : (byte)0);
|
||||||
|
symbol += repeat;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_br.EndOfStream)
|
||||||
|
{
|
||||||
|
throw Truncated();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!build)
|
||||||
|
{
|
||||||
|
return Vp8LHuffman.IsValid(lengths) ? null : throw Damaged();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Vp8LHuffman.Build(lengths) ?? throw Damaged();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DecodePixels(int width, int height, uint[] output, Vp8LHuffman[] groups, uint[]? meta, int metaBits, int metaWidth, int cacheBits)
|
||||||
|
{
|
||||||
|
var total = width * height;
|
||||||
|
uint[]? cache = cacheBits > 0 ? new uint[1 << cacheBits] : null;
|
||||||
|
var cacheShift = 32 - cacheBits;
|
||||||
|
var metaMask = meta is null ? -1 : (1 << metaBits) - 1;
|
||||||
|
var br = _br;
|
||||||
|
var pos = 0;
|
||||||
|
var x = 0;
|
||||||
|
var y = 0;
|
||||||
|
var g = 0;
|
||||||
|
var nextCheck = width;
|
||||||
|
while (pos < total)
|
||||||
|
{
|
||||||
|
if ((x & metaMask) == 0)
|
||||||
|
{
|
||||||
|
g = GroupAt(meta, metaBits, metaWidth, x, y) * 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
var code = groups[g].Read(br);
|
||||||
|
if (code < 256)
|
||||||
|
{
|
||||||
|
var red = groups[g + 1].Read(br);
|
||||||
|
var blue = groups[g + 2].Read(br);
|
||||||
|
var alpha = groups[g + 3].Read(br);
|
||||||
|
var pixel = ((uint)alpha << 24) | ((uint)red << 16) | ((uint)code << 8) | (uint)blue;
|
||||||
|
output[pos++] = pixel;
|
||||||
|
if (cache is not null)
|
||||||
|
{
|
||||||
|
cache[(HashMultiplier * pixel) >> cacheShift] = pixel;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (++x == width)
|
||||||
|
{
|
||||||
|
x = 0;
|
||||||
|
y++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (code < 256 + NumLengthCodes)
|
||||||
|
{
|
||||||
|
var length = PrefixValue(code - 256);
|
||||||
|
var distanceCode = PrefixValue(groups[g + 4].Read(br));
|
||||||
|
var distance = PlaneDistance(distanceCode, width);
|
||||||
|
if (distance > pos || length > total - pos)
|
||||||
|
{
|
||||||
|
throw Damaged();
|
||||||
|
}
|
||||||
|
|
||||||
|
var target = output.AsSpan(pos, length);
|
||||||
|
var from = pos - distance;
|
||||||
|
if (distance >= length)
|
||||||
|
{
|
||||||
|
output.AsSpan(from, length).CopyTo(target);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (var k = 0; k < length; k++)
|
||||||
|
{
|
||||||
|
output[pos + k] = output[from + k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cache is not null)
|
||||||
|
{
|
||||||
|
foreach (var pixel in target)
|
||||||
|
{
|
||||||
|
cache[(HashMultiplier * pixel) >> cacheShift] = pixel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += length;
|
||||||
|
x += length;
|
||||||
|
while (x >= width)
|
||||||
|
{
|
||||||
|
x -= width;
|
||||||
|
y++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (meta is not null && pos < total)
|
||||||
|
{
|
||||||
|
g = GroupAt(meta, metaBits, metaWidth, x, y) * 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var index = code - 256 - NumLengthCodes;
|
||||||
|
if (cache is null || index >= cache.Length)
|
||||||
|
{
|
||||||
|
throw Damaged();
|
||||||
|
}
|
||||||
|
|
||||||
|
var pixel = cache[index];
|
||||||
|
output[pos++] = pixel;
|
||||||
|
cache[(HashMultiplier * pixel) >> cacheShift] = pixel;
|
||||||
|
if (++x == width)
|
||||||
|
{
|
||||||
|
x = 0;
|
||||||
|
y++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pos >= nextCheck)
|
||||||
|
{
|
||||||
|
CheckStream();
|
||||||
|
nextCheck = pos + width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int GroupAt(uint[]? meta, int metaBits, int metaWidth, int x, int y) =>
|
||||||
|
meta is null ? 0 : (int)meta[((y >> metaBits) * metaWidth) + (x >> metaBits)];
|
||||||
|
|
||||||
|
// RFC 9649 §3.6: the value of an LZ77 prefix code with its extra bits.
|
||||||
|
private int PrefixValue(int code)
|
||||||
|
{
|
||||||
|
if (code < 4)
|
||||||
|
{
|
||||||
|
return code + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
var extraBits = (code - 2) >> 1;
|
||||||
|
var offset = (2 + (code & 1)) << extraBits;
|
||||||
|
return offset + _br.ReadBits(extraBits) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int PlaneDistance(int code, int width)
|
||||||
|
{
|
||||||
|
if (code > 120)
|
||||||
|
{
|
||||||
|
return code - 120;
|
||||||
|
}
|
||||||
|
|
||||||
|
var (dx, dy) = ShortDistance(code);
|
||||||
|
return Math.Max(1, dx + (dy * width));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The (dx, dy) of short distance code 1-120.</summary>
|
||||||
|
internal static (int Dx, int Dy) ShortDistance(int code) => (DistanceMap[(code - 1) * 2], DistanceMap[((code - 1) * 2) + 1]);
|
||||||
|
|
||||||
|
private static void InversePredictor(uint[] data, int width, int height, int bits, uint[] modes)
|
||||||
|
{
|
||||||
|
var blocksWide = DivRoundUp(width, bits);
|
||||||
|
data[0] = AddPixels(data[0], 0xFF000000);
|
||||||
|
for (var x = 1; x < width; x++)
|
||||||
|
{
|
||||||
|
data[x] = AddPixels(data[x], data[x - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var y = 1; y < height; y++)
|
||||||
|
{
|
||||||
|
var row = y * width;
|
||||||
|
data[row] = AddPixels(data[row], data[row - width]);
|
||||||
|
var modeRow = (y >> bits) * blocksWide;
|
||||||
|
for (var x = 1; x < width; x++)
|
||||||
|
{
|
||||||
|
var i = row + x;
|
||||||
|
var mode = (int)(modes[modeRow + (x >> bits)] >> 8) & 0xF;
|
||||||
|
data[i] = AddPixels(data[i], Predict(mode, data[i - 1], data[i - width], data[i - width + 1], data[i - width - 1]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
internal static uint Predict(int mode, uint left, uint top, uint topRight, uint topLeft) => mode switch
|
||||||
|
{
|
||||||
|
1 => left,
|
||||||
|
2 => top,
|
||||||
|
3 => topRight,
|
||||||
|
4 => topLeft,
|
||||||
|
5 => Average2(Average2(left, topRight), top),
|
||||||
|
6 => Average2(left, topLeft),
|
||||||
|
7 => Average2(left, top),
|
||||||
|
8 => Average2(topLeft, top),
|
||||||
|
9 => Average2(top, topRight),
|
||||||
|
10 => Average2(Average2(left, topLeft), Average2(top, topRight)),
|
||||||
|
11 => Select(left, top, topLeft),
|
||||||
|
12 => ClampAddSubtractFull(left, top, topLeft),
|
||||||
|
13 => ClampAddSubtractHalf(Average2(left, top), topLeft),
|
||||||
|
_ => 0xFF000000, // mode 0, and 14 and 15 which the format does not define
|
||||||
|
};
|
||||||
|
|
||||||
|
private static void InverseColor(uint[] data, int width, int height, int bits, uint[] elements)
|
||||||
|
{
|
||||||
|
var blocksWide = DivRoundUp(width, bits);
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
var row = y * width;
|
||||||
|
var elementRow = (y >> bits) * blocksWide;
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
var e = elements[elementRow + (x >> bits)];
|
||||||
|
var p = data[row + x];
|
||||||
|
var green = (sbyte)(p >> 8);
|
||||||
|
var red = (int)((p >> 16) & 0xFF) + (((sbyte)e * green) >> 5);
|
||||||
|
var blue = (int)(p & 0xFF) + (((sbyte)(e >> 8) * green) >> 5);
|
||||||
|
blue += ((sbyte)(e >> 16) * (sbyte)red) >> 5;
|
||||||
|
data[row + x] = (p & 0xFF00FF00) | ((uint)(red & 0xFF) << 16) | (uint)(blue & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AddGreen(Span<uint> data)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < data.Length; i++)
|
||||||
|
{
|
||||||
|
var p = data[i];
|
||||||
|
var green = (p >> 8) & 0xFF;
|
||||||
|
var redBlue = (p & 0x00FF00FF) + ((green << 16) | green);
|
||||||
|
data[i] = (p & 0xFF00FF00) | (redBlue & 0x00FF00FF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void InverseColorIndexing(uint[] data, int width, int packedWidth, int height, int bits, uint[] palette)
|
||||||
|
{
|
||||||
|
if (bits == 0)
|
||||||
|
{
|
||||||
|
var pixels = data.AsSpan(0, width * height);
|
||||||
|
for (var i = 0; i < pixels.Length; i++)
|
||||||
|
{
|
||||||
|
pixels[i] = palette[(pixels[i] >> 8) & 0xFF];
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var perByte = 1 << bits;
|
||||||
|
var bitsPerPixel = 8 >> bits;
|
||||||
|
var mask = (1 << bitsPerPixel) - 1;
|
||||||
|
|
||||||
|
// Backwards, so the packed row is read before the wider row overwrites it.
|
||||||
|
for (var y = height - 1; y >= 0; y--)
|
||||||
|
{
|
||||||
|
var packedRow = y * packedWidth;
|
||||||
|
var row = y * width;
|
||||||
|
for (var x = width - 1; x >= 0; x--)
|
||||||
|
{
|
||||||
|
var packed = (int)(data[packedRow + (x >> bits)] >> 8) & 0xFF;
|
||||||
|
var index = (packed >> ((x & (perByte - 1)) * bitsPerPixel)) & mask;
|
||||||
|
data[row + x] = palette[index];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
internal static uint AddPixels(uint a, uint b) =>
|
||||||
|
(((a & 0xFF00FF00) + (b & 0xFF00FF00)) & 0xFF00FF00) | (((a & 0x00FF00FF) + (b & 0x00FF00FF)) & 0x00FF00FF);
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
internal static uint SubtractPixels(uint a, uint b) =>
|
||||||
|
(((a | 0x00FF00FF) - (b & 0xFF00FF00)) & 0xFF00FF00) | (((a | 0xFF00FF00) - (b & 0x00FF00FF)) & 0x00FF00FF);
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static uint Average2(uint a, uint b) => (((a ^ b) & 0xFEFEFEFE) >> 1) + (a & b);
|
||||||
|
|
||||||
|
private static uint Select(uint left, uint top, uint topLeft)
|
||||||
|
{
|
||||||
|
// Manhattan distances of the estimate L + T − TL to L and to T.
|
||||||
|
var toLeft = Math.Abs(Channel(top, 24) - Channel(topLeft, 24)) + Math.Abs(Channel(top, 16) - Channel(topLeft, 16))
|
||||||
|
+ Math.Abs(Channel(top, 8) - Channel(topLeft, 8)) + Math.Abs(Channel(top, 0) - Channel(topLeft, 0));
|
||||||
|
var toTop = Math.Abs(Channel(left, 24) - Channel(topLeft, 24)) + Math.Abs(Channel(left, 16) - Channel(topLeft, 16))
|
||||||
|
+ Math.Abs(Channel(left, 8) - Channel(topLeft, 8)) + Math.Abs(Channel(left, 0) - Channel(topLeft, 0));
|
||||||
|
return toLeft < toTop ? left : top;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static uint ClampAddSubtractFull(uint a, uint b, uint c) =>
|
||||||
|
((uint)Clip255(Channel(a, 24) + Channel(b, 24) - Channel(c, 24)) << 24)
|
||||||
|
| ((uint)Clip255(Channel(a, 16) + Channel(b, 16) - Channel(c, 16)) << 16)
|
||||||
|
| ((uint)Clip255(Channel(a, 8) + Channel(b, 8) - Channel(c, 8)) << 8)
|
||||||
|
| (uint)Clip255(Channel(a, 0) + Channel(b, 0) - Channel(c, 0));
|
||||||
|
|
||||||
|
private static uint ClampAddSubtractHalf(uint a, uint b) =>
|
||||||
|
((uint)Half(Channel(a, 24), Channel(b, 24)) << 24)
|
||||||
|
| ((uint)Half(Channel(a, 16), Channel(b, 16)) << 16)
|
||||||
|
| ((uint)Half(Channel(a, 8), Channel(b, 8)) << 8)
|
||||||
|
| (uint)Half(Channel(a, 0), Channel(b, 0));
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int Half(int a, int b) => Clip255(a + ((a - b) / 2));
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int Channel(uint p, int shift) => (int)((p >> shift) & 0xFF);
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int Clip255(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
|
||||||
|
|
||||||
|
internal static int DivRoundUp(int value, int bits) => (value + (1 << bits) - 1) >> bits;
|
||||||
|
|
||||||
|
private void Charge(long bytes)
|
||||||
|
{
|
||||||
|
_budget += bytes;
|
||||||
|
_limits.CheckWorkingBytes(_budget);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CheckStream()
|
||||||
|
{
|
||||||
|
if (_br.EndOfStream)
|
||||||
|
{
|
||||||
|
throw Truncated();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ImageDecodeException Truncated() => new("WebP troncato: il flusso VP8L finisce prima dell'ultimo pixel.");
|
||||||
|
|
||||||
|
private static ImageDecodeException Damaged() => new("WebP danneggiato: codici del flusso VP8L non validi.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The bit reader of WebP lossless (RFC 9649 §3): bits are read from the least significant bit of each byte, and
|
||||||
|
/// past the end of the data it reads zeros and remembers it.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class Vp8LBitReader
|
||||||
|
{
|
||||||
|
private readonly byte[] _data;
|
||||||
|
private readonly int _end;
|
||||||
|
private int _pos;
|
||||||
|
private ulong _buffer;
|
||||||
|
private int _count;
|
||||||
|
|
||||||
|
public Vp8LBitReader(byte[] data, int start, int length)
|
||||||
|
{
|
||||||
|
_data = data;
|
||||||
|
_pos = start;
|
||||||
|
_end = start + length;
|
||||||
|
Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether bits past the end of the data were consumed.</summary>
|
||||||
|
public bool EndOfStream { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Reads <paramref name="n"/> bits (0-24), least significant first.</summary>
|
||||||
|
public int ReadBits(int n)
|
||||||
|
{
|
||||||
|
if (_count < n)
|
||||||
|
{
|
||||||
|
Fill();
|
||||||
|
if (_count < n)
|
||||||
|
{
|
||||||
|
EndOfStream = true;
|
||||||
|
_count = n; // the missing bits are zeros
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = (int)(_buffer & ((1UL << n) - 1));
|
||||||
|
_buffer >>= n;
|
||||||
|
_count -= n;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>At least 32 bits ready for <see cref="Peek"/> when the data has them; zeros past the end.</summary>
|
||||||
|
public ulong Peek()
|
||||||
|
{
|
||||||
|
if (_count < 32)
|
||||||
|
{
|
||||||
|
Fill();
|
||||||
|
}
|
||||||
|
|
||||||
|
return _buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Skip(int n)
|
||||||
|
{
|
||||||
|
if (_count < n)
|
||||||
|
{
|
||||||
|
EndOfStream = true;
|
||||||
|
_buffer = 0;
|
||||||
|
_count = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_buffer >>= n;
|
||||||
|
_count -= n;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Fill()
|
||||||
|
{
|
||||||
|
while (_count <= 56 && _pos < _end)
|
||||||
|
{
|
||||||
|
_buffer |= (ulong)_data[_pos++] << _count;
|
||||||
|
_count += 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A canonical prefix code of WebP lossless (the codes of DEFLATE: shorter codes first, then by symbol; read from the
|
||||||
|
/// first bit of the code), decoded with a table of 8 bits and second-level tables for longer codes.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class Vp8LHuffman
|
||||||
|
{
|
||||||
|
public const int MaxCodeLength = 15;
|
||||||
|
private const int RootBits = 8;
|
||||||
|
|
||||||
|
// Entry: symbol (or offset of the second-level table) | bits << 16 | second-level bits << 24.
|
||||||
|
private readonly uint[] _table;
|
||||||
|
|
||||||
|
private Vp8LHuffman(uint[] table, int singleSymbol)
|
||||||
|
{
|
||||||
|
_table = table;
|
||||||
|
SingleSymbol = singleSymbol;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The symbol of a code that has only one (read with zero bits), or −1.</summary>
|
||||||
|
public int SingleSymbol { get; }
|
||||||
|
|
||||||
|
/// <summary>Entries of the decoding tables, for the memory budget.</summary>
|
||||||
|
public int TableSize => _table.Length;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether <see cref="Build"/> would accept <paramref name="lengths"/>, without building any table: for the codes
|
||||||
|
/// of groups that no pixel uses.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsValid(ReadOnlySpan<byte> lengths)
|
||||||
|
{
|
||||||
|
var space = 1 << MaxCodeLength;
|
||||||
|
var used = 0;
|
||||||
|
foreach (var len in lengths)
|
||||||
|
{
|
||||||
|
if (len > MaxCodeLength)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (len > 0)
|
||||||
|
{
|
||||||
|
used++;
|
||||||
|
space -= 1 << (MaxCodeLength - len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One symbol is a code of zero bits; more must fill the code space exactly (Kraft).
|
||||||
|
return used == 1 || (used > 1 && space == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The code given by the code lengths of each symbol (0 = not used), or null when the lengths are not a complete
|
||||||
|
/// prefix code (or use no symbol at all). A single used symbol is a code of zero bits.
|
||||||
|
/// </summary>
|
||||||
|
public static Vp8LHuffman? Build(ReadOnlySpan<byte> lengths)
|
||||||
|
{
|
||||||
|
Span<int> counts = stackalloc int[MaxCodeLength + 1];
|
||||||
|
var used = 0;
|
||||||
|
var last = -1;
|
||||||
|
for (var s = 0; s < lengths.Length; s++)
|
||||||
|
{
|
||||||
|
var len = lengths[s];
|
||||||
|
if (len > MaxCodeLength)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (len > 0)
|
||||||
|
{
|
||||||
|
counts[len]++;
|
||||||
|
used++;
|
||||||
|
last = s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (used == 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (used == 1)
|
||||||
|
{
|
||||||
|
var single = new uint[1 << RootBits];
|
||||||
|
single.AsSpan().Fill((uint)last);
|
||||||
|
return new Vp8LHuffman(single, last);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kraft: the code must be complete, neither over- nor under-subscribed.
|
||||||
|
var space = 1 << MaxCodeLength;
|
||||||
|
for (var len = 1; len <= MaxCodeLength; len++)
|
||||||
|
{
|
||||||
|
space -= counts[len] << (MaxCodeLength - len);
|
||||||
|
if (space < 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (space != 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Span<int> next = stackalloc int[MaxCodeLength + 2];
|
||||||
|
var code = 0;
|
||||||
|
for (var len = 1; len <= MaxCodeLength; len++)
|
||||||
|
{
|
||||||
|
code = (code + counts[len - 1]) << 1;
|
||||||
|
next[len] = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Longest code under each root prefix, to size the second-level tables.
|
||||||
|
Span<byte> longest = stackalloc byte[1 << RootBits];
|
||||||
|
longest.Clear();
|
||||||
|
var codes = new int[lengths.Length];
|
||||||
|
{
|
||||||
|
Span<int> assign = stackalloc int[MaxCodeLength + 2];
|
||||||
|
next.CopyTo(assign);
|
||||||
|
for (var s = 0; s < lengths.Length; s++)
|
||||||
|
{
|
||||||
|
var len = lengths[s];
|
||||||
|
if (len == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var reversed = Reverse(assign[len]++, len);
|
||||||
|
codes[s] = reversed;
|
||||||
|
if (len > RootBits)
|
||||||
|
{
|
||||||
|
var prefix = reversed & ((1 << RootBits) - 1);
|
||||||
|
longest[prefix] = Math.Max(longest[prefix], len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Span<int> offsets = stackalloc int[1 << RootBits];
|
||||||
|
var size = 1 << RootBits;
|
||||||
|
for (var prefix = 0; prefix < longest.Length; prefix++)
|
||||||
|
{
|
||||||
|
if (longest[prefix] > 0)
|
||||||
|
{
|
||||||
|
offsets[prefix] = size;
|
||||||
|
size += 1 << (longest[prefix] - RootBits);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var table = new uint[size];
|
||||||
|
for (var prefix = 0; prefix < longest.Length; prefix++)
|
||||||
|
{
|
||||||
|
if (longest[prefix] > 0)
|
||||||
|
{
|
||||||
|
table[prefix] = (uint)offsets[prefix] | (uint)(longest[prefix] - RootBits) << 24;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var s = 0; s < lengths.Length; s++)
|
||||||
|
{
|
||||||
|
var len = lengths[s];
|
||||||
|
if (len == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var reversed = codes[s];
|
||||||
|
if (len <= RootBits)
|
||||||
|
{
|
||||||
|
var entry = (uint)s | (uint)len << 16;
|
||||||
|
for (var i = reversed; i < (1 << RootBits); i += 1 << len)
|
||||||
|
{
|
||||||
|
table[i] = entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var prefix = reversed & ((1 << RootBits) - 1);
|
||||||
|
var subBits = longest[prefix] - RootBits;
|
||||||
|
var entry = (uint)s | (uint)(len - RootBits) << 16;
|
||||||
|
for (var i = reversed >> RootBits; i < (1 << subBits); i += 1 << (len - RootBits))
|
||||||
|
{
|
||||||
|
table[offsets[prefix] + i] = entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Vp8LHuffman(table, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads one symbol.</summary>
|
||||||
|
public int Read(Vp8LBitReader reader)
|
||||||
|
{
|
||||||
|
if (SingleSymbol >= 0)
|
||||||
|
{
|
||||||
|
return SingleSymbol;
|
||||||
|
}
|
||||||
|
|
||||||
|
var bits = reader.Peek();
|
||||||
|
var entry = _table[(int)(bits & ((1 << RootBits) - 1))];
|
||||||
|
var sub = (int)(entry >> 24);
|
||||||
|
if (sub == 0)
|
||||||
|
{
|
||||||
|
reader.Skip((int)(entry >> 16) & 0xFF);
|
||||||
|
return (int)(entry & 0xFFFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
var second = _table[(int)(entry & 0xFFFF) + (int)((bits >> RootBits) & ((1UL << sub) - 1))];
|
||||||
|
reader.Skip(RootBits + ((int)(second >> 16) & 0xFF));
|
||||||
|
return (int)(second & 0xFFFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static int Reverse(int code, int length)
|
||||||
|
{
|
||||||
|
var r = 0;
|
||||||
|
for (var i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
r = (r << 1) | (code & 1);
|
||||||
|
code >>= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,565 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Intra prediction of VP8 (RFC 6386 §12). The buffers hold the block with its row above (from one pixel to the
|
||||||
|
/// left; for subblocks eight pixels wide) and its column to the left at the usual offsets of <c>at</c>.
|
||||||
|
/// </summary>
|
||||||
|
internal static class Vp8Predict
|
||||||
|
{
|
||||||
|
/// <summary>A 16×16 luma or 8×8 chroma prediction (DC_PRED, V_PRED, H_PRED, TM_PRED).</summary>
|
||||||
|
public static void Block(Span<byte> buf, int at, int stride, int size, int mode, bool hasLeft, bool hasTop)
|
||||||
|
{
|
||||||
|
switch (mode)
|
||||||
|
{
|
||||||
|
case Vp8Tables.VPred:
|
||||||
|
{
|
||||||
|
var above = buf.Slice(at - stride, size);
|
||||||
|
for (var r = 0; r < size; r++)
|
||||||
|
{
|
||||||
|
above.CopyTo(buf.Slice(at + (r * stride), size));
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Vp8Tables.HPred:
|
||||||
|
for (var r = 0; r < size; r++)
|
||||||
|
{
|
||||||
|
var row = at + (r * stride);
|
||||||
|
buf.Slice(row, size).Fill(buf[row - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Vp8Tables.TmPred:
|
||||||
|
{
|
||||||
|
var corner = buf[at - stride - 1];
|
||||||
|
for (var r = 0; r < size; r++)
|
||||||
|
{
|
||||||
|
var row = at + (r * stride);
|
||||||
|
var delta = buf[row - 1] - corner;
|
||||||
|
for (var c = 0; c < size; c++)
|
||||||
|
{
|
||||||
|
buf[row + c] = Clip(buf[at - stride + c] + delta);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
var shift = size == 16 ? 4 : 3;
|
||||||
|
int value;
|
||||||
|
if (hasTop && hasLeft)
|
||||||
|
{
|
||||||
|
value = (SumAbove(buf, at, stride, size) + SumLeft(buf, at, stride, size) + size) >> (shift + 1);
|
||||||
|
}
|
||||||
|
else if (hasTop)
|
||||||
|
{
|
||||||
|
value = (SumAbove(buf, at, stride, size) + (size >> 1)) >> shift;
|
||||||
|
}
|
||||||
|
else if (hasLeft)
|
||||||
|
{
|
||||||
|
value = (SumLeft(buf, at, stride, size) + (size >> 1)) >> shift;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
value = 128;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var r = 0; r < size; r++)
|
||||||
|
{
|
||||||
|
buf.Slice(at + (r * stride), size).Fill((byte)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A 4×4 luma subblock prediction (the ten intra_bmode of RFC 6386 §12.3).</summary>
|
||||||
|
public static void Sub4x4(Span<byte> buf, int at, int stride, int mode)
|
||||||
|
{
|
||||||
|
var up = at - stride;
|
||||||
|
int a0 = buf[up], a1 = buf[up + 1], a2 = buf[up + 2], a3 = buf[up + 3];
|
||||||
|
int a4 = buf[up + 4], a5 = buf[up + 5], a6 = buf[up + 6], a7 = buf[up + 7];
|
||||||
|
int p = buf[up - 1];
|
||||||
|
int l0 = buf[at - 1], l1 = buf[at + stride - 1], l2 = buf[at + (2 * stride) - 1], l3 = buf[at + (3 * stride) - 1];
|
||||||
|
var r0 = at;
|
||||||
|
var r1 = at + stride;
|
||||||
|
var r2 = at + (2 * stride);
|
||||||
|
var r3 = at + (3 * stride);
|
||||||
|
switch (mode)
|
||||||
|
{
|
||||||
|
case Vp8Tables.BDc:
|
||||||
|
{
|
||||||
|
var v = (byte)((a0 + a1 + a2 + a3 + l0 + l1 + l2 + l3 + 4) >> 3);
|
||||||
|
buf.Slice(r0, 4).Fill(v);
|
||||||
|
buf.Slice(r1, 4).Fill(v);
|
||||||
|
buf.Slice(r2, 4).Fill(v);
|
||||||
|
buf.Slice(r3, 4).Fill(v);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Vp8Tables.BTm:
|
||||||
|
{
|
||||||
|
Span<int> left = [l0, l1, l2, l3];
|
||||||
|
for (var r = 0; r < 4; r++)
|
||||||
|
{
|
||||||
|
var row = at + (r * stride);
|
||||||
|
var delta = left[r] - p;
|
||||||
|
buf[row] = Clip(a0 + delta);
|
||||||
|
buf[row + 1] = Clip(a1 + delta);
|
||||||
|
buf[row + 2] = Clip(a2 + delta);
|
||||||
|
buf[row + 3] = Clip(a3 + delta);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Vp8Tables.BVe:
|
||||||
|
{
|
||||||
|
var c0 = Avg3(p, a0, a1);
|
||||||
|
var c1 = Avg3(a0, a1, a2);
|
||||||
|
var c2 = Avg3(a1, a2, a3);
|
||||||
|
var c3 = Avg3(a2, a3, a4);
|
||||||
|
foreach (var row in (ReadOnlySpan<int>)[r0, r1, r2, r3])
|
||||||
|
{
|
||||||
|
buf[row] = c0;
|
||||||
|
buf[row + 1] = c1;
|
||||||
|
buf[row + 2] = c2;
|
||||||
|
buf[row + 3] = c3;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Vp8Tables.BHe:
|
||||||
|
buf.Slice(r0, 4).Fill(Avg3(p, l0, l1));
|
||||||
|
buf.Slice(r1, 4).Fill(Avg3(l0, l1, l2));
|
||||||
|
buf.Slice(r2, 4).Fill(Avg3(l1, l2, l3));
|
||||||
|
buf.Slice(r3, 4).Fill(Avg3(l2, l3, l3));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Vp8Tables.BLd:
|
||||||
|
buf[r0] = Avg3(a0, a1, a2);
|
||||||
|
buf[r0 + 1] = buf[r1] = Avg3(a1, a2, a3);
|
||||||
|
buf[r0 + 2] = buf[r1 + 1] = buf[r2] = Avg3(a2, a3, a4);
|
||||||
|
buf[r0 + 3] = buf[r1 + 2] = buf[r2 + 1] = buf[r3] = Avg3(a3, a4, a5);
|
||||||
|
buf[r1 + 3] = buf[r2 + 2] = buf[r3 + 1] = Avg3(a4, a5, a6);
|
||||||
|
buf[r2 + 3] = buf[r3 + 2] = Avg3(a5, a6, a7);
|
||||||
|
buf[r3 + 3] = Avg3(a6, a7, a7);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Vp8Tables.BRd:
|
||||||
|
{
|
||||||
|
// Edge from bottom-left to top-right: L3, L2, L1, L0, P, A0, A1, A2, A3.
|
||||||
|
buf[r3] = Avg3(l3, l2, l1);
|
||||||
|
buf[r3 + 1] = buf[r2] = Avg3(l2, l1, l0);
|
||||||
|
buf[r3 + 2] = buf[r2 + 1] = buf[r1] = Avg3(l1, l0, p);
|
||||||
|
buf[r3 + 3] = buf[r2 + 2] = buf[r1 + 1] = buf[r0] = Avg3(l0, p, a0);
|
||||||
|
buf[r2 + 3] = buf[r1 + 2] = buf[r0 + 1] = Avg3(p, a0, a1);
|
||||||
|
buf[r1 + 3] = buf[r0 + 2] = Avg3(a0, a1, a2);
|
||||||
|
buf[r0 + 3] = Avg3(a1, a2, a3);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Vp8Tables.BVr:
|
||||||
|
buf[r3] = Avg3(l2, l1, l0);
|
||||||
|
buf[r2] = Avg3(l1, l0, p);
|
||||||
|
buf[r3 + 1] = buf[r1] = Avg3(l0, p, a0);
|
||||||
|
buf[r2 + 1] = buf[r0] = Avg2(p, a0);
|
||||||
|
buf[r3 + 2] = buf[r1 + 1] = Avg3(p, a0, a1);
|
||||||
|
buf[r2 + 2] = buf[r0 + 1] = Avg2(a0, a1);
|
||||||
|
buf[r3 + 3] = buf[r1 + 2] = Avg3(a0, a1, a2);
|
||||||
|
buf[r2 + 3] = buf[r0 + 2] = Avg2(a1, a2);
|
||||||
|
buf[r1 + 3] = Avg3(a1, a2, a3);
|
||||||
|
buf[r0 + 3] = Avg2(a2, a3);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Vp8Tables.BVl:
|
||||||
|
buf[r0] = Avg2(a0, a1);
|
||||||
|
buf[r1] = Avg3(a0, a1, a2);
|
||||||
|
buf[r2] = buf[r0 + 1] = Avg2(a1, a2);
|
||||||
|
buf[r1 + 1] = buf[r3] = Avg3(a1, a2, a3);
|
||||||
|
buf[r2 + 1] = buf[r0 + 2] = Avg2(a2, a3);
|
||||||
|
buf[r3 + 1] = buf[r1 + 2] = Avg3(a2, a3, a4);
|
||||||
|
buf[r2 + 2] = buf[r0 + 3] = Avg2(a3, a4);
|
||||||
|
buf[r3 + 2] = buf[r1 + 3] = Avg3(a3, a4, a5);
|
||||||
|
buf[r2 + 3] = Avg3(a4, a5, a6);
|
||||||
|
buf[r3 + 3] = Avg3(a5, a6, a7);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Vp8Tables.BHd:
|
||||||
|
buf[r3] = Avg2(l3, l2);
|
||||||
|
buf[r3 + 1] = Avg3(l3, l2, l1);
|
||||||
|
buf[r2] = buf[r3 + 2] = Avg2(l2, l1);
|
||||||
|
buf[r2 + 1] = buf[r3 + 3] = Avg3(l2, l1, l0);
|
||||||
|
buf[r2 + 2] = buf[r1] = Avg2(l1, l0);
|
||||||
|
buf[r2 + 3] = buf[r1 + 1] = Avg3(l1, l0, p);
|
||||||
|
buf[r1 + 2] = buf[r0] = Avg2(l0, p);
|
||||||
|
buf[r1 + 3] = buf[r0 + 1] = Avg3(l0, p, a0);
|
||||||
|
buf[r0 + 2] = Avg3(p, a0, a1);
|
||||||
|
buf[r0 + 3] = Avg3(a0, a1, a2);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default: // B_HU_PRED
|
||||||
|
buf[r0] = Avg2(l0, l1);
|
||||||
|
buf[r0 + 1] = Avg3(l0, l1, l2);
|
||||||
|
buf[r0 + 2] = buf[r1] = Avg2(l1, l2);
|
||||||
|
buf[r0 + 3] = buf[r1 + 1] = Avg3(l1, l2, l3);
|
||||||
|
buf[r1 + 2] = buf[r2] = Avg2(l2, l3);
|
||||||
|
buf[r1 + 3] = buf[r2 + 1] = Avg3(l2, l3, l3);
|
||||||
|
buf[r2 + 2] = buf[r2 + 3] = (byte)l3;
|
||||||
|
buf.Slice(r3, 4).Fill((byte)l3);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static byte Avg2(int a, int b) => (byte)((a + b + 1) >> 1);
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static byte Avg3(int a, int b, int c) => (byte)((a + (2 * b) + c + 2) >> 2);
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
internal static byte Clip(int v) => (uint)v <= 255 ? (byte)v : v < 0 ? (byte)0 : (byte)255;
|
||||||
|
|
||||||
|
private static int SumAbove(Span<byte> buf, int at, int stride, int size)
|
||||||
|
{
|
||||||
|
var sum = 0;
|
||||||
|
foreach (var b in buf.Slice(at - stride, size))
|
||||||
|
{
|
||||||
|
sum += b;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int SumLeft(Span<byte> buf, int at, int stride, int size)
|
||||||
|
{
|
||||||
|
var sum = 0;
|
||||||
|
for (var r = 0; r < size; r++)
|
||||||
|
{
|
||||||
|
sum += buf[at + (r * stride) - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The inverse transforms of VP8 (RFC 6386 §14.3 and §14.4), exact integer arithmetic.</summary>
|
||||||
|
internal static class Vp8Transforms
|
||||||
|
{
|
||||||
|
private const int C1 = 20091; // cos(π/8)·√2 − 1, ×65536
|
||||||
|
private const int S1 = 35468; // sin(π/8)·√2, ×65536
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The inverse Walsh-Hadamard transform of the Y2 block: its outputs are the DC coefficients of the sixteen luma
|
||||||
|
/// blocks (coefficient 0 of each block of 16 in <paramref name="blocks"/>).
|
||||||
|
/// </summary>
|
||||||
|
public static void InverseWht(ReadOnlySpan<short> input, Span<short> blocks)
|
||||||
|
{
|
||||||
|
Span<int> tmp = stackalloc int[16];
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
var a1 = input[i] + input[12 + i];
|
||||||
|
var b1 = input[4 + i] + input[8 + i];
|
||||||
|
var c1 = input[4 + i] - input[8 + i];
|
||||||
|
var d1 = input[i] - input[12 + i];
|
||||||
|
tmp[i] = a1 + b1;
|
||||||
|
tmp[4 + i] = c1 + d1;
|
||||||
|
tmp[8 + i] = a1 - b1;
|
||||||
|
tmp[12 + i] = d1 - c1;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
var row = tmp.Slice(i * 4, 4);
|
||||||
|
var a1 = row[0] + row[3];
|
||||||
|
var b1 = row[1] + row[2];
|
||||||
|
var c1 = row[1] - row[2];
|
||||||
|
var d1 = row[0] - row[3];
|
||||||
|
blocks[((i * 4) + 0) * 16] = Short((a1 + b1 + 3) >> 3);
|
||||||
|
blocks[((i * 4) + 1) * 16] = Short((c1 + d1 + 3) >> 3);
|
||||||
|
blocks[((i * 4) + 2) * 16] = Short((a1 - b1 + 3) >> 3);
|
||||||
|
blocks[((i * 4) + 3) * 16] = Short((d1 - c1 + 3) >> 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds the inverse DCT of <paramref name="coeffs"/> (raster order) to the 4×4 pixels at <paramref name="at"/>:
|
||||||
|
/// <paramref name="kind"/> 0 means an empty block, 1 only a DC coefficient, 2 any coefficients.
|
||||||
|
/// </summary>
|
||||||
|
public static void AddBlock(ReadOnlySpan<short> coeffs, int kind, Span<byte> buf, int at, int stride)
|
||||||
|
{
|
||||||
|
if (kind == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind == 1)
|
||||||
|
{
|
||||||
|
var dc = (coeffs[0] + 4) >> 3;
|
||||||
|
for (var r = 0; r < 4; r++)
|
||||||
|
{
|
||||||
|
var row = buf.Slice(at + (r * stride), 4);
|
||||||
|
row[0] = Vp8Predict.Clip(row[0] + dc);
|
||||||
|
row[1] = Vp8Predict.Clip(row[1] + dc);
|
||||||
|
row[2] = Vp8Predict.Clip(row[2] + dc);
|
||||||
|
row[3] = Vp8Predict.Clip(row[3] + dc);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Span<int> tmp = stackalloc int[16];
|
||||||
|
for (var i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
// Vertical pass over column i.
|
||||||
|
int i0 = coeffs[i], i4 = coeffs[4 + i], i8 = coeffs[8 + i], i12 = coeffs[12 + i];
|
||||||
|
var a = i0 + i8;
|
||||||
|
var b = i0 - i8;
|
||||||
|
var c = Mul2(i4) - Mul1(i12);
|
||||||
|
var d = Mul1(i4) + Mul2(i12);
|
||||||
|
tmp[i] = a + d;
|
||||||
|
tmp[4 + i] = b + c;
|
||||||
|
tmp[8 + i] = b - c;
|
||||||
|
tmp[12 + i] = a - d;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var r = 0; r < 4; r++)
|
||||||
|
{
|
||||||
|
// Horizontal pass over row r.
|
||||||
|
var t = tmp.Slice(r * 4, 4);
|
||||||
|
var a = t[0] + t[2];
|
||||||
|
var b = t[0] - t[2];
|
||||||
|
var c = Mul2(t[1]) - Mul1(t[3]);
|
||||||
|
var d = Mul1(t[1]) + Mul2(t[3]);
|
||||||
|
var row = buf.Slice(at + (r * stride), 4);
|
||||||
|
row[0] = Vp8Predict.Clip(row[0] + ((a + d + 4) >> 3));
|
||||||
|
row[1] = Vp8Predict.Clip(row[1] + ((b + c + 4) >> 3));
|
||||||
|
row[2] = Vp8Predict.Clip(row[2] + ((b - c + 4) >> 3));
|
||||||
|
row[3] = Vp8Predict.Clip(row[3] + ((a - d + 4) >> 3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int Mul1(int a) => ((a * C1) >> 16) + a;
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int Mul2(int a) => (a * S1) >> 16;
|
||||||
|
|
||||||
|
private static short Short(int v) => (short)Math.Clamp(v, short.MinValue, short.MaxValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The loop filters of VP8 (RFC 6386 §15), applied to the whole reconstructed frame in raster order.</summary>
|
||||||
|
internal static class Vp8LoopFilter
|
||||||
|
{
|
||||||
|
public static void Apply(Vp8Decoder frame)
|
||||||
|
{
|
||||||
|
var y = frame.YPlane;
|
||||||
|
var u = frame.UPlane;
|
||||||
|
var v = frame.VPlane;
|
||||||
|
var ys = frame.YStride;
|
||||||
|
var uvs = frame.UvStride;
|
||||||
|
var simple = frame.SimpleFilter;
|
||||||
|
for (var mbY = 0; mbY < frame.MbHeight; mbY++)
|
||||||
|
{
|
||||||
|
for (var mbX = 0; mbX < frame.MbWidth; mbX++)
|
||||||
|
{
|
||||||
|
var (limit, interior, hev, inner) = frame.FilterOf((mbY * frame.MbWidth) + mbX);
|
||||||
|
if (limit == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var yAt = (mbY * 16 * ys) + (mbX * 16);
|
||||||
|
var uvAt = (mbY * 8 * uvs) + (mbX * 8);
|
||||||
|
if (simple)
|
||||||
|
{
|
||||||
|
// Edge strength 2·limit + 1 compares with 4·|p0 − q0| + |p1 − q1| (RFC 6386 §15.2).
|
||||||
|
if (mbX > 0)
|
||||||
|
{
|
||||||
|
SimpleEdge(y, yAt, 1, ys, (2 * (limit + 4)) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inner)
|
||||||
|
{
|
||||||
|
for (var k = 4; k < 16; k += 4)
|
||||||
|
{
|
||||||
|
SimpleEdge(y, yAt + k, 1, ys, (2 * limit) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mbY > 0)
|
||||||
|
{
|
||||||
|
SimpleEdge(y, yAt, ys, 1, (2 * (limit + 4)) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inner)
|
||||||
|
{
|
||||||
|
for (var k = 4; k < 16; k += 4)
|
||||||
|
{
|
||||||
|
SimpleEdge(y, yAt + (k * ys), ys, 1, (2 * limit) + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var mbEdge = (2 * (limit + 4)) + 1;
|
||||||
|
var subEdge = (2 * limit) + 1;
|
||||||
|
if (mbX > 0)
|
||||||
|
{
|
||||||
|
MacroblockEdge(y, yAt, 1, ys, 16, mbEdge, interior, hev);
|
||||||
|
MacroblockEdge(u, uvAt, 1, uvs, 8, mbEdge, interior, hev);
|
||||||
|
MacroblockEdge(v, uvAt, 1, uvs, 8, mbEdge, interior, hev);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inner)
|
||||||
|
{
|
||||||
|
for (var k = 4; k < 16; k += 4)
|
||||||
|
{
|
||||||
|
SubblockEdge(y, yAt + k, 1, ys, 16, subEdge, interior, hev);
|
||||||
|
}
|
||||||
|
|
||||||
|
SubblockEdge(u, uvAt + 4, 1, uvs, 8, subEdge, interior, hev);
|
||||||
|
SubblockEdge(v, uvAt + 4, 1, uvs, 8, subEdge, interior, hev);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mbY > 0)
|
||||||
|
{
|
||||||
|
MacroblockEdge(y, yAt, ys, 1, 16, mbEdge, interior, hev);
|
||||||
|
MacroblockEdge(u, uvAt, uvs, 1, 8, mbEdge, interior, hev);
|
||||||
|
MacroblockEdge(v, uvAt, uvs, 1, 8, mbEdge, interior, hev);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inner)
|
||||||
|
{
|
||||||
|
for (var k = 4; k < 16; k += 4)
|
||||||
|
{
|
||||||
|
SubblockEdge(y, yAt + (k * ys), ys, 1, 16, subEdge, interior, hev);
|
||||||
|
}
|
||||||
|
|
||||||
|
SubblockEdge(u, uvAt + (4 * uvs), uvs, 1, 8, subEdge, interior, hev);
|
||||||
|
SubblockEdge(v, uvAt + (4 * uvs), uvs, 1, 8, subEdge, interior, hev);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The simple filter over 16 pixels of an edge: <paramref name="step"/> crosses the edge (1 for a vertical edge),
|
||||||
|
/// <paramref name="along"/> moves along it; <paramref name="edge2"/> is twice the edge limit plus one.
|
||||||
|
/// </summary>
|
||||||
|
internal static void SimpleEdge(byte[] buf, int at, int step, int along, int edge2)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 16; i++)
|
||||||
|
{
|
||||||
|
var q = at + (i * along);
|
||||||
|
int p1 = buf[q - (2 * step)], p0 = buf[q - step], q0 = buf[q], q1 = buf[q + step];
|
||||||
|
if ((4 * Math.Abs(p0 - q0)) + Math.Abs(p1 - q1) <= edge2)
|
||||||
|
{
|
||||||
|
CommonAdjust(buf, q, step, useOuterTaps: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void SubblockEdge(byte[] buf, int at, int step, int along, int count, int edge2, int interior, int hevThreshold)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var q = at + (i * along);
|
||||||
|
if (!NeedsFilter(buf, q, step, edge2, interior))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var hev = HighEdgeVariance(buf, q, step, hevThreshold);
|
||||||
|
var a = (CommonAdjust(buf, q, step, hev) + 1) >> 1;
|
||||||
|
if (!hev)
|
||||||
|
{
|
||||||
|
buf[q + step] = S2U(U2S(buf[q + step]) - a);
|
||||||
|
buf[q - (2 * step)] = S2U(U2S(buf[q - (2 * step)]) + a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void MacroblockEdge(byte[] buf, int at, int step, int along, int count, int edge2, int interior, int hevThreshold)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var q = at + (i * along);
|
||||||
|
if (!NeedsFilter(buf, q, step, edge2, interior))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (HighEdgeVariance(buf, q, step, hevThreshold))
|
||||||
|
{
|
||||||
|
CommonAdjust(buf, q, step, useOuterTaps: true);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var p2 = U2S(buf[q - (3 * step)]);
|
||||||
|
var p1 = U2S(buf[q - (2 * step)]);
|
||||||
|
var p0 = U2S(buf[q - step]);
|
||||||
|
var q0 = U2S(buf[q]);
|
||||||
|
var q1 = U2S(buf[q + step]);
|
||||||
|
var q2 = U2S(buf[q + (2 * step)]);
|
||||||
|
var w = C(C(p1 - q1) + (3 * (q0 - p0)));
|
||||||
|
var a = C(((27 * w) + 63) >> 7);
|
||||||
|
buf[q] = S2U(q0 - a);
|
||||||
|
buf[q - step] = S2U(p0 + a);
|
||||||
|
a = C(((18 * w) + 63) >> 7);
|
||||||
|
buf[q + step] = S2U(q1 - a);
|
||||||
|
buf[q - (2 * step)] = S2U(p1 + a);
|
||||||
|
a = C(((9 * w) + 63) >> 7);
|
||||||
|
buf[q + (2 * step)] = S2U(q2 - a);
|
||||||
|
buf[q - (3 * step)] = S2U(p2 + a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static bool NeedsFilter(byte[] buf, int q, int step, int edge2, int interior)
|
||||||
|
{
|
||||||
|
int p3 = buf[q - (4 * step)], p2 = buf[q - (3 * step)], p1 = buf[q - (2 * step)], p0 = buf[q - step];
|
||||||
|
int q0 = buf[q], q1 = buf[q + step], q2 = buf[q + (2 * step)], q3 = buf[q + (3 * step)];
|
||||||
|
return (4 * Math.Abs(p0 - q0)) + Math.Abs(p1 - q1) <= edge2
|
||||||
|
&& Math.Abs(p3 - p2) <= interior && Math.Abs(p2 - p1) <= interior && Math.Abs(p1 - p0) <= interior
|
||||||
|
&& Math.Abs(q3 - q2) <= interior && Math.Abs(q2 - q1) <= interior && Math.Abs(q1 - q0) <= interior;
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static bool HighEdgeVariance(byte[] buf, int q, int step, int threshold) =>
|
||||||
|
Math.Abs(buf[q - (2 * step)] - buf[q - step]) > threshold || Math.Abs(buf[q + step] - buf[q]) > threshold;
|
||||||
|
|
||||||
|
// RFC 6386 §15.2, common_adjust: moves p0 and q0 towards each other; returns the adjustment of q0.
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int CommonAdjust(byte[] buf, int q, int step, bool useOuterTaps)
|
||||||
|
{
|
||||||
|
var p1 = U2S(buf[q - (2 * step)]);
|
||||||
|
var p0 = U2S(buf[q - step]);
|
||||||
|
var q0 = U2S(buf[q]);
|
||||||
|
var q1 = U2S(buf[q + step]);
|
||||||
|
var a = C((useOuterTaps ? C(p1 - q1) : 0) + (3 * (q0 - p0)));
|
||||||
|
var b = C(a + 3) >> 3;
|
||||||
|
a = C(a + 4) >> 3;
|
||||||
|
buf[q] = S2U(q0 - a);
|
||||||
|
buf[q - step] = S2U(p0 + b);
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int U2S(byte v) => v - 128;
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static byte S2U(int v) => (byte)(C(v) + 128);
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int C(int v) => Math.Clamp(v, -128, 127);
|
||||||
|
}
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The constant tables of the VP8 key frame format (RFC 6386): quantizer steps (§14.1), the probabilities of the intra
|
||||||
|
/// modes (§11) and of the DCT tokens (§13), the trees they are read with, the scan order and the coefficient bands.
|
||||||
|
/// </summary>
|
||||||
|
internal static class Vp8Tables
|
||||||
|
{
|
||||||
|
/// <summary>Intra modes of a 16×16 luma block or an 8×8 chroma block (RFC 6386 §8.1).</summary>
|
||||||
|
public const int DcPred = 0, VPred = 1, HPred = 2, TmPred = 3, BPred = 4;
|
||||||
|
|
||||||
|
/// <summary>Modes of a 4×4 luma subblock, in the order of RFC 6386 §8.1 (intra_bmode).</summary>
|
||||||
|
public const int BDc = 0, BTm = 1, BVe = 2, BHe = 3, BLd = 4, BRd = 5, BVr = 6, BVl = 7, BHd = 8, BHu = 9;
|
||||||
|
|
||||||
|
public const int NumBModes = 10;
|
||||||
|
|
||||||
|
/// <summary>§11.2: kf_ymode_prob.</summary>
|
||||||
|
public static ReadOnlySpan<byte> KeyFrameYModeProbs => [145, 156, 163, 128];
|
||||||
|
|
||||||
|
/// <summary>§11.2: kf_uv_mode_prob.</summary>
|
||||||
|
public static ReadOnlySpan<byte> KeyFrameUvModeProbs => [142, 114, 183];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// §11.2: bmode_tree, as pairs of children; a child ≤ 0 is the leaf −mode, a positive child the index of the next
|
||||||
|
/// pair.
|
||||||
|
/// </summary>
|
||||||
|
public static ReadOnlySpan<sbyte> BModeTree =>
|
||||||
|
[
|
||||||
|
-BDc, 2,
|
||||||
|
-BTm, 4,
|
||||||
|
-BVe, 6,
|
||||||
|
8, 12,
|
||||||
|
-BHe, 10,
|
||||||
|
-BRd, -BVr,
|
||||||
|
-BLd, 14,
|
||||||
|
-BVl, 16,
|
||||||
|
-BHd, -BHu,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// §11.5: kf_bmode_probs[above][left][9], flattened: the probabilities of the tree of a subblock mode given the
|
||||||
|
/// modes of the subblocks above and to the left.
|
||||||
|
/// </summary>
|
||||||
|
public static ReadOnlySpan<byte> KeyFrameBModeProbs =>
|
||||||
|
[
|
||||||
|
231, 120, 48, 89, 115, 113, 120, 152, 112,
|
||||||
|
152, 179, 64, 126, 170, 118, 46, 70, 95,
|
||||||
|
175, 69, 143, 80, 85, 82, 72, 155, 103,
|
||||||
|
56, 58, 10, 171, 218, 189, 17, 13, 152,
|
||||||
|
144, 71, 10, 38, 171, 213, 144, 34, 26,
|
||||||
|
114, 26, 17, 163, 44, 195, 21, 10, 173,
|
||||||
|
121, 24, 80, 195, 26, 62, 44, 64, 85,
|
||||||
|
170, 46, 55, 19, 136, 160, 33, 206, 71,
|
||||||
|
63, 20, 8, 114, 114, 208, 12, 9, 226,
|
||||||
|
81, 40, 11, 96, 182, 84, 29, 16, 36,
|
||||||
|
|
||||||
|
134, 183, 89, 137, 98, 101, 106, 165, 148,
|
||||||
|
72, 187, 100, 130, 157, 111, 32, 75, 80,
|
||||||
|
66, 102, 167, 99, 74, 62, 40, 234, 128,
|
||||||
|
41, 53, 9, 178, 241, 141, 26, 8, 107,
|
||||||
|
104, 79, 12, 27, 217, 255, 87, 17, 7,
|
||||||
|
74, 43, 26, 146, 73, 166, 49, 23, 157,
|
||||||
|
65, 38, 105, 160, 51, 52, 31, 115, 128,
|
||||||
|
87, 68, 71, 44, 114, 51, 15, 186, 23,
|
||||||
|
47, 41, 14, 110, 182, 183, 21, 17, 194,
|
||||||
|
66, 45, 25, 102, 197, 189, 23, 18, 22,
|
||||||
|
|
||||||
|
88, 88, 147, 150, 42, 46, 45, 196, 205,
|
||||||
|
43, 97, 183, 117, 85, 38, 35, 179, 61,
|
||||||
|
39, 53, 200, 87, 26, 21, 43, 232, 171,
|
||||||
|
56, 34, 51, 104, 114, 102, 29, 93, 77,
|
||||||
|
107, 54, 32, 26, 51, 1, 81, 43, 31,
|
||||||
|
39, 28, 85, 171, 58, 165, 90, 98, 64,
|
||||||
|
34, 22, 116, 206, 23, 34, 43, 166, 73,
|
||||||
|
68, 25, 106, 22, 64, 171, 36, 225, 114,
|
||||||
|
34, 19, 21, 102, 132, 188, 16, 76, 124,
|
||||||
|
62, 18, 78, 95, 85, 57, 50, 48, 51,
|
||||||
|
|
||||||
|
193, 101, 35, 159, 215, 111, 89, 46, 111,
|
||||||
|
60, 148, 31, 172, 219, 228, 21, 18, 111,
|
||||||
|
112, 113, 77, 85, 179, 255, 38, 120, 114,
|
||||||
|
40, 42, 1, 196, 245, 209, 10, 25, 109,
|
||||||
|
100, 80, 8, 43, 154, 1, 51, 26, 71,
|
||||||
|
88, 43, 29, 140, 166, 213, 37, 43, 154,
|
||||||
|
61, 63, 30, 155, 67, 45, 68, 1, 209,
|
||||||
|
142, 78, 78, 16, 255, 128, 34, 197, 171,
|
||||||
|
41, 40, 5, 102, 211, 183, 4, 1, 221,
|
||||||
|
51, 50, 17, 168, 209, 192, 23, 25, 82,
|
||||||
|
|
||||||
|
125, 98, 42, 88, 104, 85, 117, 175, 82,
|
||||||
|
95, 84, 53, 89, 128, 100, 113, 101, 45,
|
||||||
|
75, 79, 123, 47, 51, 128, 81, 171, 1,
|
||||||
|
57, 17, 5, 71, 102, 57, 53, 41, 49,
|
||||||
|
115, 21, 2, 10, 102, 255, 166, 23, 6,
|
||||||
|
38, 33, 13, 121, 57, 73, 26, 1, 85,
|
||||||
|
41, 10, 67, 138, 77, 110, 90, 47, 114,
|
||||||
|
101, 29, 16, 10, 85, 128, 101, 196, 26,
|
||||||
|
57, 18, 10, 102, 102, 213, 34, 20, 43,
|
||||||
|
117, 20, 15, 36, 163, 128, 68, 1, 26,
|
||||||
|
|
||||||
|
138, 31, 36, 171, 27, 166, 38, 44, 229,
|
||||||
|
67, 87, 58, 169, 82, 115, 26, 59, 179,
|
||||||
|
63, 59, 90, 180, 59, 166, 93, 73, 154,
|
||||||
|
40, 40, 21, 116, 143, 209, 34, 39, 175,
|
||||||
|
57, 46, 22, 24, 128, 1, 54, 17, 37,
|
||||||
|
47, 15, 16, 183, 34, 223, 49, 45, 183,
|
||||||
|
46, 17, 33, 183, 6, 98, 15, 32, 183,
|
||||||
|
65, 32, 73, 115, 28, 128, 23, 128, 205,
|
||||||
|
40, 3, 9, 115, 51, 192, 18, 6, 223,
|
||||||
|
87, 37, 9, 115, 59, 77, 64, 21, 47,
|
||||||
|
|
||||||
|
104, 55, 44, 218, 9, 54, 53, 130, 226,
|
||||||
|
64, 90, 70, 205, 40, 41, 23, 26, 57,
|
||||||
|
54, 57, 112, 184, 5, 41, 38, 166, 213,
|
||||||
|
30, 34, 26, 133, 152, 116, 10, 32, 134,
|
||||||
|
75, 32, 12, 51, 192, 255, 160, 43, 51,
|
||||||
|
39, 19, 53, 221, 26, 114, 32, 73, 255,
|
||||||
|
31, 9, 65, 234, 2, 15, 1, 118, 73,
|
||||||
|
88, 31, 35, 67, 102, 85, 55, 186, 85,
|
||||||
|
56, 21, 23, 111, 59, 205, 45, 37, 192,
|
||||||
|
55, 38, 70, 124, 73, 102, 1, 34, 98,
|
||||||
|
|
||||||
|
102, 61, 71, 37, 34, 53, 31, 243, 192,
|
||||||
|
69, 60, 71, 38, 73, 119, 28, 222, 37,
|
||||||
|
68, 45, 128, 34, 1, 47, 11, 245, 171,
|
||||||
|
62, 17, 19, 70, 146, 85, 55, 62, 70,
|
||||||
|
75, 15, 9, 9, 64, 255, 184, 119, 16,
|
||||||
|
37, 43, 37, 154, 100, 163, 85, 160, 1,
|
||||||
|
63, 9, 92, 136, 28, 64, 32, 201, 85,
|
||||||
|
86, 6, 28, 5, 64, 255, 25, 248, 1,
|
||||||
|
56, 8, 17, 132, 137, 255, 55, 116, 128,
|
||||||
|
58, 15, 20, 82, 135, 57, 26, 121, 40,
|
||||||
|
|
||||||
|
164, 50, 31, 137, 154, 133, 25, 35, 218,
|
||||||
|
51, 103, 44, 131, 131, 123, 31, 6, 158,
|
||||||
|
86, 40, 64, 135, 148, 224, 45, 183, 128,
|
||||||
|
22, 26, 17, 131, 240, 154, 14, 1, 209,
|
||||||
|
83, 12, 13, 54, 192, 255, 68, 47, 28,
|
||||||
|
45, 16, 21, 91, 64, 222, 7, 1, 197,
|
||||||
|
56, 21, 39, 155, 60, 138, 23, 102, 213,
|
||||||
|
85, 26, 85, 85, 128, 128, 32, 146, 171,
|
||||||
|
18, 11, 7, 63, 144, 171, 4, 4, 246,
|
||||||
|
35, 27, 10, 146, 174, 171, 12, 26, 128,
|
||||||
|
|
||||||
|
190, 80, 35, 99, 180, 80, 126, 54, 45,
|
||||||
|
85, 126, 47, 87, 176, 51, 41, 20, 32,
|
||||||
|
101, 75, 128, 139, 118, 146, 116, 128, 85,
|
||||||
|
56, 41, 15, 176, 236, 85, 37, 9, 62,
|
||||||
|
146, 36, 19, 30, 171, 255, 97, 27, 20,
|
||||||
|
71, 30, 17, 119, 118, 255, 17, 18, 138,
|
||||||
|
101, 38, 60, 138, 55, 70, 43, 26, 142,
|
||||||
|
138, 45, 61, 62, 219, 1, 81, 188, 64,
|
||||||
|
32, 41, 20, 117, 151, 142, 20, 21, 163,
|
||||||
|
112, 19, 12, 61, 195, 128, 48, 4, 24,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>§14.1: dc_qlookup.</summary>
|
||||||
|
public static ReadOnlySpan<byte> DcQuant =>
|
||||||
|
[
|
||||||
|
4, 5, 6, 7, 8, 9, 10, 10, 11, 12,
|
||||||
|
13, 14, 15, 16, 17, 17, 18, 19, 20, 20,
|
||||||
|
21, 21, 22, 22, 23, 23, 24, 25, 25, 26,
|
||||||
|
27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
|
||||||
|
37, 37, 38, 39, 40, 41, 42, 43, 44, 45,
|
||||||
|
46, 46, 47, 48, 49, 50, 51, 52, 53, 54,
|
||||||
|
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
|
||||||
|
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
|
||||||
|
75, 76, 76, 77, 78, 79, 80, 81, 82, 83,
|
||||||
|
84, 85, 86, 87, 88, 89, 91, 93, 95, 96,
|
||||||
|
98, 100, 101, 102, 104, 106, 108, 110, 112, 114,
|
||||||
|
116, 118, 122, 124, 126, 128, 130, 132, 134, 136,
|
||||||
|
138, 140, 143, 145, 148, 151, 154, 157,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>§14.1: ac_qlookup.</summary>
|
||||||
|
public static ReadOnlySpan<short> AcQuant =>
|
||||||
|
[
|
||||||
|
4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
|
||||||
|
14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
|
||||||
|
24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
|
||||||
|
34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
|
||||||
|
44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
|
||||||
|
54, 55, 56, 57, 58, 60, 62, 64, 66, 68,
|
||||||
|
70, 72, 74, 76, 78, 80, 82, 84, 86, 88,
|
||||||
|
90, 92, 94, 96, 98, 100, 102, 104, 106, 108,
|
||||||
|
110, 112, 114, 116, 119, 122, 125, 128, 131, 134,
|
||||||
|
137, 140, 143, 146, 149, 152, 155, 158, 161, 164,
|
||||||
|
167, 170, 173, 177, 181, 185, 189, 193, 197, 201,
|
||||||
|
205, 209, 213, 217, 221, 225, 229, 234, 239, 245,
|
||||||
|
249, 254, 259, 264, 269, 274, 279, 284,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>§13: the zigzag scan, from position in the token stream to raster index in the 4×4 block.</summary>
|
||||||
|
public static ReadOnlySpan<byte> Zigzag => [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
|
||||||
|
|
||||||
|
/// <summary>§13.3: the band of each coefficient position (a 17th entry, never a real position, keeps lookups simple).</summary>
|
||||||
|
public static ReadOnlySpan<byte> Bands => [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0];
|
||||||
|
|
||||||
|
/// <summary>§13.2: the probabilities of the extra bits of DCT_CAT3 to DCT_CAT6 (cat1 and cat2 are read inline).</summary>
|
||||||
|
public static ReadOnlySpan<byte> Cat3 => [173, 148, 140];
|
||||||
|
|
||||||
|
public static ReadOnlySpan<byte> Cat4 => [176, 155, 140, 135];
|
||||||
|
|
||||||
|
public static ReadOnlySpan<byte> Cat5 => [180, 157, 141, 134, 130];
|
||||||
|
|
||||||
|
public static ReadOnlySpan<byte> Cat6 => [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129];
|
||||||
|
|
||||||
|
/// <summary>Number of token probabilities: 4 block types × 8 bands × 3 contexts × 11 tree nodes.</summary>
|
||||||
|
public const int CoefficientProbCount = 4 * 8 * 3 * 11;
|
||||||
|
|
||||||
|
/// <summary>§13.5: default_coeff_probs, flattened [type][band][context][node].</summary>
|
||||||
|
public static ReadOnlySpan<byte> DefaultCoefficientProbs =>
|
||||||
|
[
|
||||||
|
// Block type 0
|
||||||
|
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128,
|
||||||
|
189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128,
|
||||||
|
106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128,
|
||||||
|
1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128,
|
||||||
|
181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128,
|
||||||
|
78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128,
|
||||||
|
1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128,
|
||||||
|
184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128,
|
||||||
|
77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128,
|
||||||
|
1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128,
|
||||||
|
170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128,
|
||||||
|
37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128,
|
||||||
|
1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128,
|
||||||
|
207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128,
|
||||||
|
102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128,
|
||||||
|
1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128,
|
||||||
|
177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128,
|
||||||
|
80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128,
|
||||||
|
1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
|
||||||
|
// Block type 1
|
||||||
|
198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62,
|
||||||
|
131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1,
|
||||||
|
68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128,
|
||||||
|
1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128,
|
||||||
|
184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128,
|
||||||
|
81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128,
|
||||||
|
1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128,
|
||||||
|
99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128,
|
||||||
|
23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128,
|
||||||
|
1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128,
|
||||||
|
109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128,
|
||||||
|
44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128,
|
||||||
|
1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128,
|
||||||
|
94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128,
|
||||||
|
22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128,
|
||||||
|
1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128,
|
||||||
|
124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128,
|
||||||
|
35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128,
|
||||||
|
1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128,
|
||||||
|
121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128,
|
||||||
|
45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128,
|
||||||
|
1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128,
|
||||||
|
203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128,
|
||||||
|
137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128,
|
||||||
|
|
||||||
|
// Block type 2
|
||||||
|
253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128,
|
||||||
|
175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128,
|
||||||
|
73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128,
|
||||||
|
1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128,
|
||||||
|
239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128,
|
||||||
|
155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128,
|
||||||
|
1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128,
|
||||||
|
201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128,
|
||||||
|
69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128,
|
||||||
|
1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128,
|
||||||
|
223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128,
|
||||||
|
141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128,
|
||||||
|
1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128,
|
||||||
|
190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128,
|
||||||
|
149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128,
|
||||||
|
213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128,
|
||||||
|
55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
|
||||||
|
// Block type 3
|
||||||
|
202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255,
|
||||||
|
126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128,
|
||||||
|
61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128,
|
||||||
|
1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128,
|
||||||
|
166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128,
|
||||||
|
39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128,
|
||||||
|
1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128,
|
||||||
|
124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128,
|
||||||
|
24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128,
|
||||||
|
1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128,
|
||||||
|
149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128,
|
||||||
|
28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128,
|
||||||
|
1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128,
|
||||||
|
123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128,
|
||||||
|
20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128,
|
||||||
|
1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128,
|
||||||
|
168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128,
|
||||||
|
47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128,
|
||||||
|
1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128,
|
||||||
|
141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128,
|
||||||
|
42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128,
|
||||||
|
1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>§13.4: coeff_update_probs, flattened like <see cref="DefaultCoefficientProbs"/>.</summary>
|
||||||
|
public static ReadOnlySpan<byte> CoefficientUpdateProbs =>
|
||||||
|
[
|
||||||
|
// Block type 0
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255,
|
||||||
|
250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
|
||||||
|
// Block type 1
|
||||||
|
217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255,
|
||||||
|
234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255,
|
||||||
|
255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
|
||||||
|
// Block type 2
|
||||||
|
186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255,
|
||||||
|
255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
|
||||||
|
// Block type 3
|
||||||
|
248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,511 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads WebP files (RFC 9649): the simple formats (one VP8 or VP8L chunk) and the extended format (VP8X) with alpha
|
||||||
|
/// (ALPH, raw or compressed with VP8L, with its filtering), the colour profile (ICCP), EXIF and XMP. Of an animation
|
||||||
|
/// it decodes the first frame, placed and blended on a transparent canvas as its ANMF chunk says, and counts the
|
||||||
|
/// frames. The pixels come out as straight RGBA8; the EXIF orientation is reported, not applied.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Strictness, as for PNG: data that ends before the last pixel of a picture is damaged (<see cref="ImageDecodeException"/>),
|
||||||
|
/// as is a RIFF size larger than the file or an ALPH chunk that cannot be decoded; unknown chunks and bytes after the
|
||||||
|
/// RIFF size are ignored, metadata chunks beyond <see cref="ImageLimits.MaxMetadataBytes"/> are skipped.
|
||||||
|
/// </remarks>
|
||||||
|
public static class WebPDecoder
|
||||||
|
{
|
||||||
|
private const uint Vp8 = 0x20385056; // "VP8 "
|
||||||
|
private const uint Vp8L = 0x4C385056; // "VP8L"
|
||||||
|
private const uint Vp8X = 0x58385056; // "VP8X"
|
||||||
|
private const uint Alph = 0x48504C41; // "ALPH"
|
||||||
|
private const uint Anim = 0x4D494E41; // "ANIM"
|
||||||
|
private const uint Anmf = 0x464D4E41; // "ANMF"
|
||||||
|
private const uint Iccp = 0x50434349; // "ICCP"
|
||||||
|
private const uint Exif = 0x46495845; // "EXIF"
|
||||||
|
private const uint Xmp = 0x20504D58; // "XMP "
|
||||||
|
|
||||||
|
/// <summary>Whether the bytes start like a WebP file (a RIFF of form WEBP).</summary>
|
||||||
|
public static bool IsWebP(ReadOnlySpan<byte> data) =>
|
||||||
|
data.Length >= 12 && data[..4].SequenceEqual("RIFF"u8) && data.Slice(8, 4).SequenceEqual("WEBP"u8);
|
||||||
|
|
||||||
|
/// <summary>Size, frames and metadata of a WebP, without decoding the pixels.</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged or not a WebP.</exception>
|
||||||
|
public static ImageInfo Identify(ReadOnlyMemory<byte> data, ImageLimits? limits = null)
|
||||||
|
{
|
||||||
|
var bytes = AsArray(data, out var offset);
|
||||||
|
var file = Parse(bytes, offset, data.Length, limits ?? ImageLimits.Default, readMetadata: true);
|
||||||
|
return file.ToInfo();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Decodes a WebP to straight RGBA8 (the first frame of an animation, on its canvas).</summary>
|
||||||
|
/// <exception cref="ImageDecodeException">The file is damaged, truncated or not a WebP.</exception>
|
||||||
|
/// <exception cref="ImageLimitException">The image is larger than <paramref name="limits"/> allow.</exception>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, ImageLimits? limits = null, bool pooled = false) =>
|
||||||
|
Decode(data, out _, limits, pooled, readMetadata: false);
|
||||||
|
|
||||||
|
/// <summary>Decodes a WebP to straight RGBA8 and returns what <see cref="Identify"/> returns as well.</summary>
|
||||||
|
public static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false) =>
|
||||||
|
Decode(data, out info, limits, pooled, readMetadata: true);
|
||||||
|
|
||||||
|
private static RgbaImage Decode(ReadOnlyMemory<byte> data, out ImageInfo info, ImageLimits? limits, bool pooled, bool readMetadata)
|
||||||
|
{
|
||||||
|
limits ??= ImageLimits.Default;
|
||||||
|
var bytes = AsArray(data, out var offset);
|
||||||
|
var file = Parse(bytes, offset, data.Length, limits, readMetadata);
|
||||||
|
var image = RgbaImage.Create(file.Width, file.Height, limits, pooled);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (file.FirstFrame is { } frame)
|
||||||
|
{
|
||||||
|
DrawFrame(bytes, frame, image, limits, pooled);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
DecodePicture(bytes, file.Picture, image, limits);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
info = file.ToInfo();
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly record struct Chunk(uint Type, int Start, int Length);
|
||||||
|
|
||||||
|
/// <summary>A picture: its bitstream chunk (VP8 or VP8L) and, for VP8, its optional ALPH chunk.</summary>
|
||||||
|
private readonly record struct Picture(Chunk Bitstream, Chunk? Alpha, int Width, int Height, bool HasAlpha);
|
||||||
|
|
||||||
|
private sealed record Frame(int X, int Y, bool Blend, Picture Picture);
|
||||||
|
|
||||||
|
private sealed class WebPFile
|
||||||
|
{
|
||||||
|
public int Width;
|
||||||
|
public int Height;
|
||||||
|
public int FrameCount = 1;
|
||||||
|
public bool HasAlpha;
|
||||||
|
public Picture Picture;
|
||||||
|
public Frame? FirstFrame;
|
||||||
|
public byte[]? Exif;
|
||||||
|
public byte[]? Icc;
|
||||||
|
public string? Xmp;
|
||||||
|
|
||||||
|
public ImageInfo ToInfo() => new(
|
||||||
|
ImageFormat.WebP,
|
||||||
|
Width,
|
||||||
|
Height,
|
||||||
|
FrameCount,
|
||||||
|
HasAlpha,
|
||||||
|
Exif is null && Icc is null && Xmp is null
|
||||||
|
? ImageMetadata.Empty
|
||||||
|
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp });
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata)
|
||||||
|
{
|
||||||
|
var span = data.AsSpan(offset, length);
|
||||||
|
if (!IsWebP(span))
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("Non è un file WebP.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var riffSize = BinaryPrimitives.ReadUInt32LittleEndian(span[4..]);
|
||||||
|
if (riffSize < 4)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: misura RIFF non valida.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (riffSize > length - 8)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: il file è più corto della misura RIFF.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var chunks = ReadChunks(data, offset + 12, (int)riffSize - 4);
|
||||||
|
if (chunks.Count == 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: nessun blocco dopo l'intestazione RIFF.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var file = new WebPFile();
|
||||||
|
var first = chunks[0];
|
||||||
|
if (first.Type == Vp8 || first.Type == Vp8L)
|
||||||
|
{
|
||||||
|
file.Picture = ReadPicture(data, first, null);
|
||||||
|
file.Width = file.Picture.Width;
|
||||||
|
file.Height = file.Picture.Height;
|
||||||
|
file.HasAlpha = file.Picture.HasAlpha;
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (first.Type != Vp8X)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: il primo blocco non è VP8, VP8L né VP8X.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (first.Length < 10)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: blocco VP8X troppo corto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var header = data.AsSpan(first.Start, 10);
|
||||||
|
var flags = header[0];
|
||||||
|
file.Width = (int)ReadUInt24(header[4..]) + 1;
|
||||||
|
file.Height = (int)ReadUInt24(header[7..]) + 1;
|
||||||
|
if ((long)file.Width * file.Height > uint.MaxValue)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: la tela VP8X è più grande di quanto il formato ammetta.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var animated = (flags & 0x02) != 0;
|
||||||
|
file.HasAlpha = (flags & 0x10) != 0;
|
||||||
|
var budget = limits.MaxMetadataBytes;
|
||||||
|
Chunk? alpha = null;
|
||||||
|
Chunk? bitstream = null;
|
||||||
|
var frames = 0;
|
||||||
|
for (var i = 1; i < chunks.Count; i++)
|
||||||
|
{
|
||||||
|
var chunk = chunks[i];
|
||||||
|
switch (chunk.Type)
|
||||||
|
{
|
||||||
|
case Anmf:
|
||||||
|
if (frames++ == 0)
|
||||||
|
{
|
||||||
|
file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case Alph:
|
||||||
|
alpha ??= chunk;
|
||||||
|
break;
|
||||||
|
case Vp8:
|
||||||
|
case Vp8L:
|
||||||
|
bitstream ??= chunk;
|
||||||
|
break;
|
||||||
|
case Iccp when readMetadata && file.Icc is null && chunk.Length <= budget:
|
||||||
|
file.Icc = data.AsSpan(chunk.Start, chunk.Length).ToArray();
|
||||||
|
budget -= chunk.Length;
|
||||||
|
break;
|
||||||
|
case Exif when readMetadata && file.Exif is null && chunk.Length <= budget:
|
||||||
|
var exif = data.AsSpan(chunk.Start, chunk.Length);
|
||||||
|
file.Exif = (exif.StartsWith("Exif\0\0"u8) ? exif[6..] : exif).ToArray();
|
||||||
|
budget -= chunk.Length;
|
||||||
|
break;
|
||||||
|
case Xmp when readMetadata && file.Xmp is null && chunk.Length <= budget:
|
||||||
|
file.Xmp = Encoding.UTF8.GetString(data, chunk.Start, chunk.Length);
|
||||||
|
budget -= chunk.Length;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (frames > 0)
|
||||||
|
{
|
||||||
|
file.FrameCount = frames;
|
||||||
|
file.HasAlpha |= file.FirstFrame!.Picture.HasAlpha;
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (animated && bitstream is null)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: animazione senza fotogrammi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bitstream is not { } still)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: manca il blocco con l'immagine.");
|
||||||
|
}
|
||||||
|
|
||||||
|
file.Picture = ReadPicture(data, still, alpha);
|
||||||
|
if (file.Picture.Width != file.Width || file.Picture.Height != file.Height)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: l'immagine non ha la misura della tela VP8X.");
|
||||||
|
}
|
||||||
|
|
||||||
|
file.HasAlpha |= file.Picture.HasAlpha;
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Chunk> ReadChunks(byte[] data, int start, int length)
|
||||||
|
{
|
||||||
|
var chunks = new List<Chunk>();
|
||||||
|
var pos = start;
|
||||||
|
var end = start + length;
|
||||||
|
while (end - pos >= 8)
|
||||||
|
{
|
||||||
|
var type = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(pos));
|
||||||
|
var size = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(pos + 4));
|
||||||
|
if (size > (uint)(end - pos - 8))
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: un blocco dichiara più byte di quelli che il file contiene.");
|
||||||
|
}
|
||||||
|
|
||||||
|
chunks.Add(new Chunk(type, pos + 8, (int)size));
|
||||||
|
pos += 8 + (int)size;
|
||||||
|
if ((size & 1) == 1 && pos < end)
|
||||||
|
{
|
||||||
|
pos++; // padding to an even size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Picture ReadPicture(byte[] data, Chunk bitstream, Chunk? alpha)
|
||||||
|
{
|
||||||
|
var payload = data.AsSpan(bitstream.Start, bitstream.Length);
|
||||||
|
if (bitstream.Type == Vp8L)
|
||||||
|
{
|
||||||
|
var (width, height, alphaUsed) = Vp8LDecoder.ReadHeader(payload);
|
||||||
|
return new Picture(bitstream, null, width, height, alphaUsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (w, h) = Vp8Decoder.ReadSize(payload);
|
||||||
|
if (alpha is { } a && a.Length == 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: blocco ALPH vuoto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Picture(bitstream, alpha, w, h, alpha is not null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Frame ReadFrame(byte[] data, Chunk anmf, int canvasWidth, int canvasHeight)
|
||||||
|
{
|
||||||
|
if (anmf.Length < 16)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: blocco ANMF troppo corto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var header = data.AsSpan(anmf.Start, 16);
|
||||||
|
var x = 2 * (int)ReadUInt24(header);
|
||||||
|
var y = 2 * (int)ReadUInt24(header[3..]);
|
||||||
|
var width = (int)ReadUInt24(header[6..]) + 1;
|
||||||
|
var height = (int)ReadUInt24(header[9..]) + 1;
|
||||||
|
var blend = (header[15] & 0x02) == 0;
|
||||||
|
if ((long)x + width > canvasWidth || (long)y + height > canvasHeight)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: un fotogramma esce dalla tela.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Chunk? alpha = null;
|
||||||
|
Chunk? bitstream = null;
|
||||||
|
foreach (var chunk in ReadChunks(data, anmf.Start + 16, anmf.Length - 16))
|
||||||
|
{
|
||||||
|
if (chunk.Type == Alph)
|
||||||
|
{
|
||||||
|
alpha ??= chunk;
|
||||||
|
}
|
||||||
|
else if (chunk.Type is Vp8 or Vp8L && bitstream is null)
|
||||||
|
{
|
||||||
|
bitstream = chunk;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bitstream is not { } frameBitstream)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: un fotogramma non ha l'immagine.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var picture = ReadPicture(data, frameBitstream, frameBitstream.Type == Vp8 ? alpha : null);
|
||||||
|
if (picture.Width != width || picture.Height != height)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: l'immagine di un fotogramma non ha la misura del suo blocco ANMF.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Frame(x, y, blend, picture);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DecodePicture(byte[] data, Picture picture, RgbaImage target, ImageLimits limits)
|
||||||
|
{
|
||||||
|
var chunk = picture.Bitstream;
|
||||||
|
if (chunk.Type == Vp8L)
|
||||||
|
{
|
||||||
|
Vp8LDecoder.Decode(data, chunk.Start, chunk.Length, limits, target);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Vp8Decoder.Decode(data, chunk.Start, chunk.Length, limits, target);
|
||||||
|
if (picture.Alpha is { } alpha)
|
||||||
|
{
|
||||||
|
WebPAlpha.Decode(data, alpha.Start, alpha.Length, limits, target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The first frame of an animation on a transparent canvas: copied, or blended over the canvas (RFC 9649 §2.7.1.1).
|
||||||
|
private static void DrawFrame(byte[] data, Frame frame, RgbaImage canvas, ImageLimits limits, bool pooled)
|
||||||
|
{
|
||||||
|
var picture = frame.Picture;
|
||||||
|
if (frame.X == 0 && frame.Y == 0 && picture.Width == canvas.Width && picture.Height == canvas.Height && !frame.Blend)
|
||||||
|
{
|
||||||
|
DecodePicture(data, picture, canvas, limits);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
limits.CheckWorkingBytes((long)picture.Width * picture.Height * RgbaImage.BytesPerPixel);
|
||||||
|
using var image = pooled ? RgbaImage.Rent(picture.Width, picture.Height) : new RgbaImage(picture.Width, picture.Height);
|
||||||
|
DecodePicture(data, picture, image, limits);
|
||||||
|
for (var y = 0; y < picture.Height; y++)
|
||||||
|
{
|
||||||
|
var source = image.GetRow(y);
|
||||||
|
var destination = canvas.GetRow(frame.Y + y).Slice(frame.X * 4, picture.Width * 4);
|
||||||
|
if (!frame.Blend)
|
||||||
|
{
|
||||||
|
source.CopyTo(destination);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < source.Length; i += 4)
|
||||||
|
{
|
||||||
|
Blend(source.Slice(i, 4), destination.Slice(i, 4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Alpha blending of RFC 9649 on straight alpha: A = As + Ad·(1 − As); RGB = (RGBs·As + RGBd·Ad·(1 − As)) / A, and
|
||||||
|
/// 0 when A is 0.
|
||||||
|
/// </summary>
|
||||||
|
internal static void Blend(ReadOnlySpan<byte> source, Span<byte> destination)
|
||||||
|
{
|
||||||
|
int sa = source[3];
|
||||||
|
if (sa == 255)
|
||||||
|
{
|
||||||
|
source.CopyTo(destination);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var da = destination[3] * (255 - sa); // ×255
|
||||||
|
var a = (sa * 255) + da; // ×255
|
||||||
|
if (a == 0)
|
||||||
|
{
|
||||||
|
destination.Clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var c = 0; c < 3; c++)
|
||||||
|
{
|
||||||
|
destination[c] = (byte)((((source[c] * sa * 255) + (destination[c] * da)) + (a / 2)) / a);
|
||||||
|
}
|
||||||
|
|
||||||
|
destination[3] = (byte)((a + 127) / 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static uint ReadUInt24(ReadOnlySpan<byte> b) => (uint)(b[0] | (b[1] << 8) | (b[2] << 16));
|
||||||
|
|
||||||
|
private static byte[] AsArray(ReadOnlyMemory<byte> data, out int offset)
|
||||||
|
{
|
||||||
|
if (MemoryMarshal.TryGetArray(data, out var segment) && segment.Array is not null)
|
||||||
|
{
|
||||||
|
offset = segment.Offset;
|
||||||
|
return segment.Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
offset = 0;
|
||||||
|
return data.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The ALPH chunk of RFC 9649 §2.7.1.2: raw or VP8L-compressed alpha, then the inverse of its filter.</summary>
|
||||||
|
internal static class WebPAlpha
|
||||||
|
{
|
||||||
|
/// <summary>Decodes the alpha plane of the chunk payload and writes it into the alpha bytes of <paramref name="target"/>.</summary>
|
||||||
|
public static void Decode(byte[] data, int start, int length, ImageLimits limits, RgbaImage target)
|
||||||
|
{
|
||||||
|
var width = target.Width;
|
||||||
|
var height = target.Height;
|
||||||
|
var header = data[start];
|
||||||
|
var compression = header & 3;
|
||||||
|
var filter = (header >> 2) & 3;
|
||||||
|
var preprocessing = (header >> 4) & 3;
|
||||||
|
if (compression > 1 || preprocessing > 1 || (header >> 6) != 0)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP danneggiato: intestazione ALPH non valida.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var count = width * height;
|
||||||
|
limits.CheckWorkingBytes(count);
|
||||||
|
var alpha = ImageBuffers.Rent<byte>(count);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var plane = alpha.AsSpan(0, count);
|
||||||
|
if (compression == 0)
|
||||||
|
{
|
||||||
|
if (length - 1 < count)
|
||||||
|
{
|
||||||
|
throw new ImageDecodeException("WebP troncato: l'alfa del blocco ALPH è incompleta.");
|
||||||
|
}
|
||||||
|
|
||||||
|
data.AsSpan(start + 1, count).CopyTo(plane);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Vp8LDecoder.DecodeAlpha(data, start + 1, length - 1, width, height, limits, plane);
|
||||||
|
}
|
||||||
|
|
||||||
|
Unfilter(plane, width, height, filter);
|
||||||
|
var pixels = target.Pixels;
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
pixels[(i * 4) + 3] = plane[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ImageBuffers.Return(alpha);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Undoes the prediction filter of the alpha plane: 1 horizontal (from the left), 2 vertical (from above), 3
|
||||||
|
/// gradient (left + above − above-left, clamped). The first pixel is predicted from 0, the rest of the first row
|
||||||
|
/// from the left and the first column from above.
|
||||||
|
/// </summary>
|
||||||
|
internal static void Unfilter(Span<byte> plane, int width, int height, int filter)
|
||||||
|
{
|
||||||
|
if (filter == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var x = 1; x < width; x++)
|
||||||
|
{
|
||||||
|
plane[x] += plane[x - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var y = 1; y < height; y++)
|
||||||
|
{
|
||||||
|
var row = plane.Slice(y * width, width);
|
||||||
|
var above = plane.Slice((y - 1) * width, width);
|
||||||
|
row[0] += above[0];
|
||||||
|
switch (filter)
|
||||||
|
{
|
||||||
|
case 1:
|
||||||
|
for (var x = 1; x < width; x++)
|
||||||
|
{
|
||||||
|
row[x] += row[x - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
for (var x = 1; x < width; x++)
|
||||||
|
{
|
||||||
|
row[x] += above[x];
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
for (var x = 1; x < width; x++)
|
||||||
|
{
|
||||||
|
row[x] += (byte)Math.Clamp(row[x - 1] + above[x] - above[x - 1], 0, 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
/// <summary>Options of <see cref="WebPEncoder"/>.</summary>
|
||||||
|
public sealed record WebPEncoderOptions
|
||||||
|
{
|
||||||
|
/// <summary>The options used when a caller passes none.</summary>
|
||||||
|
public static WebPEncoderOptions Default { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// EXIF to write in an EXIF chunk: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by the «Exif\0\0»
|
||||||
|
/// of a JPEG APP1 segment, which is removed.
|
||||||
|
/// </summary>
|
||||||
|
public byte[]? Exif { get; init; }
|
||||||
|
|
||||||
|
/// <summary>ICC profile to write in an ICCP chunk.</summary>
|
||||||
|
public byte[]? IccProfile { get; init; }
|
||||||
|
|
||||||
|
/// <summary>XMP packet to write in an XMP chunk (UTF-8).</summary>
|
||||||
|
public string? Xmp { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The tools of the lossless encoder (tests turn them on and off one by one).</summary>
|
||||||
|
internal Vp8LEncoderSettings Lossless { get; init; } = Vp8LEncoderSettings.Default;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes lossless WebP files (RFC 9649): one VP8L chunk, inside the extended format (VP8X, then ICCP, VP8L, EXIF,
|
||||||
|
/// XMP) when there is metadata. Every pixel comes back exactly, the colour under a transparent pixel included.
|
||||||
|
/// </summary>
|
||||||
|
public static class WebPEncoder
|
||||||
|
{
|
||||||
|
/// <summary>Largest width or height a WebP picture can have.</summary>
|
||||||
|
public const int MaxDimension = 16384;
|
||||||
|
|
||||||
|
/// <summary>The WebP file of <paramref name="image"/>.</summary>
|
||||||
|
/// <exception cref="ArgumentOutOfRangeException">The image is wider or taller than <see cref="MaxDimension"/>.</exception>
|
||||||
|
/// <exception cref="ArgumentException">The EXIF block is not a TIFF structure.</exception>
|
||||||
|
public static byte[] Encode(RgbaImage image, WebPEncoderOptions? options = null)
|
||||||
|
{
|
||||||
|
using var output = new MemoryStream();
|
||||||
|
Encode(image, output, options);
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the WebP file of <paramref name="image"/> to <paramref name="output"/>.</summary>
|
||||||
|
public static void Encode(RgbaImage image, Stream output, WebPEncoderOptions? options = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(image);
|
||||||
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
options ??= WebPEncoderOptions.Default;
|
||||||
|
var exif = options.Exif is { } givenExif ? ExifPayload(givenExif) : null;
|
||||||
|
var xmp = options.Xmp is { } givenXmp ? Encoding.UTF8.GetBytes(givenXmp) : null;
|
||||||
|
var bitstream = EncodeBitstream(image, options.Lossless);
|
||||||
|
var alpha = !image.IsOpaque();
|
||||||
|
var extended = exif is not null || options.IccProfile is not null || xmp is not null;
|
||||||
|
|
||||||
|
var size = 4L + ChunkSize(bitstream.Length);
|
||||||
|
if (extended)
|
||||||
|
{
|
||||||
|
size += ChunkSize(10) + ChunkSize(options.IccProfile?.Length) + ChunkSize(exif?.Length) + ChunkSize(xmp?.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (size > uint.MaxValue - 8)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("The WebP file would be larger than RIFF allows.", nameof(image));
|
||||||
|
}
|
||||||
|
|
||||||
|
Span<byte> header = stackalloc byte[12];
|
||||||
|
"RIFF"u8.CopyTo(header);
|
||||||
|
BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)size);
|
||||||
|
"WEBP"u8.CopyTo(header[8..]);
|
||||||
|
output.Write(header);
|
||||||
|
if (extended)
|
||||||
|
{
|
||||||
|
Span<byte> vp8x = stackalloc byte[10];
|
||||||
|
vp8x.Clear();
|
||||||
|
vp8x[0] = (byte)((options.IccProfile is not null ? 0x20 : 0) | (alpha ? 0x10 : 0) | (exif is not null ? 0x08 : 0) | (xmp is not null ? 0x04 : 0));
|
||||||
|
WriteUInt24(vp8x[4..], image.Width - 1);
|
||||||
|
WriteUInt24(vp8x[7..], image.Height - 1);
|
||||||
|
WriteChunk(output, "VP8X"u8, vp8x);
|
||||||
|
if (options.IccProfile is { } icc)
|
||||||
|
{
|
||||||
|
WriteChunk(output, "ICCP"u8, icc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteChunk(output, "VP8L"u8, bitstream);
|
||||||
|
if (exif is not null)
|
||||||
|
{
|
||||||
|
WriteChunk(output, "EXIF"u8, exif);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (xmp is not null)
|
||||||
|
{
|
||||||
|
WriteChunk(output, "XMP "u8, xmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The VP8L bitstream (signature, header, image stream) of <paramref name="image"/>.</summary>
|
||||||
|
internal static byte[] EncodeBitstream(RgbaImage image, Vp8LEncoderSettings settings)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Width, MaxDimension, nameof(image));
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(image.Height, MaxDimension, nameof(image));
|
||||||
|
var argb = ToArgb(image);
|
||||||
|
var writer = new Vp8LBitWriter(image.Length / 4);
|
||||||
|
writer.WriteBits(Vp8LDecoder.Signature, 8);
|
||||||
|
writer.WriteBits((uint)(image.Width - 1), 14);
|
||||||
|
writer.WriteBits((uint)(image.Height - 1), 14);
|
||||||
|
writer.WriteBits(image.IsOpaque() ? 0u : 1u, 1);
|
||||||
|
writer.WriteBits(0, 3);
|
||||||
|
Vp8LEncoder.WriteImageStream(writer, argb, image.Width, image.Height, settings);
|
||||||
|
return writer.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The headerless image stream of an ALPH chunk compressed with VP8L: the alpha values in the green channel.
|
||||||
|
/// </summary>
|
||||||
|
internal static byte[] EncodeAlphaStream(ReadOnlySpan<byte> alpha, int width, int height, Vp8LEncoderSettings settings)
|
||||||
|
{
|
||||||
|
var argb = new uint[width * height];
|
||||||
|
for (var i = 0; i < argb.Length; i++)
|
||||||
|
{
|
||||||
|
argb[i] = 0xFF000000 | ((uint)alpha[i] << 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
var writer = new Vp8LBitWriter(argb.Length / 4);
|
||||||
|
Vp8LEncoder.WriteImageStream(writer, argb, width, height, settings);
|
||||||
|
return writer.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static uint[] ToArgb(RgbaImage image)
|
||||||
|
{
|
||||||
|
var pixels = image.Pixels;
|
||||||
|
var argb = new uint[image.Width * image.Height];
|
||||||
|
for (var i = 0; i < argb.Length; i++)
|
||||||
|
{
|
||||||
|
var o = i * 4;
|
||||||
|
argb[i] = ((uint)pixels[o + 3] << 24) | ((uint)pixels[o] << 16) | ((uint)pixels[o + 1] << 8) | pixels[o + 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
return argb;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long ChunkSize(int? length) => length is { } n ? 8L + n + (n & 1) : 0;
|
||||||
|
|
||||||
|
private static void WriteChunk(Stream output, ReadOnlySpan<byte> type, ReadOnlySpan<byte> payload)
|
||||||
|
{
|
||||||
|
Span<byte> header = stackalloc byte[8];
|
||||||
|
type.CopyTo(header);
|
||||||
|
BinaryPrimitives.WriteUInt32LittleEndian(header[4..], (uint)payload.Length);
|
||||||
|
output.Write(header);
|
||||||
|
output.Write(payload);
|
||||||
|
if ((payload.Length & 1) == 1)
|
||||||
|
{
|
||||||
|
output.WriteByte(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteUInt24(Span<byte> destination, int value)
|
||||||
|
{
|
||||||
|
destination[0] = (byte)value;
|
||||||
|
destination[1] = (byte)(value >> 8);
|
||||||
|
destination[2] = (byte)(value >> 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] ExifPayload(byte[] exif)
|
||||||
|
{
|
||||||
|
ReadOnlySpan<byte> span = exif;
|
||||||
|
if (span.StartsWith("Exif\0\0"u8))
|
||||||
|
{
|
||||||
|
span = span[6..];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (span.Length < 8 || !(span.StartsWith("II*\0"u8) || span.StartsWith("MM\0*"u8)))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("EXIF must be a TIFF structure starting with «II*\\0» or «MM\\0*».", nameof(exif));
|
||||||
|
}
|
||||||
|
|
||||||
|
return span.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Febe.Core.Drawing;
|
||||||
|
|
||||||
|
/// <summary>What fills a shape: one colour or a gradient.</summary>
|
||||||
|
public abstract class Brush
|
||||||
|
{
|
||||||
|
private protected Brush()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The colours of <paramref name="output"/>.Length pixels of row <paramref name="y"/> from column
|
||||||
|
/// <paramref name="x0"/>: red, green and blue 0-255, alpha 0-1, not premultiplied. <paramref name="toUser"/> maps
|
||||||
|
/// canvas pixels back to the coordinates the brush was defined in.
|
||||||
|
/// </summary>
|
||||||
|
internal abstract void Shade(in Matrix3x2 toUser, int y, int x0, Span<Vector4> output);
|
||||||
|
|
||||||
|
/// <summary>A colour as the shading works with it.</summary>
|
||||||
|
internal static Vector4 ToVector(Color color) => new(color.R, color.G, color.B, color.A / 255f);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One colour.</summary>
|
||||||
|
public sealed class SolidBrush(Color color) : Brush
|
||||||
|
{
|
||||||
|
public Color Color { get; } = color;
|
||||||
|
|
||||||
|
internal Vector4 Value { get; } = ToVector(color);
|
||||||
|
|
||||||
|
internal override void Shade(in Matrix3x2 toUser, int y, int x0, Span<Vector4> output) => output.Fill(Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A linear gradient from <see cref="Start"/> to <see cref="End"/>: the colours change along that line and stay the
|
||||||
|
/// same across it; before the start and after the end the first and last colours continue. Colours are interpolated
|
||||||
|
/// without premultiplying.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LinearGradientBrush : Brush
|
||||||
|
{
|
||||||
|
private readonly Vector4[] _colors;
|
||||||
|
private readonly float[] _positions;
|
||||||
|
|
||||||
|
/// <param name="start">Where the first colour is, in the coordinates the shape is drawn in.</param>
|
||||||
|
/// <param name="end">Where the last colour is.</param>
|
||||||
|
/// <param name="colors">Two or more colours.</param>
|
||||||
|
/// <param name="positions">Where each colour sits between start (0) and end (1), increasing; evenly spaced when null.</param>
|
||||||
|
public LinearGradientBrush(Vector2 start, Vector2 end, IReadOnlyList<Color> colors, IReadOnlyList<float>? positions = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(colors);
|
||||||
|
if (colors.Count < 2)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("A gradient needs at least two colours.", nameof(colors));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (positions is not null && positions.Count != colors.Count)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("One position per colour.", nameof(positions));
|
||||||
|
}
|
||||||
|
|
||||||
|
Start = start;
|
||||||
|
End = end;
|
||||||
|
_colors = new Vector4[colors.Count];
|
||||||
|
_positions = new float[colors.Count];
|
||||||
|
for (var i = 0; i < colors.Count; i++)
|
||||||
|
{
|
||||||
|
_colors[i] = ToVector(colors[i]);
|
||||||
|
_positions[i] = positions is null ? i / (float)(colors.Count - 1) : Math.Clamp(positions[i], i == 0 ? 0 : _positions[i - 1], 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Vector2 Start { get; }
|
||||||
|
|
||||||
|
public Vector2 End { get; }
|
||||||
|
|
||||||
|
internal override void Shade(in Matrix3x2 toUser, int y, int x0, Span<Vector4> output)
|
||||||
|
{
|
||||||
|
var direction = End - Start;
|
||||||
|
var lengthSquared = direction.LengthSquared();
|
||||||
|
if (lengthSquared < 1e-12f)
|
||||||
|
{
|
||||||
|
output.Fill(_colors[^1]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// t = (p − start)·d / |d|², p the centre of the pixel in user coordinates; it grows by a constant per column.
|
||||||
|
var first = Vector2.Transform(new Vector2(x0 + 0.5f, y + 0.5f), toUser);
|
||||||
|
var t = Vector2.Dot(first - Start, direction) / lengthSquared;
|
||||||
|
var step = Vector2.Dot(new Vector2(toUser.M11, toUser.M12), direction) / lengthSquared;
|
||||||
|
for (var i = 0; i < output.Length; i++)
|
||||||
|
{
|
||||||
|
output[i] = At(t + (step * i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Vector4 At(float t)
|
||||||
|
{
|
||||||
|
if (t <= _positions[0])
|
||||||
|
{
|
||||||
|
return _colors[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
var last = _positions.Length - 1;
|
||||||
|
if (t >= _positions[last])
|
||||||
|
{
|
||||||
|
return _colors[last];
|
||||||
|
}
|
||||||
|
|
||||||
|
var i = 1;
|
||||||
|
while (_positions[i] < t)
|
||||||
|
{
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
var span = _positions[i] - _positions[i - 1];
|
||||||
|
var f = span <= 0 ? 1 : (t - _positions[i - 1]) / span;
|
||||||
|
return Vector4.Lerp(_colors[i - 1], _colors[i], f);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,549 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Core.Drawing;
|
||||||
|
|
||||||
|
/// <summary>How the ends of a stroked line look.</summary>
|
||||||
|
public enum LineCap
|
||||||
|
{
|
||||||
|
/// <summary>The line stops at its end points.</summary>
|
||||||
|
Butt,
|
||||||
|
|
||||||
|
/// <summary>A half circle around each end point.</summary>
|
||||||
|
Round,
|
||||||
|
|
||||||
|
/// <summary>The line goes on for half its width beyond each end point.</summary>
|
||||||
|
Square,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Draws anti-aliased shapes on an <see cref="RgbaImage"/>: filled paths, rectangles, circles and ellipses, stroked
|
||||||
|
/// lines and outlines, linear gradients, blurred discs and resized images, each composited over what is there
|
||||||
|
/// (source over, straight alpha). Coordinates go through <see cref="Transform"/>, which <see cref="Translate"/>,
|
||||||
|
/// <see cref="Scale"/> and <see cref="Rotate"/> change and <see cref="Save"/> / <see cref="Restore"/> keep.
|
||||||
|
/// Written in house (no graphics library): the coverage of every pixel is the exact area of the shape inside it.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class Canvas : IDisposable
|
||||||
|
{
|
||||||
|
private readonly RgbaImage _target;
|
||||||
|
private readonly Stack<Matrix2D> _saved = new();
|
||||||
|
private readonly CoverageRasterizer _rasterizer = new();
|
||||||
|
|
||||||
|
public Canvas(RgbaImage target)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(target);
|
||||||
|
_target = target;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Width => _target.Width;
|
||||||
|
|
||||||
|
public int Height => _target.Height;
|
||||||
|
|
||||||
|
/// <summary>The image drawn on.</summary>
|
||||||
|
public RgbaImage Target => _target;
|
||||||
|
|
||||||
|
/// <summary>From the coordinates of the shapes to the pixels of the canvas.</summary>
|
||||||
|
public Matrix2D Transform { get; set; } = Matrix2D.Identity;
|
||||||
|
|
||||||
|
/// <summary>Remembers the transform, for <see cref="Restore"/>.</summary>
|
||||||
|
public void Save() => _saved.Push(Transform);
|
||||||
|
|
||||||
|
/// <summary>Back to the transform of the last <see cref="Save"/>.</summary>
|
||||||
|
public void Restore() => Transform = _saved.Count > 0 ? _saved.Pop() : Matrix2D.Identity;
|
||||||
|
|
||||||
|
public void Translate(float x, float y) => Transform = Transform.Then(Matrix2D.Translation(x, y));
|
||||||
|
|
||||||
|
public void Scale(float x, float y) => Transform = Transform.Then(Matrix2D.Scaling(x, y));
|
||||||
|
|
||||||
|
public void Scale(float factor) => Scale(factor, factor);
|
||||||
|
|
||||||
|
/// <summary>Rotates the shapes drawn next by <paramref name="degrees"/> around the origin, clockwise on screen.</summary>
|
||||||
|
public void Rotate(float degrees) => Transform = Transform.Then(Matrix2D.Rotation(degrees));
|
||||||
|
|
||||||
|
/// <summary>Every pixel set to <paramref name="color"/>, ignoring what was there.</summary>
|
||||||
|
public void Clear(Color color)
|
||||||
|
{
|
||||||
|
var pixels = _target.Pixels;
|
||||||
|
Span<byte> one = [color.R, color.G, color.B, color.A];
|
||||||
|
for (var i = 0; i < pixels.Length; i += 4)
|
||||||
|
{
|
||||||
|
one.CopyTo(pixels.Slice(i, 4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Fill(PathBuilder path, Color color) => Fill(path, new SolidBrush(color));
|
||||||
|
|
||||||
|
/// <summary>Fills the shape <paramref name="path"/> describes (non-zero winding).</summary>
|
||||||
|
public void Fill(PathBuilder path, Brush brush)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(path);
|
||||||
|
ArgumentNullException.ThrowIfNull(brush);
|
||||||
|
var contours = path.Flatten(Transform);
|
||||||
|
FillPolygons(contours, brush);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void FillRect(float x, float y, float width, float height, Color color) => FillRect(x, y, width, height, new SolidBrush(color));
|
||||||
|
|
||||||
|
/// <summary>Fills a rectangle; without rotation the coverage of its border pixels is computed directly.</summary>
|
||||||
|
public void FillRect(float x, float y, float width, float height, Brush brush)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(brush);
|
||||||
|
var m = Transform.Value;
|
||||||
|
if (m.M12 == 0 && m.M21 == 0)
|
||||||
|
{
|
||||||
|
var a = Transform.Apply(new Vector2(x, y));
|
||||||
|
var b = Transform.Apply(new Vector2(x + width, y + height));
|
||||||
|
FillAlignedRect(MathF.Min(a.X, b.X), MathF.Min(a.Y, b.Y), MathF.Max(a.X, b.X), MathF.Max(a.Y, b.Y), brush);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Fill(new PathBuilder().AddRect(x, y, width, height), brush);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void FillRoundRect(float x, float y, float width, float height, float radius, Color color) =>
|
||||||
|
Fill(new PathBuilder().AddRoundRect(x, y, width, height, radius), color);
|
||||||
|
|
||||||
|
public void FillCircle(float cx, float cy, float r, Color color) => Fill(new PathBuilder().AddCircle(cx, cy, r), color);
|
||||||
|
|
||||||
|
public void FillEllipse(float cx, float cy, float rx, float ry, Color color) => Fill(new PathBuilder().AddEllipse(cx, cy, rx, ry), color);
|
||||||
|
|
||||||
|
/// <summary>The outline of a rectangle, <paramref name="lineWidth"/> wide and centred on its sides, square corners.</summary>
|
||||||
|
public void StrokeRect(float x, float y, float width, float height, float lineWidth, Color color)
|
||||||
|
{
|
||||||
|
var half = lineWidth / 2;
|
||||||
|
var path = new PathBuilder().AddRect(x - half, y - half, width + lineWidth, height + lineWidth);
|
||||||
|
if (width > lineWidth && height > lineWidth)
|
||||||
|
{
|
||||||
|
path.AddRect(x + half, y + half, width - lineWidth, height - lineWidth, clockwise: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Fill(path, color);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A ring: the outline of an ellipse, <paramref name="lineWidth"/> wide and centred on it.</summary>
|
||||||
|
public void StrokeEllipse(float cx, float cy, float rx, float ry, float lineWidth, Color color)
|
||||||
|
{
|
||||||
|
var half = lineWidth / 2;
|
||||||
|
var path = new PathBuilder().AddEllipse(cx, cy, rx + half, ry + half);
|
||||||
|
if (rx > half && ry > half)
|
||||||
|
{
|
||||||
|
path.AddEllipse(cx, cy, rx - half, ry - half, clockwise: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Fill(path, color);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void StrokeCircle(float cx, float cy, float r, float lineWidth, Color color) => StrokeEllipse(cx, cy, r, r, lineWidth, color);
|
||||||
|
|
||||||
|
/// <summary>A straight line <paramref name="lineWidth"/> wide.</summary>
|
||||||
|
public void DrawLine(float x0, float y0, float x1, float y1, float lineWidth, Color color, LineCap cap = LineCap.Butt) =>
|
||||||
|
Stroke(new PathBuilder().MoveTo(x0, y0).LineTo(x1, y1), lineWidth, color, cap);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The contours of <paramref name="path"/> drawn as lines <paramref name="lineWidth"/> wide, with round joins
|
||||||
|
/// and the given caps on open contours.
|
||||||
|
/// </summary>
|
||||||
|
public void Stroke(PathBuilder path, float lineWidth, Color color, LineCap cap = LineCap.Butt)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(path);
|
||||||
|
if (lineWidth <= 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var half = lineWidth * Transform.LengthScale / 2;
|
||||||
|
var pieces = new List<Vector2[]>();
|
||||||
|
foreach (var contour in path.Flatten(Transform))
|
||||||
|
{
|
||||||
|
StrokePieces(contour, half, cap, pieces);
|
||||||
|
}
|
||||||
|
|
||||||
|
FillPolygons(pieces, new SolidBrush(color));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A disc whose edge is blurred by a Gaussian of <paramref name="sigma"/> (in the units of the shapes): the
|
||||||
|
/// coverage at distance d from the centre is ½·erfc((d − r) / (σ√2)), the disc convolved with the Gaussian
|
||||||
|
/// across its edge.
|
||||||
|
/// </summary>
|
||||||
|
public void FillBlurredCircle(float cx, float cy, float r, float sigma, Color color)
|
||||||
|
{
|
||||||
|
var scale = Transform.LengthScale;
|
||||||
|
var centre = Transform.Apply(new Vector2(cx, cy));
|
||||||
|
var radius = r * scale;
|
||||||
|
var s = MathF.Max(sigma * scale, 1e-3f);
|
||||||
|
var reach = radius + (3.5f * s);
|
||||||
|
var left = Math.Max(0, (int)MathF.Floor(centre.X - reach));
|
||||||
|
var right = Math.Min(Width, (int)MathF.Ceiling(centre.X + reach));
|
||||||
|
var top = Math.Max(0, (int)MathF.Floor(centre.Y - reach));
|
||||||
|
var bottom = Math.Min(Height, (int)MathF.Ceiling(centre.Y + reach));
|
||||||
|
if (left >= right || top >= bottom)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rgba = Brush.ToVector(color);
|
||||||
|
var inverse = 1 / (s * MathF.Sqrt(2));
|
||||||
|
for (var y = top; y < bottom; y++)
|
||||||
|
{
|
||||||
|
var row = _target.GetRow(y);
|
||||||
|
var dy = y + 0.5f - centre.Y;
|
||||||
|
for (var x = left; x < right; x++)
|
||||||
|
{
|
||||||
|
var dx = x + 0.5f - centre.X;
|
||||||
|
var d = MathF.Sqrt((dx * dx) + (dy * dy));
|
||||||
|
var coverage = 0.5f * Erfc((d - radius) * inverse);
|
||||||
|
if (coverage > 1f / 1024)
|
||||||
|
{
|
||||||
|
BlendPixel(row.Slice(x * 4, 4), rgba, rgba.W * coverage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Composites one colour over one pixel, without anti-aliasing (canvas pixels, the transform ignored).</summary>
|
||||||
|
public void BlendPixel(int x, int y, Color color)
|
||||||
|
{
|
||||||
|
if ((uint)x >= (uint)Width || (uint)y >= (uint)Height)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rgba = Brush.ToVector(color);
|
||||||
|
BlendPixel(_target.GetRow(y).Slice(x * 4, 4), rgba, rgba.W);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Draws <paramref name="image"/> resized (Lanczos) to the rectangle (x, y, width, height) in canvas pixels, its
|
||||||
|
/// edges rounded to whole pixels, over what is there; the transform is not applied.
|
||||||
|
/// </summary>
|
||||||
|
public void DrawImage(RgbaImage image, float x, float y, float width, float height)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(image);
|
||||||
|
var left = (int)MathF.Round(x);
|
||||||
|
var top = (int)MathF.Round(y);
|
||||||
|
var w = (int)MathF.Round(x + width) - left;
|
||||||
|
var h = (int)MathF.Round(y + height) - top;
|
||||||
|
if (w <= 0 || h <= 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var resized = ImageResampler.Resize(image, w, h, pooled: true);
|
||||||
|
for (var row = 0; row < h; row++)
|
||||||
|
{
|
||||||
|
var ty = top + row;
|
||||||
|
if ((uint)ty >= (uint)Height)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var source = resized.GetRow(row);
|
||||||
|
var target = _target.GetRow(ty);
|
||||||
|
for (var col = 0; col < w; col++)
|
||||||
|
{
|
||||||
|
var tx = left + col;
|
||||||
|
if ((uint)tx >= (uint)Width)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var s = source.Slice(col * 4, 4);
|
||||||
|
if (s[3] == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
BlendPixel(target.Slice(tx * 4, 4), new Vector4(s[0], s[1], s[2], s[3] / 255f), s[3] / 255f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _rasterizer.Dispose();
|
||||||
|
|
||||||
|
private void FillPolygons(IReadOnlyList<Polyline> contours, Brush brush)
|
||||||
|
{
|
||||||
|
var polygons = new List<Vector2[]>(contours.Count);
|
||||||
|
foreach (var contour in contours)
|
||||||
|
{
|
||||||
|
if (contour.Points.Length >= 3)
|
||||||
|
{
|
||||||
|
polygons.Add(contour.Points);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FillPolygons(polygons, brush);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FillPolygons(List<Vector2[]> polygons, Brush brush)
|
||||||
|
{
|
||||||
|
if (polygons.Count == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var minX = float.MaxValue;
|
||||||
|
var minY = float.MaxValue;
|
||||||
|
var maxX = float.MinValue;
|
||||||
|
var maxY = float.MinValue;
|
||||||
|
foreach (var polygon in polygons)
|
||||||
|
{
|
||||||
|
foreach (var p in polygon)
|
||||||
|
{
|
||||||
|
minX = MathF.Min(minX, p.X);
|
||||||
|
minY = MathF.Min(minY, p.Y);
|
||||||
|
maxX = MathF.Max(maxX, p.X);
|
||||||
|
maxY = MathF.Max(maxY, p.Y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!float.IsFinite(minX) || !float.IsFinite(maxX) || !float.IsFinite(minY) || !float.IsFinite(maxY))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var left = Math.Max(0, (int)MathF.Floor(minX));
|
||||||
|
var top = Math.Max(0, (int)MathF.Floor(minY));
|
||||||
|
var right = Math.Min(Width, (int)MathF.Ceiling(maxX) + 1);
|
||||||
|
var bottom = Math.Min(Height, (int)MathF.Ceiling(maxY) + 1);
|
||||||
|
if (left >= right || top >= bottom)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_rasterizer.Reset(left, top, right - left, bottom - top);
|
||||||
|
foreach (var polygon in polygons)
|
||||||
|
{
|
||||||
|
_rasterizer.AddPolygon(polygon);
|
||||||
|
}
|
||||||
|
|
||||||
|
var width = right - left;
|
||||||
|
var coverage = ArrayPool<float>.Shared.Rent(width);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (var y = 0; y < bottom - top; y++)
|
||||||
|
{
|
||||||
|
_rasterizer.Coverage(y, coverage.AsSpan(0, width));
|
||||||
|
BlendRow(top + y, left, coverage.AsSpan(0, width), brush);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<float>.Shared.Return(coverage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FillAlignedRect(float x0, float y0, float x1, float y1, Brush brush)
|
||||||
|
{
|
||||||
|
var left = Math.Max(0, (int)MathF.Floor(x0));
|
||||||
|
var right = Math.Min(Width, (int)MathF.Ceiling(x1));
|
||||||
|
var top = Math.Max(0, (int)MathF.Floor(y0));
|
||||||
|
var bottom = Math.Min(Height, (int)MathF.Ceiling(y1));
|
||||||
|
if (left >= right || top >= bottom)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var width = right - left;
|
||||||
|
var columns = ArrayPool<float>.Shared.Rent(width);
|
||||||
|
var coverage = ArrayPool<float>.Shared.Rent(width);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (var i = 0; i < width; i++)
|
||||||
|
{
|
||||||
|
var px = left + i;
|
||||||
|
columns[i] = MathF.Max(0, MathF.Min(px + 1, x1) - MathF.Max(px, x0));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var y = top; y < bottom; y++)
|
||||||
|
{
|
||||||
|
var rowCoverage = MathF.Max(0, MathF.Min(y + 1, y1) - MathF.Max(y, y0));
|
||||||
|
for (var i = 0; i < width; i++)
|
||||||
|
{
|
||||||
|
coverage[i] = columns[i] * rowCoverage;
|
||||||
|
}
|
||||||
|
|
||||||
|
BlendRow(y, left, coverage.AsSpan(0, width), brush);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<float>.Shared.Return(columns);
|
||||||
|
ArrayPool<float>.Shared.Return(coverage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void BlendRow(int y, int left, ReadOnlySpan<float> coverage, Brush brush)
|
||||||
|
{
|
||||||
|
var row = _target.GetRow(y);
|
||||||
|
if (brush is SolidBrush solid)
|
||||||
|
{
|
||||||
|
var color = solid.Value;
|
||||||
|
for (var i = 0; i < coverage.Length; i++)
|
||||||
|
{
|
||||||
|
var c = coverage[i];
|
||||||
|
if (c > 1f / 1024)
|
||||||
|
{
|
||||||
|
BlendPixel(row.Slice((left + i) * 4, 4), color, color.W * c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Matrix3x2.Invert(Transform.Value, out var toUser);
|
||||||
|
var colors = ArrayPool<Vector4>.Shared.Rent(coverage.Length);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var shades = colors.AsSpan(0, coverage.Length);
|
||||||
|
brush.Shade(toUser, y, left, shades);
|
||||||
|
for (var i = 0; i < coverage.Length; i++)
|
||||||
|
{
|
||||||
|
var c = coverage[i];
|
||||||
|
if (c > 1f / 1024)
|
||||||
|
{
|
||||||
|
BlendPixel(row.Slice((left + i) * 4, 4), shades[i], shades[i].W * c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
ArrayPool<Vector4>.Shared.Return(colors);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Source over, straight alpha: <paramref name="alpha"/> is the colour's alpha times the coverage.</summary>
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static void BlendPixel(Span<byte> pixel, Vector4 color, float alpha)
|
||||||
|
{
|
||||||
|
if (alpha <= 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (alpha >= 1)
|
||||||
|
{
|
||||||
|
pixel[0] = (byte)(color.X + 0.5f);
|
||||||
|
pixel[1] = (byte)(color.Y + 0.5f);
|
||||||
|
pixel[2] = (byte)(color.Z + 0.5f);
|
||||||
|
pixel[3] = 255;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int below = pixel[3];
|
||||||
|
if (below == 255)
|
||||||
|
{
|
||||||
|
pixel[0] = (byte)(pixel[0] + ((color.X - pixel[0]) * alpha) + 0.5f);
|
||||||
|
pixel[1] = (byte)(pixel[1] + ((color.Y - pixel[1]) * alpha) + 0.5f);
|
||||||
|
pixel[2] = (byte)(pixel[2] + ((color.Z - pixel[2]) * alpha) + 0.5f);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var da = below / 255f;
|
||||||
|
var outAlpha = alpha + (da * (1 - alpha));
|
||||||
|
var keep = da * (1 - alpha) / outAlpha;
|
||||||
|
var take = alpha / outAlpha;
|
||||||
|
pixel[0] = (byte)((color.X * take) + (pixel[0] * keep) + 0.5f);
|
||||||
|
pixel[1] = (byte)((color.Y * take) + (pixel[1] * keep) + 0.5f);
|
||||||
|
pixel[2] = (byte)((color.Z * take) + (pixel[2] * keep) + 0.5f);
|
||||||
|
pixel[3] = (byte)((outAlpha * 255) + 0.5f);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The pieces of a stroke: a quadrilateral per segment, a disc per join, the caps; all turning the same way.</summary>
|
||||||
|
private static void StrokePieces(Polyline contour, float half, LineCap cap, List<Vector2[]> pieces)
|
||||||
|
{
|
||||||
|
var points = contour.Points;
|
||||||
|
var count = points.Length;
|
||||||
|
if (count < 2)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var segments = contour.Closed ? count : count - 1;
|
||||||
|
for (var i = 0; i < segments; i++)
|
||||||
|
{
|
||||||
|
var a = points[i];
|
||||||
|
var b = points[(i + 1) % count];
|
||||||
|
var along = b - a;
|
||||||
|
var length = along.Length();
|
||||||
|
if (length < 1e-6f)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var unit = along / length;
|
||||||
|
if (!contour.Closed && cap == LineCap.Square)
|
||||||
|
{
|
||||||
|
if (i == 0)
|
||||||
|
{
|
||||||
|
a -= unit * half;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i == segments - 1)
|
||||||
|
{
|
||||||
|
b += unit * half;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var normal = new Vector2(-unit.Y, unit.X) * half;
|
||||||
|
pieces.Add(Oriented([a + normal, b + normal, b - normal, a - normal]));
|
||||||
|
}
|
||||||
|
|
||||||
|
var joins = contour.Closed ? count : count - 2;
|
||||||
|
var firstJoin = contour.Closed ? 0 : 1;
|
||||||
|
for (var j = 0; j < joins; j++)
|
||||||
|
{
|
||||||
|
pieces.Add(Disc(points[firstJoin + j], half));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!contour.Closed && cap == LineCap.Round)
|
||||||
|
{
|
||||||
|
pieces.Add(Disc(points[0], half));
|
||||||
|
pieces.Add(Disc(points[count - 1], half));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Vector2[] Disc(Vector2 centre, float radius)
|
||||||
|
{
|
||||||
|
var n = PathBuilder.ArcSteps(radius, 360, 0.05f);
|
||||||
|
var result = new Vector2[n];
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
var t = i * 2 * MathF.PI / n;
|
||||||
|
result[i] = centre + new Vector2(radius * MathF.Cos(t), radius * MathF.Sin(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Oriented(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The polygon turning clockwise on screen (positive signed area with y downwards), reversed if needed.</summary>
|
||||||
|
private static Vector2[] Oriented(Vector2[] polygon)
|
||||||
|
{
|
||||||
|
var area = 0f;
|
||||||
|
for (var i = 0; i < polygon.Length; i++)
|
||||||
|
{
|
||||||
|
var p = polygon[i];
|
||||||
|
var q = polygon[(i + 1) % polygon.Length];
|
||||||
|
area += (p.X * q.Y) - (q.X * p.Y);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (area < 0)
|
||||||
|
{
|
||||||
|
Array.Reverse(polygon);
|
||||||
|
}
|
||||||
|
|
||||||
|
return polygon;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The complementary error function, |error| < 1.5e-7 (Abramowitz and Stegun 7.1.26).</summary>
|
||||||
|
private static float Erfc(float x)
|
||||||
|
{
|
||||||
|
var z = MathF.Abs(x);
|
||||||
|
var t = 1 / (1 + (0.3275911f * z));
|
||||||
|
var poly = t * (0.254829592f + (t * (-0.284496736f + (t * (1.421413741f + (t * (-1.453152027f + (t * 1.061405429f))))))));
|
||||||
|
var erfcAbs = poly * MathF.Exp(-z * z);
|
||||||
|
return x >= 0 ? erfcAbs : 2 - erfcAbs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
namespace Febe.Core.Drawing;
|
||||||
|
|
||||||
|
/// <summary>A colour of the drawing code: 8-bit red, green, blue and alpha, not premultiplied.</summary>
|
||||||
|
public readonly record struct Color(byte R, byte G, byte B, byte A = 255)
|
||||||
|
{
|
||||||
|
public static Color Transparent => new(0, 0, 0, 0);
|
||||||
|
|
||||||
|
public static Color White => new(255, 255, 255);
|
||||||
|
|
||||||
|
public static Color Black => new(0, 0, 0);
|
||||||
|
|
||||||
|
/// <summary>An opaque colour from 0xRRGGBB.</summary>
|
||||||
|
public static Color FromRgb(uint rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
|
||||||
|
|
||||||
|
/// <summary>The same colour with another alpha.</summary>
|
||||||
|
public Color WithAlpha(byte alpha) => this with { A = alpha };
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The colour <paramref name="t"/> of the way from this one to <paramref name="other"/> (0 this, 1 the other),
|
||||||
|
/// truncated to whole levels; the alpha of this colour.
|
||||||
|
/// </summary>
|
||||||
|
public Color Mix(Color other, float t) => new(
|
||||||
|
(byte)(R + ((other.R - R) * t)),
|
||||||
|
(byte)(G + ((other.G - G) * t)),
|
||||||
|
(byte)(B + ((other.B - B) * t)),
|
||||||
|
A);
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
using System.Buffers;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Febe.Core.Drawing;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Exact anti-aliased coverage of polygons by signed areas. Every edge adds, in each row it crosses, the area between
|
||||||
|
/// itself and the right side of the row to the cells it touches, as differences between neighbouring cells; the running
|
||||||
|
/// sum of a row is then, for each pixel, the winding of the area it covers, weighted by the fraction covered. The
|
||||||
|
/// coverage of a pixel is that sum, in absolute value, at most 1: the non-zero rule, exact for every pixel that no two
|
||||||
|
/// edges share and very close for the others. Works in a window of the canvas (the shape's bounds), one row of
|
||||||
|
/// differences per row of the window.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class CoverageRasterizer : IDisposable
|
||||||
|
{
|
||||||
|
private float[] _cells = [];
|
||||||
|
private int _stride;
|
||||||
|
|
||||||
|
/// <summary>Left column of the window in the canvas.</summary>
|
||||||
|
public int Left { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Top row of the window in the canvas.</summary>
|
||||||
|
public int Top { get; private set; }
|
||||||
|
|
||||||
|
public int Width { get; private set; }
|
||||||
|
|
||||||
|
public int Height { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Starts a new shape in the window (<paramref name="left"/>, <paramref name="top"/>, width × height).</summary>
|
||||||
|
public void Reset(int left, int top, int width, int height)
|
||||||
|
{
|
||||||
|
Left = left;
|
||||||
|
Top = top;
|
||||||
|
Width = width;
|
||||||
|
Height = height;
|
||||||
|
_stride = width + 2;
|
||||||
|
var length = _stride * height;
|
||||||
|
if (_cells.Length < length)
|
||||||
|
{
|
||||||
|
if (_cells.Length > 0)
|
||||||
|
{
|
||||||
|
ArrayPool<float>.Shared.Return(_cells);
|
||||||
|
}
|
||||||
|
|
||||||
|
_cells = ArrayPool<float>.Shared.Rent(length);
|
||||||
|
}
|
||||||
|
|
||||||
|
_cells.AsSpan(0, length).Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds the edges of a closed polygon (canvas pixels; the last point joins the first).</summary>
|
||||||
|
public void AddPolygon(ReadOnlySpan<Vector2> points)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < points.Length; i++)
|
||||||
|
{
|
||||||
|
AddEdge(points[i], points[(i + 1) % points.Length]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds one edge, in canvas pixels.</summary>
|
||||||
|
public void AddEdge(Vector2 from, Vector2 to)
|
||||||
|
{
|
||||||
|
var x0 = from.X - Left;
|
||||||
|
var y0 = from.Y - Top;
|
||||||
|
var x1 = to.X - Left;
|
||||||
|
var y1 = to.Y - Top;
|
||||||
|
if (y0 == y1 || float.IsNaN(x0) || float.IsNaN(x1) || float.IsNaN(y0) || float.IsNaN(y1))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outside the window on the left an edge covers everything to its right in the window: the same as an edge
|
||||||
|
// on the left border. On the right it covers nothing in the window: the right border. So the parts of the edge
|
||||||
|
// beyond either border are moved onto it.
|
||||||
|
// The direction of the edge is its winding: the pieces keep it.
|
||||||
|
float w = Width;
|
||||||
|
if (x0 >= 0 && x1 >= 0 && x0 <= w && x1 <= w)
|
||||||
|
{
|
||||||
|
Accumulate(x0, y0, x1, y1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (MathF.Max(x0, x1) <= 0 || MathF.Min(x0, x1) >= w)
|
||||||
|
{
|
||||||
|
var border = MathF.Max(x0, x1) <= 0 ? 0 : w;
|
||||||
|
Accumulate(border, y0, border, y1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cut where the edge crosses the borders, in order along the edge.
|
||||||
|
Span<float> cuts = stackalloc float[4];
|
||||||
|
var count = 0;
|
||||||
|
cuts[count++] = 0;
|
||||||
|
foreach (var border in (ReadOnlySpan<float>)[0, w])
|
||||||
|
{
|
||||||
|
var t = (border - x0) / (x1 - x0);
|
||||||
|
if (t > 0 && t < 1)
|
||||||
|
{
|
||||||
|
cuts[count++] = t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cuts[count++] = 1;
|
||||||
|
cuts[1..(count - 1)].Sort();
|
||||||
|
for (var i = 0; i + 1 < count; i++)
|
||||||
|
{
|
||||||
|
var ta = cuts[i];
|
||||||
|
var tb = cuts[i + 1];
|
||||||
|
var ya = y0 + ((y1 - y0) * ta);
|
||||||
|
var yb = y0 + ((y1 - y0) * tb);
|
||||||
|
var xa = x0 + ((x1 - x0) * ta);
|
||||||
|
var xb = x0 + ((x1 - x0) * tb);
|
||||||
|
var middle = (xa + xb) / 2;
|
||||||
|
if (middle <= 0)
|
||||||
|
{
|
||||||
|
Accumulate(0, ya, 0, yb);
|
||||||
|
}
|
||||||
|
else if (middle >= w)
|
||||||
|
{
|
||||||
|
Accumulate(w, ya, w, yb);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Accumulate(Math.Clamp(xa, 0, w), ya, Math.Clamp(xb, 0, w), yb);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The coverage of row <paramref name="y"/> of the window (0-1 for each of its columns).</summary>
|
||||||
|
public void Coverage(int y, Span<float> output)
|
||||||
|
{
|
||||||
|
var row = _cells.AsSpan(y * _stride, Width);
|
||||||
|
var sum = 0f;
|
||||||
|
for (var x = 0; x < row.Length; x++)
|
||||||
|
{
|
||||||
|
sum += row[x];
|
||||||
|
var c = MathF.Abs(sum);
|
||||||
|
output[x] = c > 1 ? 1 : c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (_cells.Length > 0)
|
||||||
|
{
|
||||||
|
ArrayPool<float>.Shared.Return(_cells);
|
||||||
|
_cells = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One edge with 0 ≤ x ≤ Width, the rows outside the window ignored.</summary>
|
||||||
|
private void Accumulate(float x0, float y0, float x1, float y1)
|
||||||
|
{
|
||||||
|
if (y0 == y1)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var direction = 1f;
|
||||||
|
if (y0 > y1)
|
||||||
|
{
|
||||||
|
(x0, y0, x1, y1) = (x1, y1, x0, y0);
|
||||||
|
direction = -1f;
|
||||||
|
}
|
||||||
|
|
||||||
|
var dxdy = (x1 - x0) / (y1 - y0);
|
||||||
|
var x = x0;
|
||||||
|
if (y0 < 0)
|
||||||
|
{
|
||||||
|
x -= y0 * dxdy;
|
||||||
|
y0 = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var end = MathF.Min(y1, Height);
|
||||||
|
if (y0 >= end)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
float w = Width;
|
||||||
|
var cells = _cells;
|
||||||
|
var firstRow = (int)y0;
|
||||||
|
var lastRow = (int)MathF.Ceiling(end);
|
||||||
|
for (var y = firstRow; y < lastRow; y++)
|
||||||
|
{
|
||||||
|
var top = MathF.Max(y, y0);
|
||||||
|
var bottom = MathF.Min(y + 1, end);
|
||||||
|
var dy = bottom - top;
|
||||||
|
var next = x + (dxdy * dy);
|
||||||
|
var d = dy * direction;
|
||||||
|
var left = Math.Clamp(MathF.Min(x, next), 0, w);
|
||||||
|
var right = Math.Clamp(MathF.Max(x, next), 0, w);
|
||||||
|
var row = y * _stride;
|
||||||
|
var leftCell = (int)left;
|
||||||
|
var rightCell = (int)MathF.Ceiling(right);
|
||||||
|
if (rightCell <= leftCell + 1)
|
||||||
|
{
|
||||||
|
// The edge stays inside one cell: the part of the cell right of it, then the full row beyond.
|
||||||
|
var middle = (0.5f * (x + next)) - leftCell;
|
||||||
|
middle = Math.Clamp(middle, 0, 1);
|
||||||
|
cells[row + leftCell] += d - (d * middle);
|
||||||
|
cells[row + leftCell + 1] += d * middle;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Across several cells the covered part grows linearly: a triangle in the first cell, a constant step
|
||||||
|
// in the middle ones, the complement of a triangle in the last one.
|
||||||
|
var s = 1 / (right - left);
|
||||||
|
var leftFraction = left - leftCell;
|
||||||
|
var firstArea = 0.5f * s * (1 - leftFraction) * (1 - leftFraction);
|
||||||
|
var rightFraction = right - (rightCell - 1);
|
||||||
|
var lastGap = 0.5f * s * rightFraction * rightFraction;
|
||||||
|
cells[row + leftCell] += d * firstArea;
|
||||||
|
if (rightCell == leftCell + 2)
|
||||||
|
{
|
||||||
|
cells[row + leftCell + 1] += d * (1 - firstArea - lastGap);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var second = s * (1.5f - leftFraction);
|
||||||
|
cells[row + leftCell + 1] += d * (second - firstArea);
|
||||||
|
for (var cell = leftCell + 2; cell < rightCell - 1; cell++)
|
||||||
|
{
|
||||||
|
cells[row + cell] += d * s;
|
||||||
|
}
|
||||||
|
|
||||||
|
var beforeLast = second + ((rightCell - leftCell - 3) * s);
|
||||||
|
cells[row + rightCell - 1] += d * (1 - beforeLast - lastGap);
|
||||||
|
}
|
||||||
|
|
||||||
|
cells[row + rightCell] += d * lastGap;
|
||||||
|
}
|
||||||
|
|
||||||
|
x = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Febe.Core.Drawing;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An affine transform of the plane: x' = M11·x + M21·y + M31, y' = M12·x + M22·y + M32 (the layout of
|
||||||
|
/// <see cref="Matrix3x2"/>, which does the arithmetic). Transforms compose as with a canvas: the last one applied
|
||||||
|
/// to the canvas acts first on the shapes drawn.
|
||||||
|
/// </summary>
|
||||||
|
public readonly record struct Matrix2D(Matrix3x2 Value)
|
||||||
|
{
|
||||||
|
public static Matrix2D Identity => new(Matrix3x2.Identity);
|
||||||
|
|
||||||
|
public static Matrix2D Translation(float x, float y) => new(Matrix3x2.CreateTranslation(x, y));
|
||||||
|
|
||||||
|
public static Matrix2D Scaling(float x, float y) => new(Matrix3x2.CreateScale(x, y));
|
||||||
|
|
||||||
|
/// <summary>A rotation by <paramref name="degrees"/> around the origin, clockwise on screen (y grows downwards).</summary>
|
||||||
|
public static Matrix2D Rotation(float degrees) => new(Matrix3x2.CreateRotation(degrees * MathF.PI / 180f));
|
||||||
|
|
||||||
|
/// <summary>The transform that applies <paramref name="inner"/> first and then this one.</summary>
|
||||||
|
public Matrix2D Then(Matrix2D inner) => new(inner.Value * Value);
|
||||||
|
|
||||||
|
public Vector2 Apply(Vector2 point) => Vector2.Transform(point, Value);
|
||||||
|
|
||||||
|
/// <summary>How much the transform enlarges lengths, on average (the square root of the area scale).</summary>
|
||||||
|
public float LengthScale => MathF.Sqrt(MathF.Abs(Value.GetDeterminant()));
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Febe.Core.Drawing;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The outline of a shape: contours of straight lines, quadratic and cubic Bézier curves and elliptic arcs. Angles are
|
||||||
|
/// in degrees, measured from the positive x axis towards the positive y axis (clockwise on screen, where y grows
|
||||||
|
/// downwards). A filled path covers the points of non-zero winding; contours drawn the other way round cut holes.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class PathBuilder
|
||||||
|
{
|
||||||
|
private readonly List<Command> _commands = [];
|
||||||
|
|
||||||
|
private enum Kind
|
||||||
|
{
|
||||||
|
Move,
|
||||||
|
Line,
|
||||||
|
Quad,
|
||||||
|
Cubic,
|
||||||
|
Arc,
|
||||||
|
Close,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether nothing was added.</summary>
|
||||||
|
public bool IsEmpty => _commands.Count == 0;
|
||||||
|
|
||||||
|
/// <summary>Starts a new contour at (<paramref name="x"/>, <paramref name="y"/>).</summary>
|
||||||
|
public PathBuilder MoveTo(float x, float y)
|
||||||
|
{
|
||||||
|
_commands.Add(new Command(Kind.Move, new Vector2(x, y)));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A straight line to (<paramref name="x"/>, <paramref name="y"/>).</summary>
|
||||||
|
public PathBuilder LineTo(float x, float y)
|
||||||
|
{
|
||||||
|
_commands.Add(new Command(Kind.Line, new Vector2(x, y)));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A quadratic Bézier curve through the control point (cx, cy) to (x, y).</summary>
|
||||||
|
public PathBuilder QuadTo(float cx, float cy, float x, float y)
|
||||||
|
{
|
||||||
|
_commands.Add(new Command(Kind.Quad, new Vector2(cx, cy), new Vector2(x, y)));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A cubic Bézier curve through the control points (c1x, c1y) and (c2x, c2y) to (x, y).</summary>
|
||||||
|
public PathBuilder CubicTo(float c1x, float c1y, float c2x, float c2y, float x, float y)
|
||||||
|
{
|
||||||
|
_commands.Add(new Command(Kind.Cubic, new Vector2(c1x, c1y), new Vector2(c2x, c2y), new Vector2(x, y)));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A new contour along the ellipse inscribed in the rectangle (<paramref name="left"/>, <paramref name="top"/>)–
|
||||||
|
/// (<paramref name="right"/>, <paramref name="bottom"/>), from <paramref name="startDegrees"/> for
|
||||||
|
/// <paramref name="sweepDegrees"/> (negative: the other way round).
|
||||||
|
/// </summary>
|
||||||
|
public PathBuilder AddArc(float left, float top, float right, float bottom, float startDegrees, float sweepDegrees)
|
||||||
|
{
|
||||||
|
var centre = new Vector2((left + right) / 2, (top + bottom) / 2);
|
||||||
|
_commands.Add(new Command(Kind.Arc, centre, new Vector2((right - left) / 2, (bottom - top) / 2), new Vector2(startDegrees, sweepDegrees)));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Closes the current contour with a straight line back to its start.</summary>
|
||||||
|
public PathBuilder Close()
|
||||||
|
{
|
||||||
|
_commands.Add(new Command(Kind.Close, default));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A closed ellipse centred on (cx, cy), clockwise on screen (or the other way round).</summary>
|
||||||
|
public PathBuilder AddEllipse(float cx, float cy, float rx, float ry, bool clockwise = true)
|
||||||
|
{
|
||||||
|
_commands.Add(new Command(Kind.Arc, new Vector2(cx, cy), new Vector2(rx, ry), new Vector2(0, clockwise ? 360 : -360)));
|
||||||
|
return Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A closed circle.</summary>
|
||||||
|
public PathBuilder AddCircle(float cx, float cy, float r, bool clockwise = true) => AddEllipse(cx, cy, r, r, clockwise);
|
||||||
|
|
||||||
|
/// <summary>A closed rectangle, clockwise on screen (or the other way round).</summary>
|
||||||
|
public PathBuilder AddRect(float x, float y, float width, float height, bool clockwise = true)
|
||||||
|
{
|
||||||
|
if (clockwise)
|
||||||
|
{
|
||||||
|
MoveTo(x, y).LineTo(x + width, y).LineTo(x + width, y + height).LineTo(x, y + height);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
MoveTo(x, y).LineTo(x, y + height).LineTo(x + width, y + height).LineTo(x + width, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A closed rectangle with corners rounded to quarter circles of <paramref name="radius"/>.</summary>
|
||||||
|
public PathBuilder AddRoundRect(float x, float y, float width, float height, float radius)
|
||||||
|
{
|
||||||
|
var r = Math.Clamp(radius, 0, Math.Min(Math.Abs(width), Math.Abs(height)) / 2);
|
||||||
|
if (r <= 0)
|
||||||
|
{
|
||||||
|
return AddRect(x, y, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
var right = x + width;
|
||||||
|
var bottom = y + height;
|
||||||
|
MoveTo(x + r, y);
|
||||||
|
LineTo(right - r, y);
|
||||||
|
ArcSegment(right - r, y + r, r, 270, 90);
|
||||||
|
LineTo(right, bottom - r);
|
||||||
|
ArcSegment(right - r, bottom - r, r, 0, 90);
|
||||||
|
LineTo(x + r, bottom);
|
||||||
|
ArcSegment(x + r, bottom - r, r, 90, 90);
|
||||||
|
LineTo(x, y + r);
|
||||||
|
ArcSegment(x + r, y + r, r, 180, 90);
|
||||||
|
return Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A closed polygon through <paramref name="points"/> (x0, y0, x1, y1, ...).</summary>
|
||||||
|
public PathBuilder AddPolygon(ReadOnlySpan<float> points)
|
||||||
|
{
|
||||||
|
if (points.Length < 6 || points.Length % 2 != 0)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("A polygon needs at least three points, two numbers each.", nameof(points));
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveTo(points[0], points[1]);
|
||||||
|
for (var i = 2; i < points.Length; i += 2)
|
||||||
|
{
|
||||||
|
LineTo(points[i], points[i + 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The contours as polylines in canvas pixels, the curves divided finely enough that no chord strays more than
|
||||||
|
/// <paramref name="tolerance"/> pixels from the curve. Chords fall inside a convex curve, so a circle loses about
|
||||||
|
/// 4·tolerance / (3·radius) of its area: 0.01 keeps that near half a percent down to a radius of 2.5 pixels.
|
||||||
|
/// </summary>
|
||||||
|
internal List<Polyline> Flatten(Matrix2D transform, float tolerance = 0.01f)
|
||||||
|
{
|
||||||
|
var result = new List<Polyline>();
|
||||||
|
var scale = Math.Max(transform.LengthScale, 1e-6f);
|
||||||
|
List<Vector2>? points = null;
|
||||||
|
var start = Vector2.Zero;
|
||||||
|
var current = Vector2.Zero;
|
||||||
|
|
||||||
|
void Finish(bool closed)
|
||||||
|
{
|
||||||
|
if (points is { Count: >= 2 })
|
||||||
|
{
|
||||||
|
result.Add(new Polyline([.. points], closed));
|
||||||
|
}
|
||||||
|
|
||||||
|
points = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Add(Vector2 user)
|
||||||
|
{
|
||||||
|
points ??= [transform.Apply(current)];
|
||||||
|
points.Add(transform.Apply(user));
|
||||||
|
current = user;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var c in _commands)
|
||||||
|
{
|
||||||
|
switch (c.Kind)
|
||||||
|
{
|
||||||
|
case Kind.Move:
|
||||||
|
Finish(closed: false);
|
||||||
|
start = current = c.A;
|
||||||
|
points = [transform.Apply(c.A)];
|
||||||
|
break;
|
||||||
|
case Kind.Line:
|
||||||
|
Add(c.A);
|
||||||
|
break;
|
||||||
|
case Kind.Quad:
|
||||||
|
{
|
||||||
|
var p0 = current;
|
||||||
|
var n = CurveSteps(Vector2.Distance(p0, c.A) + Vector2.Distance(c.A, c.B), scale, tolerance);
|
||||||
|
for (var i = 1; i <= n; i++)
|
||||||
|
{
|
||||||
|
var t = i / (float)n;
|
||||||
|
var u = 1 - t;
|
||||||
|
Add((u * u * p0) + (2 * u * t * c.A) + (t * t * c.B));
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Kind.Cubic:
|
||||||
|
{
|
||||||
|
var p0 = current;
|
||||||
|
var n = CurveSteps(Vector2.Distance(p0, c.A) + Vector2.Distance(c.A, c.B) + Vector2.Distance(c.B, c.C), scale, tolerance);
|
||||||
|
for (var i = 1; i <= n; i++)
|
||||||
|
{
|
||||||
|
var t = i / (float)n;
|
||||||
|
var u = 1 - t;
|
||||||
|
Add((u * u * u * p0) + (3 * u * u * t * c.A) + (3 * u * t * t * c.B) + (t * t * t * c.C));
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Kind.Arc:
|
||||||
|
{
|
||||||
|
var (centre, radii, startDegrees, sweepDegrees) = (c.A, c.B, c.C.X, c.C.Y);
|
||||||
|
var first = centre + Ellipse(radii, startDegrees);
|
||||||
|
if (!c.Continues)
|
||||||
|
{
|
||||||
|
Finish(closed: false);
|
||||||
|
start = current = first;
|
||||||
|
points = [transform.Apply(first)];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Add(first);
|
||||||
|
}
|
||||||
|
|
||||||
|
var n = ArcSteps(Math.Max(Math.Abs(radii.X), Math.Abs(radii.Y)) * scale, sweepDegrees, tolerance);
|
||||||
|
for (var i = 1; i <= n; i++)
|
||||||
|
{
|
||||||
|
Add(centre + Ellipse(radii, startDegrees + (sweepDegrees * i / n)));
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Kind.Close:
|
||||||
|
Finish(closed: true);
|
||||||
|
current = start;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Finish(closed: false);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An arc that continues the current contour (used by the rounded rectangle).</summary>
|
||||||
|
private void ArcSegment(float cx, float cy, float r, float startDegrees, float sweepDegrees) =>
|
||||||
|
_commands.Add(new Command(Kind.Arc, new Vector2(cx, cy), new Vector2(r, r), new Vector2(startDegrees, sweepDegrees)) { Continues = true });
|
||||||
|
|
||||||
|
private static Vector2 Ellipse(Vector2 radii, float degrees)
|
||||||
|
{
|
||||||
|
var t = degrees * MathF.PI / 180f;
|
||||||
|
return new Vector2(radii.X * MathF.Cos(t), radii.Y * MathF.Sin(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int CurveSteps(float controlLength, float scale, float tolerance)
|
||||||
|
{
|
||||||
|
var pixels = controlLength * scale;
|
||||||
|
return Math.Clamp((int)MathF.Ceiling(MathF.Sqrt(pixels / (8 * tolerance))), 1, 1024);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Chords of an arc of radius <paramref name="radiusPixels"/>, each with a sagitta of at most the tolerance.</summary>
|
||||||
|
internal static int ArcSteps(float radiusPixels, float sweepDegrees, float tolerance)
|
||||||
|
{
|
||||||
|
var sweep = MathF.Abs(sweepDegrees) * MathF.PI / 180f;
|
||||||
|
var maxStep = radiusPixels <= tolerance ? MathF.PI / 2 : 2 * MathF.Acos(1 - (tolerance / radiusPixels));
|
||||||
|
return Math.Clamp((int)MathF.Ceiling(sweep / Math.Max(maxStep, 1e-4f)), 2, 4096);
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly record struct Command(Kind Kind, Vector2 A, Vector2 B = default, Vector2 C = default)
|
||||||
|
{
|
||||||
|
public bool Continues { get; init; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A flattened contour in canvas pixels.</summary>
|
||||||
|
internal readonly record struct Polyline(Vector2[] Points, bool Closed);
|
||||||
@@ -1,9 +1,6 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<!-- Dominio e logica: motore, Governatore, interruttore, ricette, lettori, libreria, importazione.
|
<!-- Dominio e logica: motore, Governatore, interruttore, ricette, lettori, libreria, importazione.
|
||||||
Nessun riferimento a interfaccia o piattaforma: Data e Browser implementano le interfacce definite qui. -->
|
Nessun riferimento a interfaccia o piattaforma: Data e Browser implementano le interfacce definite qui. -->
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="SkiaSharp" />
|
|
||||||
</ItemGroup>
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<!-- File di configurazione per sito (specifica §6.3, §7.6): una copia incorporata come valore predefinito
|
<!-- File di configurazione per sito (specifica §6.3, §7.6): una copia incorporata come valore predefinito
|
||||||
e una copia accanto all'eseguibile, in config/, modificabile senza ricompilare. -->
|
e una copia accanto all'eseguibile, in config/, modificabile senza ricompilare. -->
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ internal static class ContentAnalysis
|
|||||||
|
|
||||||
sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
|
sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||||
ct.ThrowIfCancellationRequested();
|
ct.ThrowIfCancellationRequested();
|
||||||
(width, height, hash) = Decode(() => new MemoryStream(bytes, writable: false));
|
(width, height, hash) = Decode(bytes);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -80,25 +80,47 @@ internal static class ContentAnalysis
|
|||||||
return new ContentFacts(type, length, sha, width, height, null, hash, date, null);
|
return new ContentFacts(type, length, sha, width, height, null, hash, date, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. HEIC).</summary>
|
||||||
|
private static (int? Width, int? Height, ulong? Hash) Decode(byte[] bytes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// The bytes are already in memory: one decode of them gives hash and size, with no copy.
|
||||||
|
var (hash, size) = PerceptualHash.ComputeWithSize(bytes);
|
||||||
|
return (size?.Width, size?.Height, hash);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
|
||||||
|
{
|
||||||
|
return (null, null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The same for a photo over <see cref="InMemoryLimit"/>, which the analysis does not keep for the copy: it is read once
|
||||||
|
/// more, whole (up to <see cref="ImageDecoding.MaxFileBytes"/>; the codecs need the bytes in memory), and decoded
|
||||||
|
/// once for both hash and size.
|
||||||
|
/// </summary>
|
||||||
private static (int? Width, int? Height, ulong? Hash) Decode(Func<Stream> open)
|
private static (int? Width, int? Height, ulong? Hash) Decode(Func<Stream> open)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
int? width = null, height = null;
|
byte[]? data;
|
||||||
using (var stream = open())
|
using (var stream = open())
|
||||||
{
|
{
|
||||||
if (ImageDecoding.ReadSize(stream) is { } size)
|
data = ImageDecoding.ReadAll(stream);
|
||||||
{
|
|
||||||
(width, height) = size;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
using var again = open();
|
if (data is null)
|
||||||
return (width, height, PerceptualHash.Compute(again));
|
{
|
||||||
|
return (null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (hash, size) = PerceptualHash.ComputeWithSize(data);
|
||||||
|
return (size?.Width, size?.Height, hash);
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OutOfMemoryException)
|
catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
|
||||||
{
|
{
|
||||||
return (null, null, null); // a format SkiaSharp cannot decode (e.g. HEIC): no size, no hash
|
return (null, null, null); // formats Febe cannot decode (e.g. HEIC) already give nulls: no size, no hash
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -517,11 +517,11 @@ public sealed class ImportCopier(ImportEnvironment env)
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
hash = PerceptualHash.ComputeFromFile(saved.FullPath);
|
// One read of the file gives both the perceptual hash and the size as shown.
|
||||||
await using var stream = File.OpenRead(saved.FullPath);
|
(hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath);
|
||||||
if (ImageDecoding.ReadSize(stream) is { } size)
|
if (size is { } shown)
|
||||||
{
|
{
|
||||||
(width, height) = size;
|
(width, height) = shown;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
|||||||
@@ -1,34 +1,20 @@
|
|||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
using SkiaSharp;
|
|
||||||
|
|
||||||
namespace Febe.Core.Import;
|
namespace Febe.Core.Import;
|
||||||
|
|
||||||
/// <summary>In-memory previews of source photos for the comparison panel (nothing is written to disk).</summary>
|
/// <summary>In-memory previews of source photos for the comparison panel (nothing is written to disk).</summary>
|
||||||
internal static class ImportPreview
|
internal static class ImportPreview
|
||||||
{
|
{
|
||||||
private const int JpegQuality = 82;
|
|
||||||
|
|
||||||
/// <summary>A JPEG of the image, upright, at most <paramref name="longSide"/> pixels; null when it cannot be decoded.</summary>
|
/// <summary>A JPEG of the image, upright, at most <paramref name="longSide"/> pixels; null when it cannot be decoded.</summary>
|
||||||
public static byte[]? RenderJpeg(Stream encodedImage, int longSide)
|
public static byte[]? RenderJpeg(Stream encodedImage, int longSide)
|
||||||
{
|
{
|
||||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, longSide);
|
using var image = ThumbnailStore.DecodeFor(encodedImage, longSide);
|
||||||
if (bitmap is null)
|
if (image is null)
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var scale = Math.Min(1.0, (double)longSide / Math.Max(bitmap.Width, bitmap.Height));
|
using var small = ThumbnailStore.Render(image, longSide);
|
||||||
var width = Math.Max(1, (int)Math.Round(bitmap.Width * scale));
|
return ThumbnailStore.Jpeg(small);
|
||||||
var height = Math.Max(1, (int)Math.Round(bitmap.Height * scale));
|
|
||||||
using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
|
||||||
surface.Canvas.Clear(SKColors.White);
|
|
||||||
using (var image = SKImage.FromBitmap(bitmap))
|
|
||||||
{
|
|
||||||
surface.Canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
|
|
||||||
}
|
|
||||||
|
|
||||||
using var snapshot = surface.Snapshot();
|
|
||||||
using var data = snapshot.Encode(SKEncodedImageFormat.Jpeg, JpegQuality);
|
|
||||||
return data?.ToArray();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -159,7 +159,7 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per
|
|||||||
|
|
||||||
## Limiti noti
|
## Limiti noti
|
||||||
|
|
||||||
- HEIC/HEIF: si riconoscono, ma SkiaSharp (pacchetto Linux senza dipendenze) non li decodifica: niente dimensioni,
|
- HEIC/HEIF: si riconoscono, ma i codec di Febe (PNG, JPEG, GIF, BMP, WebP) non li decodificano: niente dimensioni,
|
||||||
impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica.
|
impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica.
|
||||||
- La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella
|
- La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella
|
||||||
scrivibile per il sistema ma non per Febe non si riconosce; lì «Sposta» lascia l'originale e lo dice.
|
scrivibile per il sistema ma non per Febe non si riconosce; lì «Sposta» lascia l'originale e lo dice.
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
namespace Febe.Core.Library;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «File danneggiato o incompleto» (spec §4.6, §8.4; Alberto's answer of 25 November 2026): a photo truncated or
|
||||||
|
/// damaged, downloaded or imported, is refused and said so. It has no thumbnail (the neutral tile) and no perceptual
|
||||||
|
/// hash, so it is never a probable duplicate; its SHA-256 still counts. The file stays in the library (rule 12): this
|
||||||
|
/// class only looks, it never deletes, replaces or downloads again.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// The check decodes the picture, so it is meant for a single file at a time (the viewer) and only for photos that
|
||||||
|
/// have no thumbnail: a photo with a thumbnail was decoded when it was stored.
|
||||||
|
/// </remarks>
|
||||||
|
public static class DamagedImage
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// True when the bytes are a photo in a format Febe reads that cannot be decoded because it is damaged or
|
||||||
|
/// truncated; false for a photo that decodes, for a format Febe does not read (HEIC, an unknown one) and for a
|
||||||
|
/// picture too large to decode.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsDamaged(ReadOnlyMemory<byte> data) => ImageDecoding.IsDamaged(data);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <see cref="IsDamaged(ReadOnlyMemory{byte})"/> for a file on disk, read once; false when it cannot be read or is
|
||||||
|
/// larger than <see cref="ImageDecoding.MaxFileBytes"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsFileDamaged(string path)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrEmpty(path);
|
||||||
|
byte[]? data;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||||
|
data = ImageDecoding.ReadAll(stream);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return data is not null && ImageDecoding.IsDamaged(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
using SkiaSharp;
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
namespace Febe.Core.Library;
|
namespace Febe.Core.Library;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Decodes images with SkiaSharp, applying the EXIF orientation (photos from phones) and, when the codec allows it,
|
/// Decodes images with the in-house codecs (<see cref="ImageDecoder"/>: JPEG, PNG, GIF, BMP, WebP), applying the
|
||||||
/// decoding directly at a reduced size to save memory and time.
|
/// EXIF orientation (photos from phones) and, for JPEG, decoding directly at a reduced size when a smaller picture is
|
||||||
|
/// enough, which saves memory and time.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal static class ImageDecoding
|
internal static class ImageDecoding
|
||||||
{
|
{
|
||||||
@@ -14,118 +15,203 @@ internal static class ImageDecoding
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public const long MaxDecodedPixels = 100_000_000;
|
public const long MaxDecodedPixels = 100_000_000;
|
||||||
|
|
||||||
|
/// <summary>Files larger than this are not read into memory to be decoded (no picture Febe keeps comes near it).</summary>
|
||||||
|
public const long MaxFileBytes = 512L * 1024 * 1024;
|
||||||
|
|
||||||
|
private static readonly ImageLimits Limits = ImageLimits.Default with { MaxPixels = MaxDecodedPixels };
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Decodes an image upright, as premultiplied RGBA. When <paramref name="minLongSide"/> is given the codec may
|
/// Decodes an image upright, as straight RGBA. When <paramref name="minLongSide"/> is given the codec may decode
|
||||||
/// decode at a lower resolution, but never below that long side (unless the image is smaller).
|
/// at a lower resolution, but never below that long side (unless the image is smaller). Returns null when the
|
||||||
/// Returns null when the content is not a decodable image.
|
/// content is not a decodable image (unknown format, HEIC, damaged or truncated file, too large).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static SKBitmap? DecodeUpright(Stream stream, int? minLongSide = null)
|
public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(stream);
|
ArgumentNullException.ThrowIfNull(stream);
|
||||||
using var data = SKData.Create(stream);
|
return ReadAll(stream) is { } data ? DecodeUpright(data, minLongSide) : null;
|
||||||
if (data is null || data.IsEmpty)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
using var codec = SKCodec.Create(data);
|
|
||||||
if (codec is null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var size = ChooseDecodeSize(codec, minLongSide);
|
|
||||||
if ((long)size.Width * size.Height > MaxDecodedPixels || size.Width <= 0 || size.Height <= 0)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var info = new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul);
|
|
||||||
var decoded = new SKBitmap(info);
|
|
||||||
var result = codec.GetPixels(info, decoded.GetPixels());
|
|
||||||
if (result is not (SKCodecResult.Success or SKCodecResult.IncompleteInput))
|
|
||||||
{
|
|
||||||
decoded.Dispose();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return Orient(decoded, codec.EncodedOrigin);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Like <see cref="DecodeUpright(Stream, int?)"/>, from bytes already in memory.</summary>
|
||||||
|
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide = null) => DecodeUpright(data, minLongSide, out _);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Like <see cref="DecodeUpright(ReadOnlyMemory{byte}, int?)"/>, and also gives what <see cref="ReadSize(ReadOnlyMemory{byte})"/>
|
||||||
|
/// would (the full size as shown, even when the picture comes back reduced or not at all), from the same bytes.
|
||||||
|
/// </summary>
|
||||||
|
public static RgbaImage? DecodeUpright(ReadOnlyMemory<byte> data, int? minLongSide, out (int Width, int Height)? shownSize)
|
||||||
|
{
|
||||||
|
shownSize = null;
|
||||||
|
if (data.IsEmpty)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
RgbaImage? stored = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ImageInfo info;
|
||||||
|
stored = minLongSide is { } min && min > 0
|
||||||
|
? ImageDecoder.DecodeAtLeast(data, min, out info, Limits, pooled: true)
|
||||||
|
: ImageDecoder.Decode(data, out info, Limits, pooled: true);
|
||||||
|
shownSize = ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
|
||||||
|
var upright = ImageOrientation.Apply(stored, info.Metadata.Orientation, pooled: true);
|
||||||
|
if (!ReferenceEquals(upright, stored))
|
||||||
|
{
|
||||||
|
stored.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
stored = null;
|
||||||
|
return upright;
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
// A damaged, truncated or too large picture can still tell its size from its headers.
|
||||||
|
shownSize ??= ReadSize(data);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
stored?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True when <paramref name="data"/> is in a format Febe decodes but cannot be decoded because it is damaged or
|
||||||
|
/// truncated (spec §8.4, «File danneggiato o incompleto»). False for a picture that decodes, for what Febe does not
|
||||||
|
/// read (unknown formats, HEIC, the JPEG processes it leaves out) and for a picture over the limits: those are not
|
||||||
|
/// damaged, Febe just has no picture of them.
|
||||||
|
/// </summary>
|
||||||
|
internal static bool IsDamaged(ReadOnlyMemory<byte> data)
|
||||||
|
{
|
||||||
|
if (data.IsEmpty || !ImageDecoder.CanDecode(ImageFormatSniffer.Detect(data.Span)))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// A reduced JPEG decode still reads every scan to its end, so it finds a cut as the full decode does.
|
||||||
|
using var image = ImageDecoder.DecodeAtLeast(data, DamageCheckSide, out _, Limits, pooled: true);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (ImageLimitException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (ImageFormatNotSupportedException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The smallest long side <see cref="IsDamaged"/> lets a JPEG be decoded at: the cheapest reduction.</summary>
|
||||||
|
private const int DamageCheckSide = 1;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Bytes read first by <see cref="ReadSize(Stream)"/> for JPEG, GIF and BMP, whose headers (a JPEG EXIF block is
|
||||||
|
/// at most 64 KiB) fit; when they do not (large ICC profiles) the rest of the file is read as well. PNG and WebP
|
||||||
|
/// are always read whole.
|
||||||
|
/// </summary>
|
||||||
|
internal const int HeaderBytes = 256 * 1024;
|
||||||
|
|
||||||
/// <summary>Dimensions of an image as displayed (orientation applied), without decoding the pixels.</summary>
|
/// <summary>Dimensions of an image as displayed (orientation applied), without decoding the pixels.</summary>
|
||||||
public static (int Width, int Height)? ReadSize(Stream stream)
|
public static (int Width, int Height)? ReadSize(Stream stream)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(stream);
|
ArgumentNullException.ThrowIfNull(stream);
|
||||||
using var codec = SKCodec.Create(stream);
|
if (!stream.CanSeek)
|
||||||
if (codec is null)
|
{
|
||||||
|
return ReadAll(stream) is { } all ? ReadSize(all) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var remaining = stream.Length - stream.Position;
|
||||||
|
if (remaining <= 0 || remaining > MaxFileBytes)
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var (w, h) = (codec.Info.Width, codec.Info.Height);
|
if (remaining <= HeaderBytes)
|
||||||
return SwapsAxes(codec.EncodedOrigin) ? (h, w) : (w, h);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static SKSizeI ChooseDecodeSize(SKCodec codec, int? minLongSide)
|
|
||||||
{
|
|
||||||
var full = new SKSizeI(codec.Info.Width, codec.Info.Height);
|
|
||||||
if (minLongSide is not { } min || Math.Max(full.Width, full.Height) <= min)
|
|
||||||
{
|
{
|
||||||
return full;
|
return ReadSize(ReadAll(stream));
|
||||||
}
|
}
|
||||||
|
|
||||||
var best = full;
|
var data = new byte[HeaderBytes];
|
||||||
foreach (var scale in new[] { 0.5f, 0.25f, 0.125f })
|
stream.ReadExactly(data);
|
||||||
|
if (ImageFormatSniffer.Detect(data) is not (ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp))
|
||||||
{
|
{
|
||||||
var scaled = codec.GetScaledDimensions(scale);
|
// PNG keeps metadata (eXIf) anywhere before IEND and checks every chunk, WebP refuses a RIFF that runs
|
||||||
if (scaled.Width <= 0 || scaled.Height <= 0 || Math.Max(scaled.Width, scaled.Height) < min)
|
// past the data: neither can be identified from a prefix.
|
||||||
|
Array.Resize(ref data, (int)remaining);
|
||||||
|
stream.ReadExactly(data.AsSpan(HeaderBytes));
|
||||||
|
return ReadSize(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var info = ImageDecoder.Identify(data, Limits);
|
||||||
|
return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
// The headers go on past the prefix (or the file is damaged): read the rest and look again.
|
||||||
|
}
|
||||||
|
|
||||||
|
Array.Resize(ref data, (int)remaining);
|
||||||
|
stream.ReadExactly(data.AsSpan(HeaderBytes));
|
||||||
|
return ReadSize(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Like <see cref="ReadSize(Stream)"/>, from bytes already in memory.</summary>
|
||||||
|
public static (int Width, int Height)? ReadSize(ReadOnlyMemory<byte> data)
|
||||||
|
{
|
||||||
|
if (data.IsEmpty)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var info = ImageDecoder.Identify(data, Limits);
|
||||||
|
return ImageOrientation.ShownSize(info.Width, info.Height, info.Metadata.Orientation);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The rest of <paramref name="stream"/>, or null when it is empty or over <see cref="MaxFileBytes"/>.</summary>
|
||||||
|
internal static byte[]? ReadAll(Stream stream)
|
||||||
|
{
|
||||||
|
if (stream.CanSeek)
|
||||||
|
{
|
||||||
|
var remaining = stream.Length - stream.Position;
|
||||||
|
if (remaining <= 0 || remaining > MaxFileBytes)
|
||||||
{
|
{
|
||||||
break;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
best = scaled;
|
var bytes = new byte[remaining];
|
||||||
|
stream.ReadExactly(bytes);
|
||||||
|
return bytes;
|
||||||
}
|
}
|
||||||
|
|
||||||
return best;
|
using var copy = new MemoryStream();
|
||||||
}
|
var buffer = new byte[81920];
|
||||||
|
int read;
|
||||||
private static bool SwapsAxes(SKEncodedOrigin origin) =>
|
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
|
||||||
origin is SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightTop or SKEncodedOrigin.RightBottom or SKEncodedOrigin.LeftBottom;
|
|
||||||
|
|
||||||
private static SKBitmap Orient(SKBitmap source, SKEncodedOrigin origin)
|
|
||||||
{
|
|
||||||
if (origin is SKEncodedOrigin.TopLeft or SKEncodedOrigin.Default)
|
|
||||||
{
|
{
|
||||||
return source;
|
if (copy.Length + read > MaxFileBytes)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
copy.Write(buffer, 0, read);
|
||||||
}
|
}
|
||||||
|
|
||||||
float w = source.Width, h = source.Height;
|
return copy.Length == 0 ? null : copy.ToArray();
|
||||||
var swap = SwapsAxes(origin);
|
|
||||||
var outW = swap ? source.Height : source.Width;
|
|
||||||
var outH = swap ? source.Width : source.Height;
|
|
||||||
|
|
||||||
// Each matrix maps a source pixel (x, y) to its upright position.
|
|
||||||
var matrix = origin switch
|
|
||||||
{
|
|
||||||
SKEncodedOrigin.TopRight => new SKMatrix(-1, 0, w, 0, 1, 0, 0, 0, 1),
|
|
||||||
SKEncodedOrigin.BottomRight => new SKMatrix(-1, 0, w, 0, -1, h, 0, 0, 1),
|
|
||||||
SKEncodedOrigin.BottomLeft => new SKMatrix(1, 0, 0, 0, -1, h, 0, 0, 1),
|
|
||||||
SKEncodedOrigin.LeftTop => new SKMatrix(0, 1, 0, 1, 0, 0, 0, 0, 1),
|
|
||||||
SKEncodedOrigin.RightTop => new SKMatrix(0, -1, h, 1, 0, 0, 0, 0, 1),
|
|
||||||
SKEncodedOrigin.RightBottom => new SKMatrix(0, -1, h, -1, 0, w, 0, 0, 1),
|
|
||||||
SKEncodedOrigin.LeftBottom => new SKMatrix(0, 1, 0, -1, 0, w, 0, 0, 1),
|
|
||||||
_ => SKMatrix.Identity,
|
|
||||||
};
|
|
||||||
|
|
||||||
var upright = new SKBitmap(new SKImageInfo(outW, outH, SKColorType.Rgba8888, SKAlphaType.Premul));
|
|
||||||
using (var canvas = new SKCanvas(upright))
|
|
||||||
{
|
|
||||||
canvas.Clear(SKColors.Transparent);
|
|
||||||
canvas.SetMatrix(in matrix);
|
|
||||||
canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
|
|
||||||
}
|
|
||||||
|
|
||||||
source.Dispose();
|
|
||||||
return upright;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -278,11 +278,11 @@ public sealed class LibraryIngest(
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
hash = PerceptualHash.ComputeFromFile(saved.FullPath);
|
// One read of the file gives both the perceptual hash and the size as shown.
|
||||||
await using var stream = File.OpenRead(saved.FullPath);
|
(hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath);
|
||||||
if (ImageDecoding.ReadSize(stream) is { } size)
|
if (size is { } shown)
|
||||||
{
|
{
|
||||||
(width, height) = size;
|
(width, height) = shown;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
|||||||
@@ -445,13 +445,11 @@ public sealed class LibraryRebuilder(
|
|||||||
{
|
{
|
||||||
if (!isVideo)
|
if (!isVideo)
|
||||||
{
|
{
|
||||||
phash = PerceptualHash.ComputeFromFile(path);
|
// One read of the file gives both the perceptual hash and the size as shown.
|
||||||
await using (var stream = File.OpenRead(path))
|
(phash, var size) = PerceptualHash.ComputeWithSizeFromFile(path);
|
||||||
|
if (size is { } shown)
|
||||||
{
|
{
|
||||||
if (ImageDecoding.ReadSize(stream) is { } size)
|
(width, height) = shown;
|
||||||
{
|
|
||||||
(width, height) = size;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
using SkiaSharp;
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
namespace Febe.Core.Library;
|
namespace Febe.Core.Library;
|
||||||
|
|
||||||
@@ -38,6 +38,9 @@ public static class PerceptualHash
|
|||||||
private const int Size = 32;
|
private const int Size = 32;
|
||||||
private const int Low = 8;
|
private const int Low = 8;
|
||||||
|
|
||||||
|
/// <summary>A JPEG is decoded reduced, but never below this long side.</summary>
|
||||||
|
private const int MinDecodedSide = 256;
|
||||||
|
|
||||||
private static readonly double[,] Cosines = BuildCosines();
|
private static readonly double[,] Cosines = BuildCosines();
|
||||||
|
|
||||||
/// <summary>Hamming distance between two hashes (0–64).</summary>
|
/// <summary>Hamming distance between two hashes (0–64).</summary>
|
||||||
@@ -50,8 +53,8 @@ public static class PerceptualHash
|
|||||||
public static ulong? Compute(Stream encodedImage)
|
public static ulong? Compute(Stream encodedImage)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(encodedImage);
|
ArgumentNullException.ThrowIfNull(encodedImage);
|
||||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256);
|
using var image = ImageDecoding.DecodeUpright(encodedImage, minLongSide: MinDecodedSide);
|
||||||
return bitmap is null ? null : Compute(bitmap);
|
return image is null ? null : Compute(image);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
|
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
|
||||||
@@ -61,17 +64,33 @@ public static class PerceptualHash
|
|||||||
return Compute(stream);
|
return Compute(stream);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible).</summary>
|
/// <summary>
|
||||||
internal static ulong Compute(SKBitmap bitmap)
|
/// Hash and size as shown of an encoded image from one decode of the same bytes; each null when it cannot be had
|
||||||
|
/// (a damaged file may still give its size).
|
||||||
|
/// </summary>
|
||||||
|
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSize(ReadOnlyMemory<byte> encodedImage)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(bitmap);
|
using var image = ImageDecoding.DecodeUpright(encodedImage, MinDecodedSide, out var size);
|
||||||
using var rgba = bitmap.ColorType == SKColorType.Rgba8888 && bitmap.AlphaType == SKAlphaType.Premul
|
return (image is null ? null : Compute(image), size);
|
||||||
? null
|
}
|
||||||
: bitmap.Copy(SKColorType.Rgba8888);
|
|
||||||
var source = rgba ?? bitmap;
|
/// <summary>Like <see cref="ComputeWithSize(ReadOnlyMemory{byte})"/> for a file, read once.</summary>
|
||||||
var grey = Luminance(source);
|
internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSizeFromFile(string path)
|
||||||
var small = AreaResample(grey, source.Width, source.Height, Size, Size);
|
{
|
||||||
return HashOf(small);
|
byte[]? data;
|
||||||
|
using (var stream = File.OpenRead(path))
|
||||||
|
{
|
||||||
|
data = ImageDecoding.ReadAll(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data is null ? (null, null) : ComputeWithSize(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Hash of a decoded image (any size), upright as it is shown.</summary>
|
||||||
|
internal static ulong Compute(RgbaImage image)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(image);
|
||||||
|
return HashOf(AreaResample(image, Size, Size));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
|
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
|
||||||
@@ -123,50 +142,37 @@ public static class PerceptualHash
|
|||||||
return hash;
|
return hash;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white.</summary>
|
/// <summary>
|
||||||
private static double[] Luminance(SKBitmap bitmap)
|
/// The grey levels (0–255, over white: <see cref="ImageGray.LumaOverWhite"/>) of an image reduced to dw × dh by area
|
||||||
|
/// averaging, one source row at a time (memory: one row and dw × source height values).
|
||||||
|
/// </summary>
|
||||||
|
internal static double[] AreaResample(RgbaImage image, int dw, int dh)
|
||||||
{
|
{
|
||||||
var width = bitmap.Width;
|
var sw = image.Width;
|
||||||
var height = bitmap.Height;
|
var sh = image.Height;
|
||||||
var result = new double[width * height];
|
|
||||||
var pixels = bitmap.GetPixelSpan();
|
|
||||||
var rowBytes = bitmap.RowBytes;
|
|
||||||
for (var y = 0; y < height; y++)
|
|
||||||
{
|
|
||||||
var row = pixels.Slice(y * rowBytes, width * 4);
|
|
||||||
for (var x = 0; x < width; x++)
|
|
||||||
{
|
|
||||||
var r = row[x * 4];
|
|
||||||
var g = row[(x * 4) + 1];
|
|
||||||
var b = row[(x * 4) + 2];
|
|
||||||
var a = row[(x * 4) + 3];
|
|
||||||
var white = 255 - a; // premultiplied: over white, each channel gains (255 − alpha)
|
|
||||||
result[(y * width) + x] = (0.299 * (r + white)) + (0.587 * (g + white)) + (0.114 * (b + white));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Area-averaging resample with exact fractional coverage (no aliasing when reducing).</summary>
|
|
||||||
internal static double[] AreaResample(double[] source, int sw, int sh, int dw, int dh)
|
|
||||||
{
|
|
||||||
var horizontal = new double[dw * sh];
|
|
||||||
var xs = Weights(sw, dw);
|
var xs = Weights(sw, dw);
|
||||||
|
var horizontal = new double[dw * sh];
|
||||||
|
var grey = new double[sw];
|
||||||
for (var y = 0; y < sh; y++)
|
for (var y = 0; y < sh; y++)
|
||||||
{
|
{
|
||||||
|
ImageGray.LumaOverWhite(image.GetRow(y), grey);
|
||||||
for (var dx = 0; dx < dw; dx++)
|
for (var dx = 0; dx < dw; dx++)
|
||||||
{
|
{
|
||||||
double sum = 0;
|
double sum = 0;
|
||||||
foreach (var (index, weight) in xs[dx])
|
foreach (var (index, weight) in xs[dx])
|
||||||
{
|
{
|
||||||
sum += source[(y * sw) + index] * weight;
|
sum += grey[index] * weight;
|
||||||
}
|
}
|
||||||
|
|
||||||
horizontal[(y * dw) + dx] = sum;
|
horizontal[(y * dw) + dx] = sum;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return Vertical(horizontal, sh, dw, dh);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double[] Vertical(double[] horizontal, int sh, int dw, int dh)
|
||||||
|
{
|
||||||
var result = new double[dw * dh];
|
var result = new double[dw * dh];
|
||||||
var ys = Weights(sh, dh);
|
var ys = Weights(sh, dh);
|
||||||
for (var dy = 0; dy < dh; dy++)
|
for (var dy = 0; dy < dh; dy++)
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using SkiaSharp;
|
using Febe.Core.Codecs.Images;
|
||||||
|
using Febe.Core.Drawing;
|
||||||
|
|
||||||
namespace Febe.Core.Library;
|
namespace Febe.Core.Library;
|
||||||
|
|
||||||
@@ -54,13 +55,14 @@ public sealed class ThumbnailStore
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide);
|
using var image = DecodeFor(encodedImage, LongSide);
|
||||||
if (bitmap is null)
|
if (image is null)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
WriteJpeg(target, Render(bitmap, LongSide));
|
using var thumbnail = Render(image, LongSide);
|
||||||
|
WriteJpeg(target, thumbnail);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,26 +96,20 @@ public sealed class ThumbnailStore
|
|||||||
}
|
}
|
||||||
|
|
||||||
const int width = 270, height = LongSide; // 9:16, like stories and reels
|
const int width = 270, height = LongSide; // 9:16, like stories and reels
|
||||||
using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
using var tile = new RgbaImage(width, height);
|
||||||
var canvas = surface.Canvas;
|
using (var canvas = new Canvas(tile))
|
||||||
canvas.Clear(new SKColor(0xE4, 0xE4, 0xE4));
|
|
||||||
using (var paint = new SKPaint { Color = new SKColor(0x9A, 0x9A, 0x9A), IsAntialias = true, Style = SKPaintStyle.Fill })
|
|
||||||
{
|
{
|
||||||
canvas.DrawCircle(width / 2f, height / 2f, 34, paint);
|
var background = new Color(0xE4, 0xE4, 0xE4);
|
||||||
}
|
canvas.Clear(background);
|
||||||
|
canvas.FillCircle(width / 2f, height / 2f, 34, new Color(0x9A, 0x9A, 0x9A));
|
||||||
|
|
||||||
using (var paint = new SKPaint { Color = new SKColor(0xE4, 0xE4, 0xE4), IsAntialias = true, Style = SKPaintStyle.Fill })
|
// The play sign: a triangle pointing right, a little right of the centre to look centred.
|
||||||
{
|
var cx = (width / 2f) + 4;
|
||||||
// A play triangle drawn as three thin rectangles would be blurry; vertices keep it crisp.
|
|
||||||
var cx = width / 2f + 4;
|
|
||||||
var cy = height / 2f;
|
var cy = height / 2f;
|
||||||
SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)];
|
canvas.Fill(new PathBuilder().AddPolygon([cx - 10, cy - 15, cx - 10, cy + 15, cx + 15, cy]), background);
|
||||||
canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
using var image = surface.Snapshot();
|
WriteJpeg(path, tile);
|
||||||
using var bitmap = SKBitmap.FromImage(image);
|
|
||||||
WriteJpeg(path, bitmap.Copy());
|
|
||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,67 +121,66 @@ public sealed class ThumbnailStore
|
|||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(source);
|
ArgumentNullException.ThrowIfNull(source);
|
||||||
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
|
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
|
||||||
using var decoded = ImageDecoding.DecodeUpright(source, longSide);
|
using var decoded = DecodeFor(source, longSide);
|
||||||
if (decoded is null)
|
if (decoded is null)
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
using var small = Render(decoded, longSide);
|
using var small = Render(decoded, longSide);
|
||||||
using var pixmap = small.PeekPixels();
|
return Jpeg(small);
|
||||||
if (pixmap is null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality));
|
|
||||||
return data?.ToArray();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static SKBitmap Render(SKBitmap source, int longSide)
|
/// <summary>
|
||||||
|
/// Decodes an image upright for a picture of <paramref name="longSide"/> pixels. A JPEG may be shrunk while decoding,
|
||||||
|
/// but only down to twice that size: the last step is left to Lanczos, since the codec's 8 × 8 block averages would
|
||||||
|
/// show at almost 1:1. Null when the content cannot be decoded.
|
||||||
|
/// </summary>
|
||||||
|
internal static RgbaImage? DecodeFor(Stream encodedImage, int longSide) =>
|
||||||
|
ImageDecoding.DecodeUpright(encodedImage, 2 * longSide);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The image reduced to <paramref name="longSide"/> on its long side (Lanczos, never enlarged) and seen over white,
|
||||||
|
/// since JPEG has no alpha. Always a new pooled image, which the caller disposes.
|
||||||
|
/// </summary>
|
||||||
|
internal static RgbaImage Render(RgbaImage source, int longSide)
|
||||||
{
|
{
|
||||||
var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height));
|
var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, longSide);
|
||||||
var width = Math.Max(1, (int)Math.Round(source.Width * scale));
|
var result = ImageResampler.Resize(source, width, height, pooled: true);
|
||||||
var height = Math.Max(1, (int)Math.Round(source.Height * scale));
|
ImageBackground.Flatten(result, Color.White);
|
||||||
var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
|
||||||
using var canvas = new SKCanvas(result);
|
|
||||||
canvas.Clear(SKColors.White); // JPEG has no alpha: transparent areas become white
|
|
||||||
using var image = SKImage.FromBitmap(source);
|
|
||||||
canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void WriteJpeg(string target, SKBitmap bitmap)
|
/// <summary>The JPEG of a thumbnail: quality <see cref="JpegQuality"/>, chroma 4:2:0.</summary>
|
||||||
|
internal static byte[] Jpeg(RgbaImage image) =>
|
||||||
|
JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = JpegQuality, Subsampling = JpegSubsampling.Ratio420 });
|
||||||
|
|
||||||
|
private static void WriteJpeg(string target, RgbaImage image)
|
||||||
{
|
{
|
||||||
using (bitmap)
|
var data = Jpeg(image);
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
||||||
|
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
|
||||||
|
try
|
||||||
{
|
{
|
||||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
|
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
|
||||||
var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp";
|
{
|
||||||
|
file.Write(data);
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using (var pixmap = bitmap.PeekPixels() ?? throw new InvalidOperationException("Miniatura senza pixel."))
|
File.Move(temp, target, overwrite: false);
|
||||||
using (var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality))
|
|
||||||
?? throw new InvalidOperationException("Codifica JPEG della miniatura non riuscita."))
|
|
||||||
using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write))
|
|
||||||
{
|
|
||||||
data.SaveTo(file);
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
File.Move(temp, target, overwrite: false);
|
|
||||||
}
|
|
||||||
catch (IOException) when (File.Exists(target))
|
|
||||||
{
|
|
||||||
// Created meanwhile by another task: same content.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
finally
|
catch (IOException) when (File.Exists(target))
|
||||||
{
|
{
|
||||||
if (File.Exists(temp))
|
// Created meanwhile by another task: same content.
|
||||||
{
|
}
|
||||||
File.Delete(temp);
|
}
|
||||||
}
|
finally
|
||||||
|
{
|
||||||
|
if (File.Exists(temp))
|
||||||
|
{
|
||||||
|
File.Delete(temp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
using System.Buffers.Binary;
|
using System.Buffers.Binary;
|
||||||
using SkiaSharp;
|
using Febe.Core.Codecs.Images;
|
||||||
|
using Febe.Core.Drawing;
|
||||||
|
|
||||||
namespace Febe.Desktop.Core;
|
namespace Febe.Desktop.Core;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The brand mark of appendix C — a rounded square in the accent colour with a ring and a dot, a body and its moon —
|
/// The brand mark of appendix C — a rounded square in the accent colour with a ring and a dot, a body and its moon —
|
||||||
/// drawn with SkiaSharp at any size, the same way the SVG describes it:
|
/// drawn with Febe's own rasteriser (<see cref="Canvas"/>) at any size, the same way the SVG describes it:
|
||||||
/// <code>
|
/// <code>
|
||||||
/// <rect width="32" height="32" rx="8" fill="#0F5C8C"/>
|
/// <rect width="32" height="32" rx="8" fill="#0F5C8C"/>
|
||||||
/// <circle cx="14.5" cy="17.5" r="7.4" fill="none" stroke="#FFFFFF" stroke-width="2.6"/>
|
/// <circle cx="14.5" cy="17.5" r="7.4" fill="none" stroke="#FFFFFF" stroke-width="2.6"/>
|
||||||
@@ -17,57 +18,32 @@ public static class BrandMark
|
|||||||
/// <summary>The sizes of the Windows icon: window, notification area, taskbar, Explorer, installer.</summary>
|
/// <summary>The sizes of the Windows icon: window, notification area, taskbar, Explorer, installer.</summary>
|
||||||
public static IReadOnlyList<int> IconSizes { get; } = [16, 24, 32, 48, 64, 128, 256];
|
public static IReadOnlyList<int> IconSizes { get; } = [16, 24, 32, 48, 64, 128, 256];
|
||||||
|
|
||||||
private static readonly SKColor Accent = new(0x0F, 0x5C, 0x8C);
|
private static readonly Color Accent = Color.FromRgb(0x0F5C8C);
|
||||||
|
|
||||||
/// <summary>The mark as a square bitmap of <paramref name="size"/> pixels, premultiplied BGRA, transparent corners.</summary>
|
/// <summary>The mark as a square image of <paramref name="size"/> pixels, straight RGBA, transparent corners.</summary>
|
||||||
public static SKBitmap Render(int size)
|
public static RgbaImage Render(int size)
|
||||||
{
|
{
|
||||||
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
|
ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
|
||||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(size, 1024);
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(size, 1024);
|
||||||
var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Premul));
|
var image = new RgbaImage(size, size);
|
||||||
using var canvas = new SKCanvas(bitmap);
|
using var canvas = new Canvas(image);
|
||||||
canvas.Clear(SKColors.Transparent);
|
canvas.Scale(size / 32f);
|
||||||
var scale = size / 32f;
|
canvas.FillRoundRect(0, 0, 32, 32, 8, Accent);
|
||||||
canvas.Scale(scale);
|
canvas.StrokeCircle(14.5f, 17.5f, 7.4f, 2.6f, Color.White);
|
||||||
using (var square = new SKPaint { Color = Accent, IsAntialias = true, Style = SKPaintStyle.Fill })
|
canvas.FillCircle(23.2f, 8.8f, 3.1f, Color.White);
|
||||||
{
|
return image;
|
||||||
canvas.DrawRoundRect(new SKRect(0, 0, 32, 32), 8, 8, square);
|
|
||||||
}
|
|
||||||
|
|
||||||
using (var ring = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Stroke, StrokeWidth = 2.6f })
|
|
||||||
{
|
|
||||||
canvas.DrawCircle(14.5f, 17.5f, 7.4f, ring);
|
|
||||||
}
|
|
||||||
|
|
||||||
using (var moon = new SKPaint { Color = SKColors.White, IsAntialias = true, Style = SKPaintStyle.Fill })
|
|
||||||
{
|
|
||||||
canvas.DrawCircle(23.2f, 8.8f, 3.1f, moon);
|
|
||||||
}
|
|
||||||
|
|
||||||
canvas.Flush();
|
|
||||||
return bitmap;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The multi-size Windows icon (<see cref="IconSizes"/>) of the mark, as the bytes of an .ico file.</summary>
|
/// <summary>The multi-size Windows icon (<see cref="IconSizes"/>) of the mark, as the bytes of an .ico file.</summary>
|
||||||
public static byte[] RenderIcon()
|
public static byte[] RenderIcon()
|
||||||
{
|
{
|
||||||
var images = new List<SKBitmap>();
|
var images = new List<RgbaImage>();
|
||||||
try
|
foreach (var size in IconSizes)
|
||||||
{
|
{
|
||||||
foreach (var size in IconSizes)
|
images.Add(Render(size));
|
||||||
{
|
}
|
||||||
images.Add(Render(size));
|
|
||||||
}
|
|
||||||
|
|
||||||
return IcoWriter.Write(images);
|
return IcoWriter.Write(images);
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
foreach (var image in images)
|
|
||||||
{
|
|
||||||
image.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +62,7 @@ public static class IcoWriter
|
|||||||
private const int BitmapInfoHeader = 40;
|
private const int BitmapInfoHeader = 40;
|
||||||
|
|
||||||
/// <summary>The .ico bytes of square <paramref name="images"/> (1 to 256 pixels), in the order given.</summary>
|
/// <summary>The .ico bytes of square <paramref name="images"/> (1 to 256 pixels), in the order given.</summary>
|
||||||
public static byte[] Write(IReadOnlyList<SKBitmap> images)
|
public static byte[] Write(IReadOnlyList<RgbaImage> images)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(images);
|
ArgumentNullException.ThrowIfNull(images);
|
||||||
if (images.Count is 0 or > ushort.MaxValue)
|
if (images.Count is 0 or > ushort.MaxValue)
|
||||||
@@ -167,41 +143,48 @@ public static class IcoWriter
|
|||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The image of an entry as a bitmap (DIB or PNG), for comparisons.</summary>
|
/// <summary>The image of an entry (DIB or PNG) as straight RGBA, for comparisons.</summary>
|
||||||
public static SKBitmap Decode(ReadOnlySpan<byte> ico, IcoEntry entry)
|
public static RgbaImage Decode(ReadOnlySpan<byte> ico, IcoEntry entry)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(entry);
|
ArgumentNullException.ThrowIfNull(entry);
|
||||||
var data = ico.Slice(entry.Offset, entry.Length);
|
var data = ico.Slice(entry.Offset, entry.Length);
|
||||||
if (entry.IsPng)
|
if (entry.IsPng)
|
||||||
{
|
{
|
||||||
return SKBitmap.Decode(data.ToArray()) ?? throw new InvalidDataException("PNG dell'icona non leggibile.");
|
try
|
||||||
|
{
|
||||||
|
return PngDecoder.Decode(data.ToArray());
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException ex)
|
||||||
|
{
|
||||||
|
throw new InvalidDataException("PNG dell'icona non leggibile.", ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var size = entry.Size;
|
var size = entry.Size;
|
||||||
var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Unpremul));
|
var image = new RgbaImage(size, size);
|
||||||
var pixels = data[BitmapInfoHeader..];
|
var pixels = data[BitmapInfoHeader..];
|
||||||
for (var y = 0; y < size; y++)
|
for (var y = 0; y < size; y++)
|
||||||
{
|
{
|
||||||
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
|
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
|
||||||
|
var target = image.GetRow(y);
|
||||||
for (var x = 0; x < size; x++)
|
for (var x = 0; x < size; x++)
|
||||||
{
|
{
|
||||||
bitmap.SetPixel(x, y, new SKColor(row[(x * 4) + 2], row[(x * 4) + 1], row[x * 4], row[(x * 4) + 3]));
|
target[x * 4] = row[(x * 4) + 2];
|
||||||
|
target[(x * 4) + 1] = row[(x * 4) + 1];
|
||||||
|
target[(x * 4) + 2] = row[x * 4];
|
||||||
|
target[(x * 4) + 3] = row[(x * 4) + 3];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return bitmap;
|
return image;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ReadOnlySpan<byte> PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
private static ReadOnlySpan<byte> PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||||
|
|
||||||
private static byte[] Png(SKBitmap image)
|
private static byte[] Png(RgbaImage image) => PngEncoder.Encode(image, new PngEncoderOptions { ColorMode = PngColorMode.Rgba });
|
||||||
{
|
|
||||||
using var data = image.Encode(SKEncodedImageFormat.Png, 100) ?? throw new InvalidOperationException("Codifica PNG non riuscita.");
|
|
||||||
return data.ToArray();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>A 32-bit DIB: BITMAPINFOHEADER with twice the height (image + mask), BGRA rows bottom-up, AND mask.</summary>
|
/// <summary>A 32-bit DIB: BITMAPINFOHEADER with twice the height (image + mask), BGRA rows bottom-up, AND mask.</summary>
|
||||||
private static byte[] Dib(SKBitmap image)
|
private static byte[] Dib(RgbaImage image)
|
||||||
{
|
{
|
||||||
var size = image.Width;
|
var size = image.Width;
|
||||||
var maskStride = ((size + 31) / 32) * 4;
|
var maskStride = ((size + 31) / 32) * 4;
|
||||||
@@ -223,13 +206,13 @@ public static class IcoWriter
|
|||||||
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
|
var row = pixels.Slice((size - 1 - y) * size * 4, size * 4);
|
||||||
for (var x = 0; x < size; x++)
|
for (var x = 0; x < size; x++)
|
||||||
{
|
{
|
||||||
// GetPixel gives straight (not premultiplied) alpha, as icons want it.
|
// Straight (not premultiplied) alpha, as icons want it.
|
||||||
var c = image.GetPixel(x, y);
|
var c = image.GetPixel(x, y);
|
||||||
row[x * 4] = c.Blue;
|
row[x * 4] = c.B;
|
||||||
row[(x * 4) + 1] = c.Green;
|
row[(x * 4) + 1] = c.G;
|
||||||
row[(x * 4) + 2] = c.Red;
|
row[(x * 4) + 2] = c.R;
|
||||||
row[(x * 4) + 3] = c.Alpha;
|
row[(x * 4) + 3] = c.A;
|
||||||
if (c.Alpha == 0)
|
if (c.A == 0)
|
||||||
{
|
{
|
||||||
// Transparent pixels are also set in the AND mask, for the readers that ignore the alpha channel.
|
// Transparent pixels are also set in the AND mask, for the readers that ignore the alpha channel.
|
||||||
var maskRow = mask.Slice((size - 1 - y) * maskStride, maskStride);
|
var maskRow = mask.Slice((size - 1 - y) * maskStride, maskStride);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<!-- Eseguibile Windows (WPF): finestra con l'interfaccia, icona nell'area di notifica, WebView2Host.
|
<!-- Eseguibile Windows (WPF): finestra con l'interfaccia, icona nell'area di notifica, WebView2Host.
|
||||||
Si compila anche da Linux grazie a EnableWindowsTargeting (CI e rilascio), ma gira solo su Windows.
|
Si compila anche da Linux grazie a EnableWindowsTargeting (CI e rilascio), ma gira solo su Windows.
|
||||||
Pubblicazione in un solo Febe.exe (specifica §12): il comando completo è in installer/costruisci.sh.
|
Pubblicazione in un solo Febe.exe (specifica §12): il comando completo è in installer/costruisci.sh.
|
||||||
Le librerie native (e_sqlite3, libSkiaSharp, WebView2Loader e quelle di WPF) stanno dentro l'eseguibile e si
|
Le librerie native (e_sqlite3, WebView2Loader e quelle di WPF) stanno dentro l'eseguibile e si
|
||||||
estraggono da sole al primo avvio; i file di configurazione e i simboli non escono accanto all'eseguibile. -->
|
estraggono da sole al primo avvio; i file di configurazione e i simboli non escono accanto all'eseguibile. -->
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>WinExe</OutputType>
|
<OutputType>WinExe</OutputType>
|
||||||
@@ -47,8 +47,8 @@
|
|||||||
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
|
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<!-- Un solo file: la configurazione per sito (config/*.json) è già incorporata in Febe.Core e si sovrascrive dalla
|
<!-- Un solo file: la configurazione per sito (config/*.json) è già incorporata in Febe.Core e si sovrascrive dalla
|
||||||
cartella Dati; i simboli (anche il .pdb nativo di SkiaSharp, quasi 100 MB) e la documentazione XML dei pacchetti non
|
cartella Dati; i simboli e la documentazione XML dei pacchetti non servono a chi usa Febe. Niente di tutto
|
||||||
servono a chi usa Febe. Niente di tutto questo esce accanto all'eseguibile. -->
|
questo esce accanto all'eseguibile. -->
|
||||||
<Target Name="FebeSingleFileOnly" AfterTargets="ComputeResolvedFilesToPublishList" Condition="'$(PublishSingleFile)' == 'true'">
|
<Target Name="FebeSingleFileOnly" AfterTargets="ComputeResolvedFilesToPublishList" Condition="'$(PublishSingleFile)' == 'true'">
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ResolvedFileToPublish Remove="@(ResolvedFileToPublish)" Condition="'%(ResolvedFileToPublish.Extension)' == '.pdb' or '%(ResolvedFileToPublish.Extension)' == '.xml' or $([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').StartsWith('config'))" />
|
<ResolvedFileToPublish Remove="@(ResolvedFileToPublish)" Condition="'%(ResolvedFileToPublish.Extension)' == '.pdb' or '%(ResolvedFileToPublish.Extension)' == '.xml' or $([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').StartsWith('config'))" />
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 108 KiB |
@@ -12,7 +12,6 @@
|
|||||||
<ProjectReference Include="..\Febe.Browser\Febe.Browser.csproj" />
|
<ProjectReference Include="..\Febe.Browser\Febe.Browser.csproj" />
|
||||||
<ProjectReference Include="..\Febe.Web\Febe.Web.csproj" />
|
<ProjectReference Include="..\Febe.Web\Febe.Web.csproj" />
|
||||||
<ProjectReference Include="..\Febe.App\Febe.App.csproj" />
|
<ProjectReference Include="..\Febe.App\Febe.App.csproj" />
|
||||||
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<InternalsVisibleTo Include="Febe.Tests" />
|
<InternalsVisibleTo Include="Febe.Tests" />
|
||||||
|
|||||||
@@ -77,7 +77,8 @@ public sealed record MediaDto(
|
|||||||
string? Folder,
|
string? Folder,
|
||||||
string? Thumb,
|
string? Thumb,
|
||||||
bool Available,
|
bool Available,
|
||||||
string State);
|
string State,
|
||||||
|
bool Damaged = false);
|
||||||
|
|
||||||
/// <summary>Everything the viewer shows of an entry.</summary>
|
/// <summary>Everything the viewer shows of an entry.</summary>
|
||||||
public sealed record EntryDto(
|
public sealed record EntryDto(
|
||||||
|
|||||||
@@ -237,6 +237,7 @@ public static class LibraryApi
|
|||||||
folder = string.IsNullOrEmpty(directory) ? accountFolder : Path.Combine(accountFolder, directory);
|
folder = string.IsNullOrEmpty(directory) ? accountFolder : Path.Combine(accountFolder, directory);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var path = files.Resolve(account, m);
|
||||||
return new MediaDto(
|
return new MediaDto(
|
||||||
m.Id,
|
m.Id,
|
||||||
m.Position,
|
m.Position,
|
||||||
@@ -248,8 +249,9 @@ public static class LibraryApi
|
|||||||
relative is null ? null : Path.GetFileName(LibraryLayout.ToPlatform(relative)),
|
relative is null ? null : Path.GetFileName(LibraryLayout.ToPlatform(relative)),
|
||||||
folder,
|
folder,
|
||||||
m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null,
|
m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null,
|
||||||
files.Resolve(account, m) is not null,
|
path is not null,
|
||||||
ApiMapping.State(m.State));
|
ApiMapping.State(m.State),
|
||||||
|
IsDamaged(m, path));
|
||||||
}).ToList();
|
}).ToList();
|
||||||
|
|
||||||
return new EntryDto(
|
return new EntryDto(
|
||||||
@@ -272,6 +274,14 @@ public static class LibraryApi
|
|||||||
media);
|
media);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «File danneggiato o incompleto» (spec §4.6, §8.4): a photo on disk with no thumbnail whose bytes are damaged or
|
||||||
|
/// truncated. A photo with a thumbnail was decoded when it was stored, so only those without one are looked at,
|
||||||
|
/// one file each time the viewer opens it; the file is only read, never touched (rule 12).
|
||||||
|
/// </summary>
|
||||||
|
private static bool IsDamaged(Media media, string? path) =>
|
||||||
|
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && DamagedImage.IsFileDamaged(path);
|
||||||
|
|
||||||
private static async Task<(Account Account, Media Media)> MediaAsync(IFebeStorage storage, long mediaId, CancellationToken ct)
|
private static async Task<(Account Account, Media Media)> MediaAsync(IFebeStorage storage, long mediaId, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
|
var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
using SkiaSharp;
|
using System.Numerics;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using Febe.Core.Drawing;
|
||||||
|
|
||||||
namespace Febe.Web.Demo;
|
namespace Febe.Web.Demo;
|
||||||
|
|
||||||
@@ -35,8 +37,8 @@ public static class DemoImages
|
|||||||
{
|
{
|
||||||
ArgumentOutOfRangeException.ThrowIfLessThan(width, 16);
|
ArgumentOutOfRangeException.ThrowIfLessThan(width, 16);
|
||||||
ArgumentOutOfRangeException.ThrowIfLessThan(height, 16);
|
ArgumentOutOfRangeException.ThrowIfLessThan(height, 16);
|
||||||
using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
var image = new RgbaImage(width, height);
|
||||||
using (var canvas = new SKCanvas(bitmap))
|
using (var canvas = new Canvas(image))
|
||||||
{
|
{
|
||||||
var painter = new Painter(canvas, width, height, new Random(seed * 7919 + (int)subject));
|
var painter = new Painter(canvas, width, height, new Random(seed * 7919 + (int)subject));
|
||||||
switch (subject)
|
switch (subject)
|
||||||
@@ -59,64 +61,54 @@ public static class DemoImages
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
using var image = SKImage.FromBitmap(bitmap);
|
return JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = quality });
|
||||||
using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality);
|
|
||||||
return data.ToArray();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class Painter(SKCanvas canvas, float w, float h, Random random)
|
/// <summary>A rectangle by its edges.</summary>
|
||||||
|
private readonly record struct Box(float Left, float Top, float Right, float Bottom);
|
||||||
|
|
||||||
|
private sealed class Painter(Canvas canvas, float w, float h, Random random)
|
||||||
{
|
{
|
||||||
private float R(float min, float max) => min + ((float)random.NextDouble() * (max - min));
|
private float R(float min, float max) => min + ((float)random.NextDouble() * (max - min));
|
||||||
|
|
||||||
private T Pick<T>(params T[] items) => items[random.Next(items.Length)];
|
private T Pick<T>(params T[] items) => items[random.Next(items.Length)];
|
||||||
|
|
||||||
private static SKColor C(uint rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
|
private static Color C(uint rgb) => Color.FromRgb(rgb);
|
||||||
|
|
||||||
private static SKColor Mix(SKColor a, SKColor b, float t) => new(
|
private static Color Mix(Color a, Color b, float t) => a.Mix(b, t).WithAlpha(255);
|
||||||
(byte)(a.Red + ((b.Red - a.Red) * t)),
|
|
||||||
(byte)(a.Green + ((b.Green - a.Green) * t)),
|
|
||||||
(byte)(a.Blue + ((b.Blue - a.Blue) * t)));
|
|
||||||
|
|
||||||
private void Gradient(SKRect rect, SKColor top, SKColor bottom)
|
private void Gradient(Box rect, Color top, Color bottom) =>
|
||||||
|
canvas.FillRect(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, new LinearGradientBrush(new Vector2(0, rect.Top), new Vector2(0, rect.Bottom), [top, bottom]));
|
||||||
|
|
||||||
|
private void Fill(PathBuilder path, Color color) => canvas.Fill(path, color);
|
||||||
|
|
||||||
|
private void Circle(float x, float y, float r, Color color) => canvas.FillCircle(x, y, r, color);
|
||||||
|
|
||||||
|
private void Oval(float cx, float cy, float rx, float ry, Color color, float rotate = 0)
|
||||||
{
|
{
|
||||||
using var paint = new SKPaint { IsAntialias = true };
|
|
||||||
paint.Shader = SKShader.CreateLinearGradient(new SKPoint(0, rect.Top), new SKPoint(0, rect.Bottom), [top, bottom], null, SKShaderTileMode.Clamp);
|
|
||||||
canvas.DrawRect(rect, paint);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Fill(SKPathBuilder builder, SKColor color)
|
|
||||||
{
|
|
||||||
using var path = builder.Detach();
|
|
||||||
using var paint = new SKPaint { IsAntialias = true, Color = color, Style = SKPaintStyle.Fill };
|
|
||||||
canvas.DrawPath(path, paint);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Circle(float x, float y, float r, SKColor color)
|
|
||||||
{
|
|
||||||
using var paint = new SKPaint { IsAntialias = true, Color = color };
|
|
||||||
canvas.DrawCircle(x, y, r, paint);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Oval(float cx, float cy, float rx, float ry, SKColor color, float rotate = 0)
|
|
||||||
{
|
|
||||||
using var paint = new SKPaint { IsAntialias = true, Color = color };
|
|
||||||
canvas.Save();
|
canvas.Save();
|
||||||
canvas.Translate(cx, cy);
|
canvas.Translate(cx, cy);
|
||||||
canvas.RotateDegrees(rotate);
|
canvas.Rotate(rotate);
|
||||||
canvas.DrawOval(new SKRect(-rx, -ry, rx, ry), paint);
|
canvas.FillEllipse(0, 0, rx, ry, color);
|
||||||
canvas.Restore();
|
canvas.Restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Rect(float x, float y, float rw, float rh, SKColor color, float radius = 0)
|
private void Rect(float x, float y, float rw, float rh, Color color, float radius = 0)
|
||||||
{
|
{
|
||||||
using var paint = new SKPaint { IsAntialias = true, Color = color };
|
if (radius > 0)
|
||||||
canvas.DrawRoundRect(new SKRect(x, y, x + rw, y + rh), radius, radius, paint);
|
{
|
||||||
|
canvas.FillRoundRect(x, y, rw, rh, radius, color);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
canvas.FillRect(x, y, rw, rh, color);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>A soft ridge across the picture at height <paramref name="baseY"/>, filled down to the bottom.</summary>
|
/// <summary>A soft ridge across the picture at height <paramref name="baseY"/>, filled down to the bottom.</summary>
|
||||||
private static SKPathBuilder Ridge(float w, float h, float baseY, float amplitude, int bumps, float phase)
|
private static PathBuilder Ridge(float w, float h, float baseY, float amplitude, int bumps, float phase)
|
||||||
{
|
{
|
||||||
var path = new SKPathBuilder();
|
var path = new PathBuilder();
|
||||||
path.MoveTo(0, h);
|
path.MoveTo(0, h);
|
||||||
const int steps = 48;
|
const int steps = 48;
|
||||||
for (var i = 0; i <= steps; i++)
|
for (var i = 0; i <= steps; i++)
|
||||||
@@ -138,23 +130,23 @@ public static class DemoImages
|
|||||||
var cx = R(-0.1f, 1.1f) * w;
|
var cx = R(-0.1f, 1.1f) * w;
|
||||||
var cy = R(top, bottom) * h;
|
var cy = R(top, bottom) * h;
|
||||||
var size = R(0.07f, 0.13f) * Math.Max(w, h);
|
var size = R(0.07f, 0.13f) * Math.Max(w, h);
|
||||||
var color = new SKColor(255, 255, 255, (byte)R(200, 240));
|
var color = new Color(255, 255, 255, (byte)R(200, 240));
|
||||||
Oval(cx, cy, size, size * 0.32f, color);
|
Oval(cx, cy, size, size * 0.32f, color);
|
||||||
Oval(cx - (size * 0.35f), cy + (size * 0.05f), size * 0.55f, size * 0.25f, color);
|
Oval(cx - (size * 0.35f), cy + (size * 0.05f), size * 0.55f, size * 0.25f, color);
|
||||||
Oval(cx + (size * 0.25f), cy - (size * 0.12f), size * 0.5f, size * 0.3f, new SKColor(255, 255, 255, (byte)R(220, 250)));
|
Oval(cx + (size * 0.25f), cy - (size * 0.12f), size * 0.5f, size * 0.3f, new Color(255, 255, 255, (byte)R(220, 250)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Cypress(float x, float baseY, float size, SKColor color)
|
private void Cypress(float x, float baseY, float size, Color color)
|
||||||
{
|
{
|
||||||
Oval(x, baseY - (size * 0.55f), size * 0.22f, size * 0.55f, color);
|
Oval(x, baseY - (size * 0.55f), size * 0.22f, size * 0.55f, color);
|
||||||
Rect(x - (size * 0.03f), baseY - (size * 0.08f), size * 0.06f, size * 0.12f, Mix(color, SKColors.Black, 0.3f));
|
Rect(x - (size * 0.03f), baseY - (size * 0.08f), size * 0.06f, size * 0.12f, Mix(color, Color.Black, 0.3f));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Hills(bool road)
|
public void Hills(bool road)
|
||||||
{
|
{
|
||||||
var sky = Pick(C(0x6FA8DC), C(0x7FB3E0), C(0x5E9BD6), C(0x8DBBE3));
|
var sky = Pick(C(0x6FA8DC), C(0x7FB3E0), C(0x5E9BD6), C(0x8DBBE3));
|
||||||
Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.45f));
|
Gradient(new Box(0, 0, w, h), sky, Mix(sky, Color.White, 0.45f));
|
||||||
Clouds(0.08f, 0.35f, random.Next(2, 5));
|
Clouds(0.08f, 0.35f, random.Next(2, 5));
|
||||||
var greens = Pick(
|
var greens = Pick(
|
||||||
new[] { C(0x8DB867), C(0x6E9E4C), C(0x4F8A3E), C(0x3C7232) },
|
new[] { C(0x8DB867), C(0x6E9E4C), C(0x4F8A3E), C(0x3C7232) },
|
||||||
@@ -164,7 +156,7 @@ public static class DemoImages
|
|||||||
for (var layer = 0; layer < 4; layer++)
|
for (var layer = 0; layer < 4; layer++)
|
||||||
{
|
{
|
||||||
var y = baseY + (layer * h * R(0.08f, 0.12f));
|
var y = baseY + (layer * h * R(0.08f, 0.12f));
|
||||||
using var ridge = Ridge(w, h, y, h * R(0.015f, 0.04f), random.Next(1, 4), R(0, 6));
|
var ridge = Ridge(w, h, y, h * R(0.015f, 0.04f), random.Next(1, 4), R(0, 6));
|
||||||
Fill(ridge, greens[layer]);
|
Fill(ridge, greens[layer]);
|
||||||
if (!road && layer < 3)
|
if (!road && layer < 3)
|
||||||
{
|
{
|
||||||
@@ -178,7 +170,7 @@ public static class DemoImages
|
|||||||
if (road)
|
if (road)
|
||||||
{
|
{
|
||||||
var horizon = baseY + (h * 0.03f);
|
var horizon = baseY + (h * 0.03f);
|
||||||
using var path = new SKPathBuilder();
|
var path = new PathBuilder();
|
||||||
path.MoveTo(w * 0.47f, horizon);
|
path.MoveTo(w * 0.47f, horizon);
|
||||||
path.LineTo(w * 0.53f, horizon);
|
path.LineTo(w * 0.53f, horizon);
|
||||||
path.LineTo(w * 0.86f, h);
|
path.LineTo(w * 0.86f, h);
|
||||||
@@ -208,13 +200,13 @@ public static class DemoImages
|
|||||||
public void Mountains()
|
public void Mountains()
|
||||||
{
|
{
|
||||||
var sky = Pick(C(0x5D8FC8), C(0x6E9BD0), C(0x7FA8D6));
|
var sky = Pick(C(0x5D8FC8), C(0x6E9BD0), C(0x7FA8D6));
|
||||||
Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.55f));
|
Gradient(new Box(0, 0, w, h), sky, Mix(sky, Color.White, 0.55f));
|
||||||
var ranges = new[] { C(0x8C9BB2), C(0x6F7F99), C(0x56647E) };
|
var ranges = new[] { C(0x8C9BB2), C(0x6F7F99), C(0x56647E) };
|
||||||
for (var r = 0; r < 3; r++)
|
for (var r = 0; r < 3; r++)
|
||||||
{
|
{
|
||||||
var baseY = h * (0.55f + (r * 0.08f));
|
var baseY = h * (0.55f + (r * 0.08f));
|
||||||
var peaks = random.Next(2, 4) + r;
|
var peaks = random.Next(2, 4) + r;
|
||||||
using var path = new SKPathBuilder();
|
var path = new PathBuilder();
|
||||||
path.MoveTo(0, h);
|
path.MoveTo(0, h);
|
||||||
path.LineTo(0, baseY);
|
path.LineTo(0, baseY);
|
||||||
var snow = new List<(float X, float Y, float Half)>();
|
var snow = new List<(float X, float Y, float Half)>();
|
||||||
@@ -239,7 +231,7 @@ public static class DemoImages
|
|||||||
{
|
{
|
||||||
var depth = (baseY - py) * 0.32f;
|
var depth = (baseY - py) * 0.32f;
|
||||||
var ratio = depth / (baseY - py);
|
var ratio = depth / (baseY - py);
|
||||||
using var cap = new SKPathBuilder();
|
var cap = new PathBuilder();
|
||||||
cap.MoveTo(px, py);
|
cap.MoveTo(px, py);
|
||||||
cap.LineTo(px + (half * ratio), py + depth);
|
cap.LineTo(px + (half * ratio), py + depth);
|
||||||
cap.LineTo(px + (half * ratio * 0.3f), py + (depth * 0.8f));
|
cap.LineTo(px + (half * ratio * 0.3f), py + (depth * 0.8f));
|
||||||
@@ -260,7 +252,7 @@ public static class DemoImages
|
|||||||
var x = R(0, 1) * w;
|
var x = R(0, 1) * w;
|
||||||
var size = h * R(0.06f, 0.11f);
|
var size = h * R(0.06f, 0.11f);
|
||||||
var y = groundY + (h * R(-0.01f, 0.08f));
|
var y = groundY + (h * R(-0.01f, 0.08f));
|
||||||
using var tree = new SKPathBuilder();
|
var tree = new PathBuilder();
|
||||||
tree.MoveTo(x, y - size);
|
tree.MoveTo(x, y - size);
|
||||||
tree.LineTo(x + (size * 0.28f), y);
|
tree.LineTo(x + (size * 0.28f), y);
|
||||||
tree.LineTo(x - (size * 0.28f), y);
|
tree.LineTo(x - (size * 0.28f), y);
|
||||||
@@ -273,16 +265,16 @@ public static class DemoImages
|
|||||||
{
|
{
|
||||||
var top = Pick(C(0x3B2A5A), C(0x4A2F63), C(0x2E2350));
|
var top = Pick(C(0x3B2A5A), C(0x4A2F63), C(0x2E2350));
|
||||||
var bottom = Pick(C(0xF0784C), C(0xE86A5A), C(0xF29A57));
|
var bottom = Pick(C(0xF0784C), C(0xE86A5A), C(0xF29A57));
|
||||||
Gradient(new SKRect(0, 0, w, h * 0.75f), top, bottom);
|
Gradient(new Box(0, 0, w, h * 0.75f), top, bottom);
|
||||||
var sunX = w * R(0.35f, 0.65f);
|
var sunX = w * R(0.35f, 0.65f);
|
||||||
var sunY = h * R(0.5f, 0.6f);
|
var sunY = h * R(0.5f, 0.6f);
|
||||||
var r = Math.Min(w, h) * R(0.09f, 0.13f);
|
var r = Math.Min(w, h) * R(0.09f, 0.13f);
|
||||||
Circle(sunX, sunY, r * 1.8f, new SKColor(255, 220, 170, 60));
|
Circle(sunX, sunY, r * 1.8f, new Color(255, 220, 170, 60));
|
||||||
Circle(sunX, sunY, r, C(0xFBE3B0));
|
Circle(sunX, sunY, r, C(0xFBE3B0));
|
||||||
var hills = new[] { C(0x6B4A73), C(0x4E3A63), C(0x35294D) };
|
var hills = new[] { C(0x6B4A73), C(0x4E3A63), C(0x35294D) };
|
||||||
for (var i = 0; i < 3; i++)
|
for (var i = 0; i < 3; i++)
|
||||||
{
|
{
|
||||||
using var ridge = Ridge(w, h, h * (0.66f + (i * 0.09f)), h * R(0.02f, 0.05f), random.Next(1, 3), R(0, 6));
|
var ridge = Ridge(w, h, h * (0.66f + (i * 0.09f)), h * R(0.02f, 0.05f), random.Next(1, 3), R(0, 6));
|
||||||
Fill(ridge, hills[i]);
|
Fill(ridge, hills[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -291,32 +283,31 @@ public static class DemoImages
|
|||||||
{
|
{
|
||||||
var sky = Pick(C(0x8CC4E8), C(0x7BB8E2), C(0x9CCDEB));
|
var sky = Pick(C(0x8CC4E8), C(0x7BB8E2), C(0x9CCDEB));
|
||||||
var horizon = h * R(0.42f, 0.55f);
|
var horizon = h * R(0.42f, 0.55f);
|
||||||
Gradient(new SKRect(0, 0, w, horizon), Mix(sky, C(0x4F8FC8), 0.3f), Mix(sky, SKColors.White, 0.5f));
|
Gradient(new Box(0, 0, w, horizon), Mix(sky, C(0x4F8FC8), 0.3f), Mix(sky, Color.White, 0.5f));
|
||||||
Clouds(0.08f, 0.25f, random.Next(0, 3));
|
Clouds(0.08f, 0.25f, random.Next(0, 3));
|
||||||
var water = Pick(C(0x2AA3C1), C(0x1F8FB3), C(0x31A9BE));
|
var water = Pick(C(0x2AA3C1), C(0x1F8FB3), C(0x31A9BE));
|
||||||
var sand = random.Next(3) == 0;
|
var sand = random.Next(3) == 0;
|
||||||
Gradient(new SKRect(0, horizon, w, h), water, Mix(water, C(0x0B4A6B), 0.55f));
|
Gradient(new Box(0, horizon, w, h), water, Mix(water, C(0x0B4A6B), 0.55f));
|
||||||
using (var wave = new SKPaint { IsAntialias = true, Color = new SKColor(255, 255, 255, 110), StrokeWidth = Math.Max(2, h * 0.004f), StrokeCap = SKStrokeCap.Round })
|
var foam = new Color(255, 255, 255, 110);
|
||||||
|
var waveWidth = Math.Max(2, h * 0.004f);
|
||||||
|
for (var i = 0; i < 9; i++)
|
||||||
{
|
{
|
||||||
for (var i = 0; i < 9; i++)
|
var y = horizon + ((h - horizon) * R(0.1f, 0.9f));
|
||||||
{
|
var x = R(0.05f, 0.85f) * w;
|
||||||
var y = horizon + ((h - horizon) * R(0.1f, 0.9f));
|
canvas.DrawLine(x, y, x + (w * R(0.03f, 0.08f)), y, waveWidth, foam, LineCap.Round);
|
||||||
var x = R(0.05f, 0.85f) * w;
|
|
||||||
canvas.DrawLine(x, y, x + (w * R(0.03f, 0.08f)), y, wave);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sand)
|
if (sand)
|
||||||
{
|
{
|
||||||
using var shore = Ridge(w, h, h * 0.9f, h * 0.02f, 2, R(0, 6));
|
var shore = Ridge(w, h, h * 0.9f, h * 0.02f, 2, R(0, 6));
|
||||||
Fill(shore, C(0xE9D8B4));
|
Fill(shore, C(0xE9D8B4));
|
||||||
}
|
}
|
||||||
|
|
||||||
var bx = w * R(0.3f, 0.65f);
|
var bx = w * R(0.3f, 0.65f);
|
||||||
var by = horizon + ((h - horizon) * R(0.2f, 0.4f));
|
var by = horizon + ((h - horizon) * R(0.2f, 0.4f));
|
||||||
var s = Math.Min(w, h) * R(0.06f, 0.09f);
|
var s = Math.Min(w, h) * R(0.06f, 0.09f);
|
||||||
using (var sail = new SKPathBuilder())
|
|
||||||
{
|
{
|
||||||
|
var sail = new PathBuilder();
|
||||||
sail.MoveTo(bx, by - s);
|
sail.MoveTo(bx, by - s);
|
||||||
sail.LineTo(bx + (s * 0.45f), by - (s * 0.1f));
|
sail.LineTo(bx + (s * 0.45f), by - (s * 0.1f));
|
||||||
sail.LineTo(bx, by - (s * 0.1f));
|
sail.LineTo(bx, by - (s * 0.1f));
|
||||||
@@ -324,8 +315,8 @@ public static class DemoImages
|
|||||||
Fill(sail, C(0xF6F6F4));
|
Fill(sail, C(0xF6F6F4));
|
||||||
}
|
}
|
||||||
|
|
||||||
using (var sail2 = new SKPathBuilder())
|
|
||||||
{
|
{
|
||||||
|
var sail2 = new PathBuilder();
|
||||||
sail2.MoveTo(bx - (s * 0.04f), by - (s * 0.85f));
|
sail2.MoveTo(bx - (s * 0.04f), by - (s * 0.85f));
|
||||||
sail2.LineTo(bx - (s * 0.04f), by - (s * 0.12f));
|
sail2.LineTo(bx - (s * 0.04f), by - (s * 0.12f));
|
||||||
sail2.LineTo(bx - (s * 0.38f), by - (s * 0.12f));
|
sail2.LineTo(bx - (s * 0.38f), by - (s * 0.12f));
|
||||||
@@ -333,8 +324,8 @@ public static class DemoImages
|
|||||||
Fill(sail2, C(0xE0533F));
|
Fill(sail2, C(0xE0533F));
|
||||||
}
|
}
|
||||||
|
|
||||||
using (var hull = new SKPathBuilder())
|
|
||||||
{
|
{
|
||||||
|
var hull = new PathBuilder();
|
||||||
hull.MoveTo(bx - (s * 0.5f), by - (s * 0.05f));
|
hull.MoveTo(bx - (s * 0.5f), by - (s * 0.05f));
|
||||||
hull.LineTo(bx + (s * 0.55f), by - (s * 0.05f));
|
hull.LineTo(bx + (s * 0.55f), by - (s * 0.05f));
|
||||||
hull.LineTo(bx + (s * 0.4f), by + (s * 0.1f));
|
hull.LineTo(bx + (s * 0.4f), by + (s * 0.1f));
|
||||||
@@ -346,10 +337,10 @@ public static class DemoImages
|
|||||||
|
|
||||||
public void City()
|
public void City()
|
||||||
{
|
{
|
||||||
Gradient(new SKRect(0, 0, w, h), C(0x1E1B3A), Pick(C(0x3E2F5C), C(0x4A3566), C(0x2F2A52)));
|
Gradient(new Box(0, 0, w, h), C(0x1E1B3A), Pick(C(0x3E2F5C), C(0x4A3566), C(0x2F2A52)));
|
||||||
for (var i = 0; i < 70; i++)
|
for (var i = 0; i < 70; i++)
|
||||||
{
|
{
|
||||||
Circle(R(0, 1) * w, R(0, 0.45f) * h, R(0.6f, 1.8f), new SKColor(255, 255, 255, (byte)R(60, 180)));
|
Circle(R(0, 1) * w, R(0, 0.45f) * h, R(0.6f, 1.8f), new Color(255, 255, 255, (byte)R(60, 180)));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (var layer = 0; layer < 2; layer++)
|
for (var layer = 0; layer < 2; layer++)
|
||||||
@@ -384,7 +375,7 @@ public static class DemoImages
|
|||||||
public void Leaves(bool flowers)
|
public void Leaves(bool flowers)
|
||||||
{
|
{
|
||||||
var dark = Pick(C(0x1F4D33), C(0x24533A), C(0x2B5C3C));
|
var dark = Pick(C(0x1F4D33), C(0x24533A), C(0x2B5C3C));
|
||||||
Gradient(new SKRect(0, 0, w, h), Mix(dark, SKColors.Black, 0.1f), dark);
|
Gradient(new Box(0, 0, w, h), Mix(dark, Color.Black, 0.1f), dark);
|
||||||
var greens = new[] { C(0x3E8C4E), C(0x5AA45A), C(0x2F7A45), C(0x78B861), C(0x4C9A6A), C(0x8BC46A) };
|
var greens = new[] { C(0x3E8C4E), C(0x5AA45A), C(0x2F7A45), C(0x78B861), C(0x4C9A6A), C(0x8BC46A) };
|
||||||
var size = Math.Max(w, h);
|
var size = Math.Max(w, h);
|
||||||
for (var i = 0; i < 46; i++)
|
for (var i = 0; i < 46; i++)
|
||||||
@@ -395,11 +386,10 @@ public static class DemoImages
|
|||||||
var angle = R(0, 360);
|
var angle = R(0, 360);
|
||||||
var color = greens[random.Next(greens.Length)];
|
var color = greens[random.Next(greens.Length)];
|
||||||
Oval(cx, cy, rx, rx * 0.42f, color, angle);
|
Oval(cx, cy, rx, rx * 0.42f, color, angle);
|
||||||
using var vein = new SKPaint { IsAntialias = true, Color = Mix(color, SKColors.White, 0.25f), StrokeWidth = Math.Max(1.5f, size * 0.003f) };
|
|
||||||
canvas.Save();
|
canvas.Save();
|
||||||
canvas.Translate(cx, cy);
|
canvas.Translate(cx, cy);
|
||||||
canvas.RotateDegrees(angle);
|
canvas.Rotate(angle);
|
||||||
canvas.DrawLine(-rx * 0.85f, 0, rx * 0.85f, 0, vein);
|
canvas.DrawLine(-rx * 0.85f, 0, rx * 0.85f, 0, Math.Max(1.5f, size * 0.003f), Mix(color, Color.White, 0.25f));
|
||||||
canvas.Restore();
|
canvas.Restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -426,21 +416,16 @@ public static class DemoImages
|
|||||||
{
|
{
|
||||||
var table = Pick(C(0xE9E6E1), C(0xEFEBE4), C(0xDCD7CF));
|
var table = Pick(C(0xE9E6E1), C(0xEFEBE4), C(0xDCD7CF));
|
||||||
Rect(0, 0, w, h, table);
|
Rect(0, 0, w, h, table);
|
||||||
using (var line = new SKPaint { IsAntialias = true, Color = Mix(table, SKColors.Black, 0.08f), StrokeWidth = Math.Max(2, w * 0.004f) })
|
var grooves = Mix(table, Color.Black, 0.08f);
|
||||||
|
for (var y = h * 0.12f; y < h; y += h * 0.16f)
|
||||||
{
|
{
|
||||||
for (var y = h * 0.12f; y < h; y += h * 0.16f)
|
canvas.DrawLine(0, y, w, y + (h * 0.01f), Math.Max(2, w * 0.004f), grooves);
|
||||||
{
|
|
||||||
canvas.DrawLine(0, y, w, y + (h * 0.01f), line);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var r = Math.Min(w, h) * R(0.28f, 0.34f);
|
var r = Math.Min(w, h) * R(0.28f, 0.34f);
|
||||||
var cx = w * R(0.42f, 0.55f);
|
var cx = w * R(0.42f, 0.55f);
|
||||||
var cy = h * R(0.48f, 0.58f);
|
var cy = h * R(0.48f, 0.58f);
|
||||||
using (var shadow = new SKPaint { IsAntialias = true, Color = new SKColor(0, 0, 0, 40), MaskFilter = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, r * 0.06f) })
|
canvas.FillBlurredCircle(cx + (r * 0.04f), cy + (r * 0.06f), r, r * 0.06f, new Color(0, 0, 0, 40));
|
||||||
{
|
|
||||||
canvas.DrawCircle(cx + (r * 0.04f), cy + (r * 0.06f), r, shadow);
|
|
||||||
}
|
|
||||||
|
|
||||||
Circle(cx, cy, r, C(0xFAFAF8));
|
Circle(cx, cy, r, C(0xFAFAF8));
|
||||||
Circle(cx, cy, r * 0.78f, C(0xF0EEEA));
|
Circle(cx, cy, r * 0.78f, C(0xF0EEEA));
|
||||||
@@ -458,24 +443,23 @@ public static class DemoImages
|
|||||||
var cr = Math.Min(w, h) * 0.085f;
|
var cr = Math.Min(w, h) * 0.085f;
|
||||||
Circle(cupX, cupY, cr, C(0xF5F3EF));
|
Circle(cupX, cupY, cr, C(0xF5F3EF));
|
||||||
Circle(cupX, cupY, cr * 0.75f, C(0x5B3A26));
|
Circle(cupX, cupY, cr * 0.75f, C(0x5B3A26));
|
||||||
using var fork = new SKPaint { IsAntialias = true, Color = C(0xC9C6C0), StrokeWidth = Math.Max(3, w * 0.008f), StrokeCap = SKStrokeCap.Round };
|
canvas.DrawLine(cx + (r * 1.18f), cy - (r * 0.5f), cx + (r * 1.18f), cy + (r * 0.75f), Math.Max(3, w * 0.008f), C(0xC9C6C0), LineCap.Round);
|
||||||
canvas.DrawLine(cx + (r * 1.18f), cy - (r * 0.5f), cx + (r * 1.18f), cy + (r * 0.75f), fork);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Portrait()
|
public void Portrait()
|
||||||
{
|
{
|
||||||
var bg = Pick(C(0xB27FC0), C(0xC98F9B), C(0x8FA8C9), C(0xD3A26F), C(0x7FB8A3), C(0xA88FC7));
|
var bg = Pick(C(0xB27FC0), C(0xC98F9B), C(0x8FA8C9), C(0xD3A26F), C(0x7FB8A3), C(0xA88FC7));
|
||||||
Gradient(new SKRect(0, 0, w, h), Mix(bg, SKColors.White, 0.15f), Mix(bg, SKColors.Black, 0.12f));
|
Gradient(new Box(0, 0, w, h), Mix(bg, Color.White, 0.15f), Mix(bg, Color.Black, 0.12f));
|
||||||
var skin = Pick(C(0xD9A27B), C(0xC88A63), C(0xA86F4D), C(0xE8B996), C(0x8D5A3B));
|
var skin = Pick(C(0xD9A27B), C(0xC88A63), C(0xA86F4D), C(0xE8B996), C(0x8D5A3B));
|
||||||
var hair = Pick(C(0x8A4B2A), C(0x3B2A20), C(0xD8B45A), C(0x5A3A22), C(0x1F1B18));
|
var hair = Pick(C(0x8A4B2A), C(0x3B2A20), C(0xD8B45A), C(0x5A3A22), C(0x1F1B18));
|
||||||
var shirt = Pick(C(0xA8B04A), C(0x5F8F57), C(0xB84A4A), C(0x4F6FA8), C(0xE0C35A));
|
var shirt = Pick(C(0xA8B04A), C(0x5F8F57), C(0xB84A4A), C(0x4F6FA8), C(0xE0C35A));
|
||||||
var cx = w * 0.5f;
|
var cx = w * 0.5f;
|
||||||
var unit = Math.Min(w, h * 0.8f);
|
var unit = Math.Min(w, h * 0.8f);
|
||||||
Oval(cx, h * 1.02f, unit * 0.42f, h * 0.32f, shirt);
|
Oval(cx, h * 1.02f, unit * 0.42f, h * 0.32f, shirt);
|
||||||
Rect(cx - (unit * 0.06f), h * 0.52f, unit * 0.12f, h * 0.16f, Mix(skin, SKColors.Black, 0.08f));
|
Rect(cx - (unit * 0.06f), h * 0.52f, unit * 0.12f, h * 0.16f, Mix(skin, Color.Black, 0.08f));
|
||||||
Oval(cx, h * 0.44f, unit * 0.16f, unit * 0.2f, skin);
|
Oval(cx, h * 0.44f, unit * 0.16f, unit * 0.2f, skin);
|
||||||
using var top = new SKPathBuilder();
|
var top = new PathBuilder();
|
||||||
top.AddArc(new SKRect(cx - (unit * 0.17f), (h * 0.44f) - (unit * 0.22f), cx + (unit * 0.17f), (h * 0.44f) + (unit * 0.04f)), 180, 180);
|
top.AddArc(cx - (unit * 0.17f), (h * 0.44f) - (unit * 0.22f), cx + (unit * 0.17f), (h * 0.44f) + (unit * 0.04f), 180, 180);
|
||||||
top.Close();
|
top.Close();
|
||||||
Fill(top, hair);
|
Fill(top, hair);
|
||||||
}
|
}
|
||||||
@@ -484,23 +468,23 @@ public static class DemoImages
|
|||||||
{
|
{
|
||||||
var wall = Pick(C(0xE5DFCF), C(0xE9E2D2), C(0xDCD6C6));
|
var wall = Pick(C(0xE5DFCF), C(0xE9E2D2), C(0xDCD6C6));
|
||||||
var floorY = h * R(0.68f, 0.74f);
|
var floorY = h * R(0.68f, 0.74f);
|
||||||
Gradient(new SKRect(0, 0, w, floorY), Mix(wall, SKColors.White, 0.2f), wall);
|
Gradient(new Box(0, 0, w, floorY), Mix(wall, Color.White, 0.2f), wall);
|
||||||
Gradient(new SKRect(0, floorY, w, h), C(0xC9AE84), C(0xB89A6E));
|
Gradient(new Box(0, floorY, w, h), C(0xC9AE84), C(0xB89A6E));
|
||||||
var winX = w * R(0.25f, 0.45f);
|
var winX = w * R(0.25f, 0.45f);
|
||||||
var winW = w * R(0.26f, 0.34f);
|
var winW = w * R(0.26f, 0.34f);
|
||||||
var winY = h * 0.1f;
|
var winY = h * 0.1f;
|
||||||
var winH = h * 0.38f;
|
var winH = h * 0.38f;
|
||||||
Rect(winX - 6, winY - 6, winW + 12, winH + 12, C(0xF7F7F5));
|
Rect(winX - 6, winY - 6, winW + 12, winH + 12, C(0xF7F7F5));
|
||||||
Gradient(new SKRect(winX, winY, winX + winW, winY + winH), C(0x9CCBEB), C(0xC9E4F4));
|
Gradient(new Box(winX, winY, winX + winW, winY + winH), C(0x9CCBEB), C(0xC9E4F4));
|
||||||
Rect(winX + (winW / 2) - 3, winY, 6, winH, C(0xF7F7F5));
|
Rect(winX + (winW / 2) - 3, winY, 6, winH, C(0xF7F7F5));
|
||||||
Rect(winX, winY + (winH / 2) - 3, winW, 6, C(0xF7F7F5));
|
Rect(winX, winY + (winH / 2) - 3, winW, 6, C(0xF7F7F5));
|
||||||
var sofa = Pick(C(0x6E9F7A), C(0x4E8F86), C(0x8A6A9E), C(0xA05A5A));
|
var sofa = Pick(C(0x6E9F7A), C(0x4E8F86), C(0x8A6A9E), C(0xA05A5A));
|
||||||
var sx = w * R(0.05f, 0.15f);
|
var sx = w * R(0.05f, 0.15f);
|
||||||
var sw = w * R(0.48f, 0.58f);
|
var sw = w * R(0.48f, 0.58f);
|
||||||
Rect(sx, floorY - (h * 0.2f), sw, h * 0.12f, Mix(sofa, SKColors.White, 0.15f), 10);
|
Rect(sx, floorY - (h * 0.2f), sw, h * 0.12f, Mix(sofa, Color.White, 0.15f), 10);
|
||||||
Rect(sx, floorY - (h * 0.1f), sw, h * 0.12f, sofa, 10);
|
Rect(sx, floorY - (h * 0.1f), sw, h * 0.12f, sofa, 10);
|
||||||
var px = w * R(0.75f, 0.85f);
|
var px = w * R(0.75f, 0.85f);
|
||||||
using var pot = new SKPathBuilder();
|
var pot = new PathBuilder();
|
||||||
pot.MoveTo(px - (w * 0.045f), floorY - (h * 0.08f));
|
pot.MoveTo(px - (w * 0.045f), floorY - (h * 0.08f));
|
||||||
pot.LineTo(px + (w * 0.045f), floorY - (h * 0.08f));
|
pot.LineTo(px + (w * 0.045f), floorY - (h * 0.08f));
|
||||||
pot.LineTo(px + (w * 0.035f), floorY + (h * 0.01f));
|
pot.LineTo(px + (w * 0.035f), floorY + (h * 0.01f));
|
||||||
@@ -518,34 +502,34 @@ public static class DemoImages
|
|||||||
|
|
||||||
public void Bokeh()
|
public void Bokeh()
|
||||||
{
|
{
|
||||||
Gradient(new SKRect(0, 0, w, h), C(0x1B1530), Pick(C(0x2A1E3A), C(0x1E1A2E)));
|
Gradient(new Box(0, 0, w, h), C(0x1B1530), Pick(C(0x2A1E3A), C(0x1E1A2E)));
|
||||||
var colors = new[] { C(0xF2B84B), C(0xE0567A), C(0x6BC5E8), C(0xB06BE0), C(0xF08A4B), C(0x7FD38A) };
|
var colors = new[] { C(0xF2B84B), C(0xE0567A), C(0x6BC5E8), C(0xB06BE0), C(0xF08A4B), C(0x7FD38A) };
|
||||||
var size = Math.Max(w, h);
|
var size = Math.Max(w, h);
|
||||||
for (var i = 0; i < 40; i++)
|
for (var i = 0; i < 40; i++)
|
||||||
{
|
{
|
||||||
var color = colors[random.Next(colors.Length)].WithAlpha((byte)R(90, 200));
|
var color = colors[random.Next(colors.Length)].WithAlpha((byte)R(90, 200));
|
||||||
using var paint = new SKPaint { IsAntialias = true, Color = color, MaskFilter = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, size * R(0.004f, 0.012f)) };
|
var sigma = size * R(0.004f, 0.012f);
|
||||||
canvas.DrawCircle(R(0, 1) * w, R(0, 1) * h, size * R(0.02f, 0.06f), paint);
|
var x = R(0, 1) * w;
|
||||||
|
var y = R(0, 1) * h;
|
||||||
|
canvas.FillBlurredCircle(x, y, size * R(0.02f, 0.06f), sigma, color);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Concert()
|
public void Concert()
|
||||||
{
|
{
|
||||||
Gradient(new SKRect(0, 0, w, h), C(0x14121C), C(0x1E1A2A));
|
Gradient(new Box(0, 0, w, h), C(0x14121C), C(0x1E1A2A));
|
||||||
var beams = new[] { C(0xE04A5A), C(0xF2C14B), C(0x4A7FE0), C(0xA04AE0), C(0x4AC0E0) };
|
var beams = new[] { C(0xE04A5A), C(0xF2C14B), C(0x4A7FE0), C(0xA04AE0), C(0x4AC0E0) };
|
||||||
for (var i = 0; i < 5; i++)
|
for (var i = 0; i < 5; i++)
|
||||||
{
|
{
|
||||||
var x = w * (0.12f + (i * 0.19f)) + R(-0.04f, 0.04f) * w;
|
var x = w * (0.12f + (i * 0.19f)) + R(-0.04f, 0.04f) * w;
|
||||||
var color = beams[random.Next(beams.Length)];
|
var color = beams[random.Next(beams.Length)];
|
||||||
using var paint = new SKPaint { IsAntialias = true };
|
var light = new LinearGradientBrush(new Vector2(0, 0), new Vector2(0, h * 0.75f), [color.WithAlpha(40), color.WithAlpha(190)]);
|
||||||
paint.Shader = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, h * 0.75f), [color.WithAlpha(40), color.WithAlpha(190)], null, SKShaderTileMode.Clamp);
|
var beam = new PathBuilder();
|
||||||
using var beam = new SKPathBuilder();
|
|
||||||
beam.MoveTo(x, 0);
|
beam.MoveTo(x, 0);
|
||||||
beam.LineTo(x + (w * R(-0.12f, 0.12f)) + (w * 0.08f), h * 0.75f);
|
beam.LineTo(x + (w * R(-0.12f, 0.12f)) + (w * 0.08f), h * 0.75f);
|
||||||
beam.LineTo(x + (w * R(-0.12f, 0.12f)) - (w * 0.08f), h * 0.75f);
|
beam.LineTo(x + (w * R(-0.12f, 0.12f)) - (w * 0.08f), h * 0.75f);
|
||||||
beam.Close();
|
beam.Close();
|
||||||
using var beamPath = beam.Detach();
|
canvas.Fill(beam, light);
|
||||||
canvas.DrawPath(beamPath, paint);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Rect(0, h * 0.72f, w, h * 0.04f, C(0x2B2838));
|
Rect(0, h * 0.72f, w, h * 0.04f, C(0x2B2838));
|
||||||
@@ -560,7 +544,7 @@ public static class DemoImages
|
|||||||
public void Houses()
|
public void Houses()
|
||||||
{
|
{
|
||||||
var sky = Pick(C(0x8CC4E8), C(0x9CCDEB));
|
var sky = Pick(C(0x8CC4E8), C(0x9CCDEB));
|
||||||
Gradient(new SKRect(0, 0, w, h), sky, Mix(sky, SKColors.White, 0.4f));
|
Gradient(new Box(0, 0, w, h), sky, Mix(sky, Color.White, 0.4f));
|
||||||
var facades = new[] { C(0xF2C55C), C(0xE88B6A), C(0xF0A3A0), C(0xE5D37A), C(0xD9774F), C(0x9FC7B4), C(0xF4E2B8) };
|
var facades = new[] { C(0xF2C55C), C(0xE88B6A), C(0xF0A3A0), C(0xE5D37A), C(0xD9774F), C(0x9FC7B4), C(0xF4E2B8) };
|
||||||
var x = 0f;
|
var x = 0f;
|
||||||
while (x < w)
|
while (x < w)
|
||||||
@@ -569,7 +553,7 @@ public static class DemoImages
|
|||||||
var top = h * R(0.12f, 0.4f);
|
var top = h * R(0.12f, 0.4f);
|
||||||
var color = facades[random.Next(facades.Length)];
|
var color = facades[random.Next(facades.Length)];
|
||||||
Rect(x, top, fw, h - top, color);
|
Rect(x, top, fw, h - top, color);
|
||||||
Rect(x, top, fw, h * 0.02f, Mix(color, SKColors.Black, 0.2f));
|
Rect(x, top, fw, h * 0.02f, Mix(color, Color.Black, 0.2f));
|
||||||
var cell = fw / 5;
|
var cell = fw / 5;
|
||||||
for (var wy = top + (cell * 0.8f); wy < h - cell; wy += cell * 1.4f)
|
for (var wy = top + (cell * 0.8f); wy < h - cell; wy += cell * 1.4f)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using Febe.Core.Abstractions;
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Drawing;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
using Febe.Web.Api;
|
using Febe.Web.Api;
|
||||||
@@ -8,7 +10,6 @@ using Febe.Web.Connection;
|
|||||||
using Febe.Web.Engine;
|
using Febe.Web.Engine;
|
||||||
using Febe.Web.Library;
|
using Febe.Web.Library;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using SkiaSharp;
|
|
||||||
|
|
||||||
namespace Febe.Web.Demo;
|
namespace Febe.Web.Demo;
|
||||||
|
|
||||||
@@ -90,18 +91,18 @@ public sealed class DemoBrowserPreview(IHttpContextAccessor accessor, DemoWorld
|
|||||||
|
|
||||||
const int width = 640;
|
const int width = 640;
|
||||||
const int height = 360;
|
const int height = 360;
|
||||||
using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
using var frame = new RgbaImage(width, height);
|
||||||
using (var canvas = new SKCanvas(bitmap))
|
using (var canvas = new Canvas(frame))
|
||||||
{
|
{
|
||||||
canvas.Clear(new SKColor(0x1A, 0x1A, 0x1A));
|
canvas.Clear(new Color(0x1A, 0x1A, 0x1A));
|
||||||
var tall = height - 40f;
|
var tall = height - 40f;
|
||||||
var wide = tall * 9 / 16;
|
var wide = tall * 9 / 16;
|
||||||
var gap = 26f;
|
var gap = 26f;
|
||||||
var left = (width - (3 * wide) - (2 * gap)) / 2;
|
var left = (width - (3 * wide) - (2 * gap)) / 2;
|
||||||
using var dim = new SKPaint { Color = new SKColor(0, 0, 0, 110) };
|
var dim = new Color(0, 0, 0, 110);
|
||||||
for (var i = 0; i < files.Count; i++)
|
for (var i = 0; i < files.Count; i++)
|
||||||
{
|
{
|
||||||
using var image = SKImage.FromEncodedData(files[i]);
|
using var image = DecodeOrNull(files[i]);
|
||||||
if (image is null)
|
if (image is null)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@@ -112,18 +113,27 @@ public sealed class DemoBrowserPreview(IHttpContextAccessor accessor, DemoWorld
|
|||||||
var h = tall * scale;
|
var h = tall * scale;
|
||||||
var x = left + (i * (wide + gap)) + ((wide - w) / 2);
|
var x = left + (i * (wide + gap)) + ((wide - w) / 2);
|
||||||
var y = (height - h) / 2;
|
var y = (height - h) / 2;
|
||||||
var rect = new SKRect(x, y, x + w, y + h);
|
canvas.DrawImage(image, x, y, w, h);
|
||||||
canvas.DrawImage(image, rect, new SKSamplingOptions(SKCubicResampler.Mitchell));
|
|
||||||
if (i != 1)
|
if (i != 1)
|
||||||
{
|
{
|
||||||
canvas.DrawRect(rect, dim);
|
canvas.FillRect(x, y, w, h, dim);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
using var frame = SKImage.FromBitmap(bitmap);
|
return JpegEncoder.Encode(frame, new JpegEncoderOptions { Quality = 80 });
|
||||||
using var encoded = frame.Encode(SKEncodedImageFormat.Jpeg, 80);
|
}
|
||||||
return encoded.ToArray();
|
|
||||||
|
private static RgbaImage? DecodeOrNull(byte[] bytes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return ImageDecoder.Decode(bytes);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,22 +280,22 @@ internal static class DemoDuplicates
|
|||||||
/// <summary>The picture resized by <paramref name="scale"/> and recompressed: the same photo saved again, smaller.</summary>
|
/// <summary>The picture resized by <paramref name="scale"/> and recompressed: the same photo saved again, smaller.</summary>
|
||||||
public static (byte[] Bytes, int Width, int Height)? Variant(byte[] jpeg, double scale, int quality)
|
public static (byte[] Bytes, int Width, int Height)? Variant(byte[] jpeg, double scale, int quality)
|
||||||
{
|
{
|
||||||
using var image = SKImage.FromEncodedData(jpeg);
|
RgbaImage image;
|
||||||
if (image is null)
|
try
|
||||||
|
{
|
||||||
|
image = ImageDecoder.Decode(jpeg);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var width = Math.Max(16, (int)Math.Round(image.Width * scale));
|
using (image)
|
||||||
var height = Math.Max(16, (int)Math.Round(image.Height * scale));
|
|
||||||
using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
|
|
||||||
using (var canvas = new SKCanvas(bitmap))
|
|
||||||
{
|
{
|
||||||
canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell));
|
var width = Math.Max(16, (int)Math.Round(image.Width * scale));
|
||||||
|
var height = Math.Max(16, (int)Math.Round(image.Height * scale));
|
||||||
|
using var resized = ImageResampler.Resize(image, width, height);
|
||||||
|
return (JpegEncoder.Encode(resized, new JpegEncoderOptions { Quality = quality }), width, height);
|
||||||
}
|
}
|
||||||
|
|
||||||
using var result = SKImage.FromBitmap(bitmap);
|
|
||||||
using var encoded = result.Encode(SKEncodedImageFormat.Jpeg, quality);
|
|
||||||
return (encoded.ToArray(), width, height);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Impostazioni, Informazioni: version and shell, where the guide is (the wiki of the repository), the folders, the
|
// Impostazioni, Informazioni: version and shell, where the guide is (the wiki of the repository), the folders, the
|
||||||
// statement on the risk for the account (spec §1, §15 «che cosa la guida deve dire»), the licenses of what Febe
|
// statement on the risk for the account (spec §1, §15 «che cosa la guida deve dire»), the licenses of what Febe
|
||||||
// carries inside (Archivo OFL, Lucide ISC, SQLite, SkiaSharp, .NET, WebView2).
|
// carries inside (Archivo OFL, Lucide ISC, SQLite, .NET, WebView2). Images (codecs, thumbnails, drawing) are Febe's own code.
|
||||||
|
|
||||||
import { api } from '../core/api.js';
|
import { api } from '../core/api.js';
|
||||||
import { h, icon, fill, brand } from '../core/dom.js';
|
import { h, icon, fill, brand } from '../core/dom.js';
|
||||||
|
|||||||
@@ -143,6 +143,11 @@ export function openViewer({ tile, source, origin, onDeleted }) {
|
|||||||
h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante'))));
|
h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante'))));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (media.damaged) {
|
||||||
|
// Spec §4.6, §8.4: a truncated or damaged photo is never shown half; the file stays, its actions too.
|
||||||
|
fill(stage, h('div.mancante', icon('image', 'l'), h('p', h('b', t('vis.danneggiato'))), h('p', t('vis.danneggiatoTesto'))));
|
||||||
|
return;
|
||||||
|
}
|
||||||
const src = `/api/media/${media.id}/file`;
|
const src = `/api/media/${media.id}/file`;
|
||||||
if (media.kind === 'video') {
|
if (media.kind === 'video') {
|
||||||
fill(stage, h('video', { src, poster: thumb, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata', 'aria-label': t('libreria.tipiTessera.' + entry.kind) }));
|
fill(stage, h('video', { src, poster: thumb, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata', 'aria-label': t('libreria.tipiTessera.' + entry.kind) }));
|
||||||
|
|||||||
@@ -202,6 +202,8 @@
|
|||||||
"elimina": "Elimina dalla libreria",
|
"elimina": "Elimina dalla libreria",
|
||||||
"mancante": "Il file non è sul disco: forse è stato spostato o cancellato fuori da Febe.",
|
"mancante": "Il file non è sul disco: forse è stato spostato o cancellato fuori da Febe.",
|
||||||
"videoMancante": "Il video non è sul disco: qui si vede solo la sua copertina.",
|
"videoMancante": "Il video non è sul disco: qui si vede solo la sua copertina.",
|
||||||
|
"danneggiato": "File danneggiato o incompleto",
|
||||||
|
"danneggiatoTesto": "Febe non riesce a leggere questa foto: forse lo scaricamento o la copia si sono interrotti. Il file resta nella libreria così com'è.",
|
||||||
"tipoFile": "{tipo}, {media} {n} di {totale}",
|
"tipoFile": "{tipo}, {media} {n} di {totale}",
|
||||||
"tipoSingolo": "{tipo}, {media}",
|
"tipoSingolo": "{tipo}, {media}",
|
||||||
"seguito": "Seguito",
|
"seguito": "Seguito",
|
||||||
@@ -841,7 +843,6 @@
|
|||||||
{ "nome": "Archivo", "testo": "carattere, SIL Open Font License 1.1", "file": "/caratteri/LICENZA-OFL.txt" },
|
{ "nome": "Archivo", "testo": "carattere, SIL Open Font License 1.1", "file": "/caratteri/LICENZA-OFL.txt" },
|
||||||
{ "nome": "Lucide", "testo": "icone, licenza ISC", "file": "/icone/LICENZA-ISC.txt" },
|
{ "nome": "Lucide", "testo": "icone, licenza ISC", "file": "/icone/LICENZA-ISC.txt" },
|
||||||
{ "nome": "SQLite e Microsoft.Data.Sqlite", "testo": "database, pubblico dominio e licenza MIT" },
|
{ "nome": "SQLite e Microsoft.Data.Sqlite", "testo": "database, pubblico dominio e licenza MIT" },
|
||||||
{ "nome": "SkiaSharp", "testo": "miniature e impronte delle immagini, licenza MIT" },
|
|
||||||
{ "nome": ".NET e ASP.NET Core", "testo": "licenza MIT" },
|
{ "nome": ".NET e ASP.NET Core", "testo": "licenza MIT" },
|
||||||
{ "nome": "WebView2", "testo": "solo versione Windows, licenza Microsoft" }
|
{ "nome": "WebView2", "testo": "solo versione Windows, licenza Microsoft" }
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
using System.Buffers.Binary;
|
using System.Buffers.Binary;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
using Febe.Desktop.Core;
|
using Febe.Desktop.Core;
|
||||||
using Febe.Tests.Desktop.Support;
|
using Febe.Tests.Desktop.Support;
|
||||||
using SkiaSharp;
|
|
||||||
|
|
||||||
namespace Febe.Tests.Desktop;
|
namespace Febe.Tests.Desktop;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The icon of the Windows application (spec §12, appendix C): the brand mark drawn with SkiaSharp and written by the
|
/// The icon of the Windows application (spec §12, appendix C): the brand mark drawn with Febe's own canvas and written by the
|
||||||
/// hand-made ICO writer, at 16, 24, 32, 48, 64, 128 and 256 pixels. The committed <c>src/Febe.Desktop/Febe.ico</c> must be
|
/// hand-made ICO writer, at 16, 24, 32, 48, 64, 128 and 256 pixels. The committed <c>src/Febe.Desktop/Febe.ico</c> must be
|
||||||
/// what the code draws: <c>FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests</c> writes it again.
|
/// what the code draws: <c>FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests</c> writes it again.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -53,28 +53,28 @@ public sealed class IconTests
|
|||||||
{
|
{
|
||||||
using var image = IcoWriter.Decode(ico, entry);
|
using var image = IcoWriter.Decode(ico, entry);
|
||||||
var s = entry.Size;
|
var s = entry.Size;
|
||||||
Assert.AreEqual(0, image.GetPixel(0, 0).Alpha, $"{s}: transparent corner");
|
Assert.AreEqual(0, image.GetPixel(0, 0).A, $"{s}: transparent corner");
|
||||||
Assert.AreEqual(0, image.GetPixel(s - 1, s - 1).Alpha, $"{s}: transparent corner");
|
Assert.AreEqual(0, image.GetPixel(s - 1, s - 1).A, $"{s}: transparent corner");
|
||||||
|
|
||||||
// Inside the square, away from ring and moon (x=4/32, y=28/32): the accent colour #0F5C8C.
|
// Inside the square, away from ring and moon (x=4/32, y=28/32): the accent colour #0F5C8C.
|
||||||
var accent = image.GetPixel(Scale(4, s), Scale(28, s));
|
var accent = image.GetPixel(Scale(4, s), Scale(28, s));
|
||||||
if (s >= 24)
|
if (s >= 24)
|
||||||
{
|
{
|
||||||
AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), accent, 6, $"{s}: accent");
|
AssertClose(Accent, accent, 6, $"{s}: accent");
|
||||||
}
|
}
|
||||||
|
|
||||||
// The centre of the moon (23.2, 8.8) is white.
|
// The centre of the moon (23.2, 8.8) is white.
|
||||||
var moon = image.GetPixel(Scale(23.2, s), Scale(8.8, s));
|
var moon = image.GetPixel(Scale(23.2, s), Scale(8.8, s));
|
||||||
if (s >= 32)
|
if (s >= 32)
|
||||||
{
|
{
|
||||||
AssertClose(SKColors.White, moon, 10, $"{s}: moon");
|
AssertClose(White, moon, 10, $"{s}: moon");
|
||||||
}
|
}
|
||||||
|
|
||||||
// The centre of the ring (14.5, 17.5) is the accent, not white: it is a ring, not a disc.
|
// The centre of the ring (14.5, 17.5) is the accent, not white: it is a ring, not a disc.
|
||||||
var hole = image.GetPixel(Scale(14.5, s), Scale(17.5, s));
|
var hole = image.GetPixel(Scale(14.5, s), Scale(17.5, s));
|
||||||
if (s >= 32)
|
if (s >= 32)
|
||||||
{
|
{
|
||||||
AssertClose(new SKColor(0x0F, 0x5C, 0x8C, 0xFF), hole, 6, $"{s}: ring hole");
|
AssertClose(Accent, hole, 6, $"{s}: ring hole");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,8 +82,8 @@ public sealed class IconTests
|
|||||||
[TestMethod]
|
[TestMethod]
|
||||||
public void TheWriterRefusesImagesThatAreNotSquareOrTooLarge()
|
public void TheWriterRefusesImagesThatAreNotSquareOrTooLarge()
|
||||||
{
|
{
|
||||||
using var wide = new SKBitmap(32, 16);
|
using var wide = new RgbaImage(32, 16);
|
||||||
using var huge = new SKBitmap(512, 512);
|
using var huge = new RgbaImage(512, 512);
|
||||||
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([wide]));
|
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([wide]));
|
||||||
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([huge]));
|
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([huge]));
|
||||||
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([]));
|
Assert.ThrowsExactly<ArgumentException>(() => IcoWriter.Write([]));
|
||||||
@@ -106,7 +106,7 @@ public sealed class IconTests
|
|||||||
var b = IcoWriter.ReadDirectory(fresh);
|
var b = IcoWriter.ReadDirectory(fresh);
|
||||||
CollectionAssert.AreEqual(b.Select(e => e.Size).ToArray(), a.Select(e => e.Size).ToArray());
|
CollectionAssert.AreEqual(b.Select(e => e.Size).ToArray(), a.Select(e => e.Size).ToArray());
|
||||||
|
|
||||||
// Pixel by pixel, with a small tolerance (antialiasing may differ by a unit between SkiaSharp builds).
|
// Pixel by pixel, with a small tolerance (the drawing is in floating point).
|
||||||
for (var i = 0; i < a.Count; i++)
|
for (var i = 0; i < a.Count; i++)
|
||||||
{
|
{
|
||||||
using var left = IcoWriter.Decode(committed, a[i]);
|
using var left = IcoWriter.Decode(committed, a[i]);
|
||||||
@@ -123,12 +123,16 @@ public sealed class IconTests
|
|||||||
|
|
||||||
private static int Scale(double coordinate, int size) => Math.Clamp((int)Math.Floor(coordinate * size / 32), 0, size - 1);
|
private static int Scale(double coordinate, int size) => Math.Clamp((int)Math.Floor(coordinate * size / 32), 0, size - 1);
|
||||||
|
|
||||||
private static void AssertClose(SKColor expected, SKColor actual, int tolerance, string what)
|
private static readonly (byte R, byte G, byte B, byte A) Accent = (0x0F, 0x5C, 0x8C, 0xFF);
|
||||||
|
|
||||||
|
private static readonly (byte R, byte G, byte B, byte A) White = (0xFF, 0xFF, 0xFF, 0xFF);
|
||||||
|
|
||||||
|
private static void AssertClose((byte R, byte G, byte B, byte A) expected, (byte R, byte G, byte B, byte A) actual, int tolerance, string what)
|
||||||
{
|
{
|
||||||
var ok = Math.Abs(expected.Red - actual.Red) <= tolerance
|
var ok = Math.Abs(expected.R - actual.R) <= tolerance
|
||||||
&& Math.Abs(expected.Green - actual.Green) <= tolerance
|
&& Math.Abs(expected.G - actual.G) <= tolerance
|
||||||
&& Math.Abs(expected.Blue - actual.Blue) <= tolerance
|
&& Math.Abs(expected.B - actual.B) <= tolerance
|
||||||
&& Math.Abs(expected.Alpha - actual.Alpha) <= tolerance;
|
&& Math.Abs(expected.A - actual.A) <= tolerance;
|
||||||
Assert.IsTrue(ok, $"{what}: atteso {expected}, trovato {actual}");
|
Assert.IsTrue(ok, $"{what}: atteso {expected}, trovato {actual}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,5 +19,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<None Include="campioni\**\*" CopyToOutputDirectory="PreserveNewest" />
|
<None Include="campioni\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||||
|
<!-- Immagini di riferimento dei codec di casa (Imaging/Riferimenti/LEGGIMI.md). -->
|
||||||
|
<None Include="Imaging\Riferimenti\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using static Febe.Tests.Imaging.TestImages;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>The in-house BMP decoder on files built by hand: variants the reference set lacks, and damage.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class BmpDecoderTests
|
||||||
|
{
|
||||||
|
private const uint BiRgb = 0;
|
||||||
|
private const uint BiRle8 = 1;
|
||||||
|
private const uint BiRle4 = 2;
|
||||||
|
private const uint BiBitfields = 3;
|
||||||
|
private const uint BiJpeg = 4;
|
||||||
|
private const uint BiPng = 5;
|
||||||
|
private const uint BiAlphaBitfields = 6;
|
||||||
|
|
||||||
|
// BGRx palette entries: black, red, green, blue.
|
||||||
|
private static readonly byte[] Palette4 = [0, 0, 0, 0, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 0];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TwoBitsPerPixelBottomUp()
|
||||||
|
{
|
||||||
|
// 3×2, stride 4 bytes; the first row in the file is the bottom one. Top row 0 1 2, bottom row 3 2 1.
|
||||||
|
byte[] pixels = [0b11_10_01_00, 0, 0, 0, 0b00_01_10_00, 0, 0, 0];
|
||||||
|
using var image = BmpDecoder.Decode(Bmp(40, 3, 2, 2, BiRgb, Palette4, pixels));
|
||||||
|
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0));
|
||||||
|
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(2, 0));
|
||||||
|
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 1));
|
||||||
|
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(1, 1));
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(2, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ACoreHeaderHasThreeBytePaletteEntries()
|
||||||
|
{
|
||||||
|
byte[] palette = [10, 20, 30, 40, 50, 60];
|
||||||
|
byte[] pixels = [0b0100_0000, 0, 0, 0];
|
||||||
|
using var image = BmpDecoder.Decode(Bmp(12, 3, 1, 1, BiRgb, palette, pixels));
|
||||||
|
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((60, 50, 40, 255), image.GetPixel(1, 0));
|
||||||
|
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(2, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ACoreHeaderHeightIsUnsignedAndBottomUp()
|
||||||
|
{
|
||||||
|
// bcHeight 40000 is 0x9C40, which a signed read takes for −25536 (top-down, wrong size). One-bit pixels,
|
||||||
|
// rows of 4 bytes: the first row in the file is the bottom of the picture and the only one with index 1.
|
||||||
|
const int height = 40_000;
|
||||||
|
byte[] palette = [10, 20, 30, 40, 50, 60];
|
||||||
|
var pixels = new byte[height * 4];
|
||||||
|
pixels[0] = 0b1000_0000;
|
||||||
|
var bmp = Bmp(12, 1, height, 1, BiRgb, palette, pixels);
|
||||||
|
Assert.AreEqual((1, height), (BmpDecoder.Identify(bmp).Width, BmpDecoder.Identify(bmp).Height));
|
||||||
|
using var image = BmpDecoder.Decode(bmp);
|
||||||
|
Assert.AreEqual((1, height), (image.Width, image.Height));
|
||||||
|
Assert.AreEqual((60, 50, 40, 255), image.GetPixel(0, height - 1), "la prima riga del file è in fondo");
|
||||||
|
Assert.AreEqual((30, 20, 10, 255), image.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SixteenBitsWithFourMasksAfterAnInformationHeader()
|
||||||
|
{
|
||||||
|
// ARGB 4444: a = 8 → 136, r = 15 → 255, g = 0, b = 15 → 255.
|
||||||
|
byte[] masks = [0x00, 0x0F, 0, 0, 0xF0, 0x00, 0, 0, 0x0F, 0x00, 0, 0, 0x00, 0xF0, 0, 0];
|
||||||
|
byte[] pixels = [0x0F, 0x8F, 0x00, 0x00];
|
||||||
|
using var image = BmpDecoder.Decode(Bmp(40, 1, 1, 16, BiAlphaBitfields, masks, pixels), out var info);
|
||||||
|
Assert.IsTrue(info.HasAlpha);
|
||||||
|
Assert.AreEqual((255, 0, 255, 136), image.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ThirtyTwoBitsWithMasksInAnyOrder()
|
||||||
|
{
|
||||||
|
// V4 header with masks for R G B A in memory order: bytes are R, G, B, A.
|
||||||
|
byte[] pixels = [1, 2, 3, 4, 250, 251, 252, 253];
|
||||||
|
var bmp = Bmp(108, 2, -1, 32, BiBitfields, [], pixels, masks: [0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000]);
|
||||||
|
using var image = BmpDecoder.Decode(bmp);
|
||||||
|
Assert.AreEqual((1, 2, 3, 4), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((250, 251, 252, 253), image.GetPixel(1, 0));
|
||||||
|
|
||||||
|
// BI_RGB ignores the alpha byte, even with a V4 header.
|
||||||
|
using var opaque = BmpDecoder.Decode(Bmp(108, 2, -1, 32, BiRgb, [], pixels));
|
||||||
|
Assert.AreEqual((3, 2, 1, 255), opaque.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RleDeltasAndLineEndsLeaveTheSkippedPixelsTransparent()
|
||||||
|
{
|
||||||
|
byte[] palette = [0, 0, 255, 0, 255, 0, 0, 0]; // BGRx: red, blue
|
||||||
|
byte[] data = [2, 1, 0, 0, 0, 2, 1, 1, 1, 0, 0, 1];
|
||||||
|
using var image = BmpDecoder.Decode(Bmp(40, 4, 3, 8, BiRle8, palette, data, colorsUsed: 2));
|
||||||
|
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 2), "riga in basso, indice 1");
|
||||||
|
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(1, 2));
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(2, 2));
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 1), "riga saltata dallo spostamento");
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0), "dopo lo spostamento (1, 1), indice 0");
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnRle4AbsoluteRunOfOddLengthIsPaddedToAWord()
|
||||||
|
{
|
||||||
|
var palette = Enumerable.Range(0, 16).SelectMany(i => new byte[] { 0, 0, (byte)(i * 16), 0 }).ToArray();
|
||||||
|
byte[] data = [0, 5, 0x12, 0x34, 0x50, 0, 2, 0x67, 0, 1];
|
||||||
|
using var image = BmpDecoder.Decode(Bmp(40, 7, 1, 4, BiRle4, palette, data));
|
||||||
|
byte[] expected = [1, 2, 3, 4, 5, 6, 7];
|
||||||
|
for (var x = 0; x < expected.Length; x++)
|
||||||
|
{
|
||||||
|
Assert.AreEqual((byte)(expected[x] * 16), image.GetPixel(x, 0).R, $"pixel {x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnIndexBeyondAShortPaletteIsOpaqueBlack()
|
||||||
|
{
|
||||||
|
byte[] palette = [1, 2, 3, 0, 4, 5, 6, 0];
|
||||||
|
byte[] pixels = [1, 5, 0, 0];
|
||||||
|
using var image = BmpDecoder.Decode(Bmp(40, 2, 1, 8, BiRgb, palette, pixels, colorsUsed: 2));
|
||||||
|
Assert.AreEqual((6, 5, 4, 255), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(1, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnEmbeddedPngIsDecodedByThePngDecoder()
|
||||||
|
{
|
||||||
|
using var source = TestImages.Random(5, 3, 8);
|
||||||
|
var png = PngEncoder.Encode(source);
|
||||||
|
var bmp = Bmp(40, 5, 3, 0, BiPng, [], png);
|
||||||
|
using var image = BmpDecoder.Decode(bmp);
|
||||||
|
ImageAssert.AreEqual(source, image, "PNG nel BMP");
|
||||||
|
Assert.AreEqual(ImageFormat.Bmp, BmpDecoder.Identify(bmp).Format);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DamagedOrUnsupportedFilesThrow()
|
||||||
|
{
|
||||||
|
byte[] row = [0, 0, 0, 0];
|
||||||
|
var cases = new Dictionary<string, (byte[] Bytes, bool Unsupported)>
|
||||||
|
{
|
||||||
|
["vuoto"] = ([], false),
|
||||||
|
["non BMP"] = ("BA\0\0"u8.ToArray(), false),
|
||||||
|
["solo l'intestazione del file"] = (Bmp(40, 1, 1, 24, BiRgb, [], row)[..16], false),
|
||||||
|
["intestazione di 20 byte"] = (PatchHeaderSize(Bmp(40, 1, 1, 24, BiRgb, [], row), 20), true),
|
||||||
|
["larghezza zero"] = (Bmp(40, 0, 1, 24, BiRgb, [], row), false),
|
||||||
|
["larghezza negativa"] = (Bmp(40, -3, 1, 24, BiRgb, [], row), false),
|
||||||
|
["7 bit per pixel"] = (Bmp(40, 1, 1, 7, BiRgb, [], row), false),
|
||||||
|
["64 bit per pixel"] = (Bmp(40, 1, 1, 64, BiRgb, [], new byte[8]), true),
|
||||||
|
["JPEG dentro"] = (Bmp(40, 1, 1, 0, BiJpeg, [], [0xFF, 0xD8, 0xFF]), true),
|
||||||
|
["compressione 9"] = (Bmp(40, 1, 1, 24, 9, [], row), true),
|
||||||
|
["RLE8 a 4 bit"] = (Bmp(40, 1, 1, 4, BiRle8, Palette4, [0, 1]), false),
|
||||||
|
["RLE dall'alto"] = (Bmp(40, 1, -1, 8, BiRle8, Palette4, [0, 1]), false),
|
||||||
|
["RLE tagliato"] = (Bmp(40, 4, 2, 8, BiRle8, Palette4, [2, 1, 0]), false),
|
||||||
|
["tratto assoluto tagliato"] = (Bmp(40, 4, 1, 8, BiRle8, Palette4, [0, 4, 1, 2]), false),
|
||||||
|
["pixel tagliati"] = (Bmp(40, 4, 4, 24, BiRgb, [], new byte[40]), false),
|
||||||
|
["maschere non contigue"] = (Bmp(108, 1, 1, 32, BiBitfields, [], row, masks: [0x00FF00FF, 0x0000FF00, 0, 0]), false),
|
||||||
|
["maschere oltre i 16 bit"] = (Bmp(108, 1, 1, 16, BiBitfields, [], row, masks: [0x00FF0000, 0x0000FF00, 0xFF, 0]), false),
|
||||||
|
["maschere mancanti"] = (Bmp(40, 1, 1, 32, BiBitfields, [], [])[..54], false),
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var (name, (bytes, unsupported)) in cases)
|
||||||
|
{
|
||||||
|
if (unsupported)
|
||||||
|
{
|
||||||
|
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => BmpDecoder.Decode(bytes), name);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Assert.Throws<ImageDecodeException>(() => BmpDecoder.Decode(bytes), name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnImageBeyondTheLimitsIsRefusedButStillIdentified()
|
||||||
|
{
|
||||||
|
var bmp = Bmp(40, 100_000, 1, 24, BiRgb, [], new byte[4]);
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => BmpDecoder.Decode(bmp));
|
||||||
|
Assert.AreEqual(100_000, BmpDecoder.Identify(bmp).Width);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] PatchHeaderSize(byte[] bmp, uint size)
|
||||||
|
{
|
||||||
|
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(bmp.AsSpan(14), size);
|
||||||
|
return bmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using static Febe.Tests.Imaging.TestImages;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>The in-house GIF decoder on files built from GIF89a: palettes, transparency, clipping, damage.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class GifDecoderTests
|
||||||
|
{
|
||||||
|
// Four colours: black, red, green, blue.
|
||||||
|
private static readonly byte[] Palette4 = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AFrameOnTheWholeCanvasTakesItsColoursFromTheGlobalPalette()
|
||||||
|
{
|
||||||
|
byte[] indices = [0, 1, 2, 3, 3, 2, 1, 0];
|
||||||
|
var gif = Gif(4, 2, Palette4, GifFrame(0, 0, 4, 2, indices, 2));
|
||||||
|
using var image = GifDecoder.Decode(gif, out var info);
|
||||||
|
Assert.AreEqual((ImageFormat.Gif, 4, 2, 1), (info.Format, info.Width, info.Height, info.FrameCount));
|
||||||
|
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 0));
|
||||||
|
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(3, 0));
|
||||||
|
Assert.AreEqual((0, 255, 0, 255), image.GetPixel(1, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheTransparentIndexAndTheAreaOutsideTheFrameAreTransparent()
|
||||||
|
{
|
||||||
|
byte[] indices = [1, 2, 2, 1];
|
||||||
|
var gif = Gif(4, 3, Palette4, GifControl(2), GifFrame(1, 1, 2, 2, indices, 2));
|
||||||
|
using var image = GifDecoder.Decode(gif);
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(0, 0), "fuori dal fotogramma");
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(1, 1));
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(2, 1), "indice trasparente");
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(2, 2));
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(3, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheTransparencyOfALaterControlBlockDoesNotChangeTheFirstFrame()
|
||||||
|
{
|
||||||
|
byte[] indices = [1, 2];
|
||||||
|
var gif = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2));
|
||||||
|
using var image = GifDecoder.Decode(gif, out var info);
|
||||||
|
Assert.AreEqual(2, info.FrameCount);
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ALocalPaletteWinsOverTheGlobalOne()
|
||||||
|
{
|
||||||
|
byte[] local = [9, 9, 9, 7, 7, 7];
|
||||||
|
var gif = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, [0, 1], 2, local));
|
||||||
|
using var image = GifDecoder.Decode(gif);
|
||||||
|
Assert.AreEqual((9, 9, 9, 255), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((7, 7, 7, 255), image.GetPixel(1, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AFrameLargerThanTheCanvasIsClippedAndAnEmptyCanvasTakesTheFrameSize()
|
||||||
|
{
|
||||||
|
var indices = Enumerable.Range(0, 12).Select(i => (byte)(i % 4)).ToArray();
|
||||||
|
using (var clipped = GifDecoder.Decode(Gif(3, 2, Palette4, GifFrame(1, 0, 4, 3, indices, 2))))
|
||||||
|
{
|
||||||
|
Assert.AreEqual((3, 2), (clipped.Width, clipped.Height));
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), clipped.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((0, 0, 0, 255), clipped.GetPixel(1, 0));
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), clipped.GetPixel(2, 0));
|
||||||
|
Assert.AreEqual((0, 0, 0, 255), clipped.GetPixel(1, 1), "riga 1 del fotogramma, colonna 0: indice 4 % 4");
|
||||||
|
}
|
||||||
|
|
||||||
|
using var sized = GifDecoder.Decode(Gif(0, 0, Palette4, GifFrame(2, 1, 4, 3, indices, 2)));
|
||||||
|
Assert.AreEqual((6, 4), (sized.Width, sized.Height));
|
||||||
|
Assert.AreEqual((0, 0, 255, 255), sized.GetPixel(5, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void InterlacedRowsGoWhereTheFourPassesPutThem()
|
||||||
|
{
|
||||||
|
for (var height = 1; height <= 40; height++)
|
||||||
|
{
|
||||||
|
var rows = Enumerable.Range(0, height).Select(r => GifDecoder.InterlacedRow(r, height)).ToList();
|
||||||
|
CollectionAssert.AreEquivalent(Enumerable.Range(0, height).ToList(), rows, $"altezza {height}");
|
||||||
|
}
|
||||||
|
|
||||||
|
CollectionAssert.AreEqual(new[] { 0, 8, 4, 2, 6, 1, 3, 5, 7, 9 }, Enumerable.Range(0, 10).Select(r => GifDecoder.InterlacedRow(r, 10)).ToArray());
|
||||||
|
|
||||||
|
// Row r of the file holds the colour of its own image row: decoding puts each one back in place.
|
||||||
|
const int height10 = 10;
|
||||||
|
var indices = new byte[2 * height10];
|
||||||
|
for (var r = 0; r < height10; r++)
|
||||||
|
{
|
||||||
|
indices[2 * r] = indices[(2 * r) + 1] = (byte)GifDecoder.InterlacedRow(r, height10);
|
||||||
|
}
|
||||||
|
|
||||||
|
var palette = Enumerable.Range(0, 16).SelectMany(i => new[] { (byte)(i * 10), (byte)0, (byte)0 }).ToArray();
|
||||||
|
using var image = GifDecoder.Decode(Gif(2, height10, palette, GifFrame(0, 0, 2, height10, indices, 4, interlaced: true)));
|
||||||
|
for (var y = 0; y < height10; y++)
|
||||||
|
{
|
||||||
|
Assert.AreEqual((byte)(y * 10), image.GetPixel(1, y).R, $"riga {y}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LiteralCodesAtEveryInitialSizeDecode()
|
||||||
|
{
|
||||||
|
for (var minCodeSize = 2; minCodeSize <= 8; minCodeSize++)
|
||||||
|
{
|
||||||
|
var colours = 1 << minCodeSize;
|
||||||
|
var random = new Random(minCodeSize);
|
||||||
|
var indices = new byte[37 * 23];
|
||||||
|
for (var i = 0; i < indices.Length; i++)
|
||||||
|
{
|
||||||
|
indices[i] = (byte)random.Next(colours);
|
||||||
|
}
|
||||||
|
|
||||||
|
var output = new byte[indices.Length];
|
||||||
|
var data = GifLiteralLzw(indices, minCodeSize);
|
||||||
|
Assert.AreEqual(indices.Length, GifDecoder.DecodeLzw(data, 0, minCodeSize, output), $"codici da {minCodeSize + 1} bit");
|
||||||
|
CollectionAssert.AreEqual(indices, output, $"codici da {minCodeSize + 1} bit");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DataThatStopsEarlyLeavesTheRestTransparent()
|
||||||
|
{
|
||||||
|
var indices = Enumerable.Repeat((byte)1, 16).ToArray();
|
||||||
|
var full = Gif(4, 4, Palette4, GifFrame(0, 0, 4, 4, indices, 2));
|
||||||
|
|
||||||
|
// Cut inside the LZW data, before the end code: the first pixels are there, the others are not.
|
||||||
|
var cut = full[..(full.Length - 6)];
|
||||||
|
using var image = GifDecoder.Decode(cut);
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((0, 0, 0, 0), image.GetPixel(3, 3));
|
||||||
|
|
||||||
|
// Every shorter file either fails cleanly or gives an image of the canvas size.
|
||||||
|
for (var length = 0; length < full.Length; length++)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var partial = GifDecoder.Decode(full[..length]);
|
||||||
|
Assert.AreEqual((4, 4), (partial.Width, partial.Height), $"tagliato a {length}");
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void CommentsBeforeTheFirstFrameAreMetadataAndOtherExtensionsAreSkipped()
|
||||||
|
{
|
||||||
|
byte[] comment = [0x21, 0xFE, 5, (byte)'C', (byte)'i', (byte)'a', (byte)'o', (byte)' ', 3, (byte)'G', (byte)'I', (byte)'F', 0];
|
||||||
|
byte[] netscape = [0x21, 0xFF, 11, .. "NETSCAPE2.0"u8, 3, 1, 0, 0, 0];
|
||||||
|
var gif = Gif(1, 1, Palette4, comment, netscape, GifFrame(0, 0, 1, 1, [3], 2));
|
||||||
|
var info = GifDecoder.Identify(gif);
|
||||||
|
Assert.AreEqual("Ciao GIF", info.Metadata.Texts.Single().Text);
|
||||||
|
using var image = GifDecoder.Decode(gif);
|
||||||
|
Assert.AreEqual((0, 0, 255, 255), image.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DamagedFilesThrowAnImageDecodeException()
|
||||||
|
{
|
||||||
|
var frame = GifFrame(0, 0, 1, 1, [1], 2);
|
||||||
|
var badCodeSize = frame.ToArray();
|
||||||
|
badCodeSize[10] = 12;
|
||||||
|
var cases = new Dictionary<string, byte[]>
|
||||||
|
{
|
||||||
|
["vuoto"] = [],
|
||||||
|
["non GIF"] = "GIF90a"u8.ToArray(),
|
||||||
|
["senza schermo logico"] = "GIF89a\x01\0"u8.ToArray(),
|
||||||
|
["senza fotogrammi"] = Gif(1, 1, Palette4),
|
||||||
|
["senza tavolozza"] = Gif(1, 1, null, frame),
|
||||||
|
["codici LZW da 13 bit"] = Gif(1, 1, Palette4, badCodeSize),
|
||||||
|
["tavolozza globale tagliata"] = Gif(1, 1, Palette4)[..20],
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var (name, bytes) in cases)
|
||||||
|
{
|
||||||
|
Assert.Throws<ImageDecodeException>(() => GifDecoder.Decode(bytes), name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ACanvasBeyondTheLimitsIsRefusedButStillIdentified()
|
||||||
|
{
|
||||||
|
var gif = Gif(60000, 60000, Palette4, GifFrame(0, 0, 1, 1, [1], 2));
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => GifDecoder.Decode(gif));
|
||||||
|
Assert.AreEqual((60000, 60000), (GifDecoder.Identify(gif).Width, GifDecoder.Identify(gif).Height));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>Comparisons of decoded images that say where they differ.</summary>
|
||||||
|
internal static class ImageAssert
|
||||||
|
{
|
||||||
|
/// <summary>Same size and the same bytes in every pixel.</summary>
|
||||||
|
public static void AreEqual(RgbaImage expected, RgbaImage actual, string what)
|
||||||
|
{
|
||||||
|
Assert.AreEqual((expected.Width, expected.Height), (actual.Width, actual.Height), $"{what}: misura diversa.");
|
||||||
|
AreEqual(expected.Width, expected.Pixels, actual.Pixels, what);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The same RGBA bytes, for images of the given width.</summary>
|
||||||
|
public static void AreEqual(int width, ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual, string what)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(expected.Length, actual.Length, $"{what}: lunghezza diversa.");
|
||||||
|
var first = -1;
|
||||||
|
var different = 0;
|
||||||
|
for (var i = 0; i < expected.Length; i += 4)
|
||||||
|
{
|
||||||
|
if (!expected.Slice(i, 4).SequenceEqual(actual.Slice(i, 4)))
|
||||||
|
{
|
||||||
|
different++;
|
||||||
|
if (first < 0)
|
||||||
|
{
|
||||||
|
first = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (different > 0)
|
||||||
|
{
|
||||||
|
var pixel = first / 4;
|
||||||
|
Assert.Fail(
|
||||||
|
$"{what}: {different} pixel diversi; il primo in ({pixel % width}, {pixel / width}): atteso "
|
||||||
|
+ $"{Format(expected.Slice(first, 4))}, letto {Format(actual.Slice(first, 4))}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Format(ReadOnlySpan<byte> rgba) => $"({rgba[0]}, {rgba[1]}, {rgba[2]}, {rgba[3]})";
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Damaged files from the reference set, changed at random with fixed seeds: a decoder either reads them or throws
|
||||||
|
/// <see cref="ImageDecodeException"/>, never anything else (no index out of range, no overflow, no huge allocation).
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ImageFuzzTests
|
||||||
|
{
|
||||||
|
private const int MutationsPerFile = 120;
|
||||||
|
|
||||||
|
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> Formats =>
|
||||||
|
[
|
||||||
|
[ReferenceFormat.Png],
|
||||||
|
[ReferenceFormat.Gif],
|
||||||
|
[ReferenceFormat.Bmp],
|
||||||
|
[ReferenceFormat.Jpeg],
|
||||||
|
[ReferenceFormat.WebP],
|
||||||
|
];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(Formats))]
|
||||||
|
public void ChangedBytesNeverBreakTheDecoder(ReferenceFormat format)
|
||||||
|
{
|
||||||
|
var seed = 1000 + (int)format;
|
||||||
|
foreach (var reference in ReferenceImages.Of(format))
|
||||||
|
{
|
||||||
|
var original = reference.ReadInput();
|
||||||
|
var random = new Random(seed++);
|
||||||
|
for (var i = 0; i < MutationsPerFile; i++)
|
||||||
|
{
|
||||||
|
var mutated = Mutate(original, random);
|
||||||
|
if (format == ReferenceFormat.Png && random.Next(3) > 0)
|
||||||
|
{
|
||||||
|
// Most changes to a PNG only meet a wrong CRC: fixing it lets them reach the pixels.
|
||||||
|
TestImages.FixPngCrcs(mutated);
|
||||||
|
}
|
||||||
|
|
||||||
|
TryDecode(mutated, $"{reference.Name}, modifica {i}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ChangedBytesNeverBreakTheFacade()
|
||||||
|
{
|
||||||
|
var random = new Random(77);
|
||||||
|
foreach (var reference in ReferenceImages.All)
|
||||||
|
{
|
||||||
|
var mutated = Mutate(reference.ReadInput(), random);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var image = ImageDecoder.Decode(mutated, Small);
|
||||||
|
ImageDecoder.Identify(mutated, Small);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TryDecode(byte[] bytes, string what)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var image = ImageDecoder.Decode(bytes, Small);
|
||||||
|
Assert.IsGreaterThan(0, image.Width, what);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ImageDecoder.Identify(bytes, Small);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Mutate(byte[] original, Random random)
|
||||||
|
{
|
||||||
|
var bytes = original.ToArray();
|
||||||
|
switch (random.Next(4))
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
// A few random bytes anywhere after the signature.
|
||||||
|
for (var k = random.Next(1, 9); k > 0; k--)
|
||||||
|
{
|
||||||
|
bytes[random.Next(Math.Min(8, bytes.Length - 1), bytes.Length)] = (byte)random.Next(256);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
// A byte of the headers set to an extreme.
|
||||||
|
bytes[random.Next(Math.Min(8, bytes.Length - 1), Math.Min(bytes.Length, 80))] = random.Next(2) == 0 ? (byte)0 : (byte)0xFF;
|
||||||
|
return bytes;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
// Cut short.
|
||||||
|
return bytes[..random.Next(1, bytes.Length)];
|
||||||
|
|
||||||
|
default:
|
||||||
|
// A run of bytes flipped.
|
||||||
|
var start = random.Next(8, bytes.Length);
|
||||||
|
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
|
||||||
|
for (var k = 0; k < length; k++)
|
||||||
|
{
|
||||||
|
bytes[start + k] ^= 0x5A;
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,688 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Numerics;
|
||||||
|
using System.Text;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using Febe.Core.Drawing;
|
||||||
|
using Scenes = Febe.Tests.Support.TestImages;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What replaced SkiaSharp around the codecs: the resampler, EXIF orientation, the JPEG decoded smaller, the converter
|
||||||
|
/// that keeps metadata, PNG texts and the anti-aliased rasteriser of <see cref="Canvas"/>.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ImageProcessingTests
|
||||||
|
{
|
||||||
|
// ---- Resampler ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(4000, 3000, 480, 480, 360)]
|
||||||
|
[DataRow(3024, 4032, 480, 360, 480)]
|
||||||
|
[DataRow(100, 50, 480, 100, 50)]
|
||||||
|
[DataRow(5000, 2, 480, 480, 1)]
|
||||||
|
[DataRow(1081, 1081, 480, 480, 480)]
|
||||||
|
public void FitWithinKeepsTheProportionsAndNeverEnlarges(int width, int height, int longSide, int expectedWidth, int expectedHeight) =>
|
||||||
|
Assert.AreEqual((expectedWidth, expectedHeight), ImageResampler.FitWithin(width, height, longSide));
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(ResampleFilter.Lanczos3, false)]
|
||||||
|
[DataRow(ResampleFilter.Lanczos3, true)]
|
||||||
|
[DataRow(ResampleFilter.Area, false)]
|
||||||
|
[DataRow(ResampleFilter.Area, true)]
|
||||||
|
public void AFlatColourStaysFlat(ResampleFilter filter, bool linearLight)
|
||||||
|
{
|
||||||
|
using var source = Flat(301, 199, 40, 120, 210, 255);
|
||||||
|
foreach (var (w, h) in new[] { (100, 66), (37, 211), (602, 398), (1, 1) })
|
||||||
|
{
|
||||||
|
using var result = ImageResampler.Resize(source, w, h, new ResampleOptions { Filter = filter, LinearLight = linearLight });
|
||||||
|
Assert.AreEqual((w, h), (result.Width, result.Height));
|
||||||
|
AssertEveryPixel(result, (40, 120, 210, 255), 1, $"{filter} {w}×{h}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheSameSizeGivesTheSamePixels()
|
||||||
|
{
|
||||||
|
using var source = TestImages.Gradient(64, 48, 3);
|
||||||
|
using var result = ImageResampler.Resize(source, 64, 48);
|
||||||
|
ImageAssert.AreEqual(source, result, "stessa misura");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheAreaFilterAveragesWholeBlocks()
|
||||||
|
{
|
||||||
|
using var source = TestImages.Random(40, 30, 5, opaque: true);
|
||||||
|
using var result = ImageResampler.Resize(source, 20, 15, new ResampleOptions { Filter = ResampleFilter.Area });
|
||||||
|
for (var y = 0; y < 15; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 20; x++)
|
||||||
|
{
|
||||||
|
var actual = result.GetPixel(x, y);
|
||||||
|
for (var channel = 0; channel < 3; channel++)
|
||||||
|
{
|
||||||
|
var sum = 0;
|
||||||
|
for (var dy = 0; dy < 2; dy++)
|
||||||
|
{
|
||||||
|
for (var dx = 0; dx < 2; dx++)
|
||||||
|
{
|
||||||
|
sum += source.GetRow((2 * y) + dy)[(((2 * x) + dx) * 4) + channel];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = channel switch { 0 => actual.R, 1 => actual.G, _ => actual.B };
|
||||||
|
Assert.IsLessThanOrEqualTo(1.0, Math.Abs(value - (sum / 4.0)), $"({x}, {y}) canale {channel}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TransparentPixelsLendNoColour()
|
||||||
|
{
|
||||||
|
// Left half transparent black-ish noise, right half opaque orange: averaging premultiplied, the edge stays orange.
|
||||||
|
var pixels = new byte[64 * 16 * 4];
|
||||||
|
new Random(7).NextBytes(pixels);
|
||||||
|
for (var y = 0; y < 16; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 64; x++)
|
||||||
|
{
|
||||||
|
var i = ((y * 64) + x) * 4;
|
||||||
|
if (x < 32)
|
||||||
|
{
|
||||||
|
pixels[i + 3] = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
(pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]) = (250, 140, 20, 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
using var source = new RgbaImage(64, 16, pixels);
|
||||||
|
using var result = ImageResampler.Resize(source, 16, 4);
|
||||||
|
for (var y = 0; y < 4; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 16; x++)
|
||||||
|
{
|
||||||
|
var p = result.GetPixel(x, y);
|
||||||
|
if (p.A >= 8)
|
||||||
|
{
|
||||||
|
Assert.IsLessThanOrEqualTo(2, Math.Abs(p.R - 250), $"({x}, {y}) {p}");
|
||||||
|
Assert.IsLessThanOrEqualTo(2, Math.Abs(p.G - 140), $"({x}, {y}) {p}");
|
||||||
|
Assert.IsLessThanOrEqualTo(2, Math.Abs(p.B - 20), $"({x}, {y}) {p}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LinearLightAveragesTheLightNotTheCodes()
|
||||||
|
{
|
||||||
|
// Black and white stripes one pixel wide: half the light is sRGB 188, half the code is 128.
|
||||||
|
using var stripes = new RgbaImage(64, 8);
|
||||||
|
for (var y = 0; y < 8; y++)
|
||||||
|
{
|
||||||
|
var row = stripes.GetRow(y);
|
||||||
|
for (var x = 0; x < 64; x++)
|
||||||
|
{
|
||||||
|
var v = (byte)((x & 1) == 0 ? 0 : 255);
|
||||||
|
(row[x * 4], row[(x * 4) + 1], row[(x * 4) + 2], row[(x * 4) + 3]) = (v, v, v, 255);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
using var codes = ImageResampler.Resize(stripes, 16, 2, new ResampleOptions { Filter = ResampleFilter.Area });
|
||||||
|
using var light = ImageResampler.Resize(stripes, 16, 2, new ResampleOptions { Filter = ResampleFilter.Area, LinearLight = true });
|
||||||
|
Assert.IsLessThanOrEqualTo(1, Math.Abs(codes.GetPixel(8, 1).R - 128));
|
||||||
|
Assert.IsLessThanOrEqualTo(1, Math.Abs(light.GetPixel(8, 1).R - 188));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LanczosReducesFaithfully()
|
||||||
|
{
|
||||||
|
using var scene = Scenes.Scene(4, 1600, 1200);
|
||||||
|
using var lanczos = ImageResampler.Resize(scene, 400, 300);
|
||||||
|
using var area = ImageResampler.Resize(scene, 400, 300, new ResampleOptions { Filter = ResampleFilter.Area });
|
||||||
|
var quality = ImageQuality.Compare(area, lanczos);
|
||||||
|
Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Orientation ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryOrientationIsShownAsTheSpecificationSays()
|
||||||
|
{
|
||||||
|
using var stored = TestImages.Random(7, 4, 11);
|
||||||
|
for (var orientation = 1; orientation <= 8; orientation++)
|
||||||
|
{
|
||||||
|
using var expected = ImageQuality.Orient(stored, orientation);
|
||||||
|
var shown = ImageOrientation.Apply(stored, orientation);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ImageAssert.AreEqual(expected, shown, $"orientamento {orientation}");
|
||||||
|
Assert.AreEqual((expected.Width, expected.Height), ImageOrientation.ShownSize(7, 4, orientation));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (!ReferenceEquals(shown, stored))
|
||||||
|
{
|
||||||
|
shown.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UprightIsTheSameImageAndInvalidValuesCountAsUpright()
|
||||||
|
{
|
||||||
|
using var stored = TestImages.Random(5, 3, 2);
|
||||||
|
Assert.AreSame(stored, ImageOrientation.Apply(stored, 1));
|
||||||
|
Assert.AreEqual((5, 3), ImageOrientation.ShownSize(5, 3, 0));
|
||||||
|
Assert.AreEqual((5, 3), ImageOrientation.ShownSize(5, 3, 9));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- JPEG decoded smaller ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(1)]
|
||||||
|
[DataRow(2)]
|
||||||
|
[DataRow(3)]
|
||||||
|
public void AJpegDecodedSmallerLooksLikeTheFullDecodeReduced(int reduction)
|
||||||
|
{
|
||||||
|
using var scene = Scenes.Scene(5, 803, 601);
|
||||||
|
foreach (var subsampling in new[] { JpegSubsampling.Ratio420, JpegSubsampling.Ratio444 })
|
||||||
|
{
|
||||||
|
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 92, Subsampling = subsampling });
|
||||||
|
using var small = JpegDecoder.DecodeReduced(jpeg, reduction, out var info);
|
||||||
|
var scale = 1 << reduction;
|
||||||
|
Assert.AreEqual(((803 + scale - 1) / scale, (601 + scale - 1) / scale), (small.Width, small.Height), $"1/{scale}");
|
||||||
|
Assert.AreEqual((803, 601), (info.Width, info.Height), "le misure dichiarate restano quelle del file");
|
||||||
|
|
||||||
|
using var full = JpegDecoder.Decode(jpeg);
|
||||||
|
using var expected = ImageResampler.Resize(full, small.Width, small.Height, new ResampleOptions { Filter = ResampleFilter.Area });
|
||||||
|
var quality = ImageQuality.Compare(expected, small);
|
||||||
|
Assert.IsGreaterThan(reduction == 3 ? 24.0 : 27.0, quality.MinPsnr, $"1/{scale} {subsampling}: {quality}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheReducedTransformIsTheMeanOfTheFullOne()
|
||||||
|
{
|
||||||
|
// InverseReduced computes the means of 2×2 and 4×4 squares of the full inverse straight from the
|
||||||
|
// coefficients; checked against the T.81 definition in double precision, averaged, then rounded and clamped.
|
||||||
|
var random = new Random(91);
|
||||||
|
var quantization = new ushort[64];
|
||||||
|
var block = new short[64];
|
||||||
|
Span<byte> output = stackalloc byte[16];
|
||||||
|
for (var round = 0; round < 400; round++)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 64; i++)
|
||||||
|
{
|
||||||
|
quantization[i] = (ushort)random.Next(1, 24);
|
||||||
|
|
||||||
|
// Mostly small coefficients, some zero rows and columns, now and then a large one.
|
||||||
|
var zero = random.Next(4) == 0 || (round % 5 == 0 && i >= 8);
|
||||||
|
block[i] = zero ? (short)0 : (short)random.Next(-40, 41);
|
||||||
|
}
|
||||||
|
|
||||||
|
block[0] = (short)random.Next(-60, 61);
|
||||||
|
var full = new double[64];
|
||||||
|
for (var y = 0; y < 8; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 8; x++)
|
||||||
|
{
|
||||||
|
double sum = 0;
|
||||||
|
for (var v = 0; v < 8; v++)
|
||||||
|
{
|
||||||
|
for (var u = 0; u < 8; u++)
|
||||||
|
{
|
||||||
|
var cu = u == 0 ? 1 / Math.Sqrt(2) : 1;
|
||||||
|
var cv = v == 0 ? 1 / Math.Sqrt(2) : 1;
|
||||||
|
sum += cu * cv * block[(v * 8) + u] * quantization[(v * 8) + u]
|
||||||
|
* Math.Cos(((2 * x) + 1) * u * Math.PI / 16) * Math.Cos(((2 * y) + 1) * v * Math.PI / 16);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
full[(y * 8) + x] = (sum / 4) + 128;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var shift in new[] { 1, 2 })
|
||||||
|
{
|
||||||
|
var n = 8 >> shift;
|
||||||
|
var side = 1 << shift;
|
||||||
|
JpegDct.InverseReduced(block, quantization, output, n, 8, [], shift);
|
||||||
|
for (var y = 0; y < n; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < n; x++)
|
||||||
|
{
|
||||||
|
double mean = 0;
|
||||||
|
for (var dy = 0; dy < side; dy++)
|
||||||
|
{
|
||||||
|
for (var dx = 0; dx < side; dx++)
|
||||||
|
{
|
||||||
|
mean += full[(((y * side) + dy) * 8) + (x * side) + dx];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var expected = Math.Clamp((int)Math.Floor((mean / (side * side)) + 0.5), 0, 255);
|
||||||
|
Assert.IsLessThanOrEqualTo(1, Math.Abs(expected - output[(y * n) + x]), $"giro {round}, 1/{side}, ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DecodeAtLeastShrinksOnlyWhileTheLongSideIsEnough()
|
||||||
|
{
|
||||||
|
using var scene = Scenes.Scene(6, 4000, 3000);
|
||||||
|
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 80 });
|
||||||
|
foreach (var (min, expected) in new[] { (4000, 4000), (2000, 2000), (1999, 2000), (960, 1000), (480, 500), (100, 500) })
|
||||||
|
{
|
||||||
|
using var image = ImageDecoder.DecodeAtLeast(jpeg, min, out _);
|
||||||
|
Assert.AreEqual(expected, image.Width, $"almeno {min}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Formats without a reduced decode come back whole.
|
||||||
|
var png = PngEncoder.Encode(TestImages.Random(300, 200, 1, opaque: true));
|
||||||
|
using var whole = ImageDecoder.DecodeAtLeast(png, 50, out _);
|
||||||
|
Assert.AreEqual(300, whole.Width);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Converter ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AJpegBecomesPngAndWebPWithItsMetadataAndOrientationTag()
|
||||||
|
{
|
||||||
|
using var scene = Scenes.Scene(7, 320, 200);
|
||||||
|
var exif = Tiff(orientation: 6);
|
||||||
|
var icc = Profile(612);
|
||||||
|
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF/></x:xmpmeta>";
|
||||||
|
var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 90, Exif = exif, IccProfile = icc, Xmp = xmp, Comments = ["Gita al lago"] });
|
||||||
|
|
||||||
|
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP })
|
||||||
|
{
|
||||||
|
var result = ImageConverter.Convert(jpeg, target);
|
||||||
|
Assert.AreEqual((ImageFormat.Jpeg, target), (result.Source, result.Target));
|
||||||
|
Assert.IsFalse(result.Lossy);
|
||||||
|
using var back = ImageDecoder.Decode(result.Data, out var info);
|
||||||
|
Assert.AreEqual(target, info.Format);
|
||||||
|
Assert.AreEqual((320, 200), (back.Width, back.Height), "i pixel non si ruotano: l'etichetta resta");
|
||||||
|
Assert.AreEqual(6, info.Metadata.Orientation);
|
||||||
|
CollectionAssert.AreEqual(exif, info.Metadata.Exif);
|
||||||
|
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
|
||||||
|
Assert.AreEqual(xmp, info.Metadata.Xmp);
|
||||||
|
using var original = JpegDecoder.Decode(jpeg);
|
||||||
|
ImageAssert.AreEqual(original, back, $"in {target} senza perdita");
|
||||||
|
if (target == ImageFormat.Png)
|
||||||
|
{
|
||||||
|
Assert.IsEmpty(result.NotCarried);
|
||||||
|
Assert.AreEqual("Gita al lago", info.Metadata.Texts.Single(t => t.Keyword == "Comment").Text);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Assert.HasCount(1, result.NotCarried);
|
||||||
|
StringAssert.Contains(result.NotCarried[0], "WebP");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void APngBecomesJpegWithItsMetadataOverWhite()
|
||||||
|
{
|
||||||
|
using var image = TestImages.Gradient(96, 64, 9); // alpha falls from 255 to 192 across each band of 64 columns
|
||||||
|
var exif = Tiff(orientation: 3);
|
||||||
|
var icc = Profile(300);
|
||||||
|
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>";
|
||||||
|
var png = PngEncoder.Encode(image, new PngEncoderOptions
|
||||||
|
{
|
||||||
|
Exif = exif,
|
||||||
|
IccProfile = icc,
|
||||||
|
Xmp = xmp,
|
||||||
|
Texts = [new ImageText("Title", "Tramonto"), new ImageText("Description", "Città e mare")],
|
||||||
|
});
|
||||||
|
|
||||||
|
var result = ImageConverter.Convert(png, ImageFormat.Jpeg);
|
||||||
|
Assert.IsTrue(result.Lossy);
|
||||||
|
Assert.HasCount(1, result.NotCarried);
|
||||||
|
StringAssert.Contains(result.NotCarried[0], "trasparenza");
|
||||||
|
using var back = ImageDecoder.Decode(result.Data, out var info);
|
||||||
|
Assert.IsTrue(back.IsOpaque());
|
||||||
|
Assert.AreEqual(3, info.Metadata.Orientation);
|
||||||
|
CollectionAssert.AreEqual(exif, info.Metadata.Exif);
|
||||||
|
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
|
||||||
|
Assert.AreEqual(xmp, info.Metadata.Xmp);
|
||||||
|
CollectionAssert.AreEqual(new[] { "Title: Tramonto", "Description: Città e mare" }, info.Metadata.Texts.Select(t => t.Text).ToArray());
|
||||||
|
|
||||||
|
// Over white: a pixel at alpha 192 is lighter than its colour.
|
||||||
|
var (r, _, _, a) = image.GetPixel(63, 10);
|
||||||
|
Assert.AreEqual(192, a);
|
||||||
|
var expected = ((r * 192) + (255 * 63) + 127) / 255;
|
||||||
|
Assert.IsLessThanOrEqualTo(6, Math.Abs(back.GetPixel(63, 10).R - expected));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AProfileThatDoesNotDescribeRgbIsLeftBehind()
|
||||||
|
{
|
||||||
|
// Adobe CMYK, every pixel the same inks: the decoder writes RGB, so a CMYK profile no longer fits.
|
||||||
|
const int width = 16;
|
||||||
|
const int height = 8;
|
||||||
|
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||||||
|
int[] Plane(int value) => Enumerable.Repeat(value, width * height).ToArray();
|
||||||
|
var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, Plane(200)), (2, 1, 1, 0, Plane(120)), (3, 1, 1, 0, Plane(60)), (4, 1, 1, 0, Plane(230))], [fine], 0xC1);
|
||||||
|
var cmykFile = WithIcc(JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 }), Profile(400, "CMYK"));
|
||||||
|
Assert.AreEqual("CMYK", ImageConverter.IccColorSpace(JpegDecoder.Identify(cmykFile).Metadata.IccProfile));
|
||||||
|
|
||||||
|
// A grey JPEG with a grey profile: the encoders write RGB.
|
||||||
|
using var scene = Scenes.Scene(8, 48, 32);
|
||||||
|
var greyFile = JpegEncoder.Encode(scene, new JpegEncoderOptions { Grayscale = true, IccProfile = Profile(300, "GRAY") });
|
||||||
|
|
||||||
|
foreach (var (file, space) in new[] { (cmykFile, "CMYK"), (greyFile, "grigi") })
|
||||||
|
{
|
||||||
|
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP, ImageFormat.Jpeg })
|
||||||
|
{
|
||||||
|
var result = ImageConverter.Convert(file, target);
|
||||||
|
var said = string.Join("; ", result.NotCarried);
|
||||||
|
Assert.IsNull(result.Metadata.IccProfile, $"{space} in {target}");
|
||||||
|
Assert.IsNull(result.Metadata.IccProfileName, $"{space} in {target}");
|
||||||
|
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal) && n.Contains(space, StringComparison.Ordinal)), $"{space} in {target}: {said}");
|
||||||
|
Assert.IsNull(ImageDecoder.Identify(result.Data).Metadata.IccProfile, $"{space} in {target}: il file scritto non ha il profilo");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// An RGB profile travels (the other converter tests check it byte for byte); one too short to have a
|
||||||
|
// colour space does not.
|
||||||
|
Assert.AreEqual("RGB ", ImageConverter.IccColorSpace(Profile(200)));
|
||||||
|
Assert.IsNull(ImageConverter.IccColorSpace(new byte[12]));
|
||||||
|
var garbled = JpegEncoder.Encode(scene, new JpegEncoderOptions { IccProfile = new byte[12] });
|
||||||
|
var dropped = ImageConverter.Convert(garbled, ImageFormat.Png);
|
||||||
|
Assert.IsNull(dropped.Metadata.IccProfile);
|
||||||
|
Assert.IsTrue(dropped.NotCarried.Any(n => n.Contains("profilo colore", StringComparison.Ordinal)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void SixteenBitSamplesAndPngColourChunksAreReported()
|
||||||
|
{
|
||||||
|
// A 2×2 16-bit RGB PNG with gAMA and sRGB: decoded to 8 bits, so not lossless, and the colour chunks stay
|
||||||
|
// behind; both are said.
|
||||||
|
var raw = new byte[2 * (1 + (2 * 6))];
|
||||||
|
for (var i = 0; i < raw.Length; i++)
|
||||||
|
{
|
||||||
|
raw[i] = i % 13 == 0 ? (byte)0 : (byte)(i * 37);
|
||||||
|
}
|
||||||
|
|
||||||
|
var gamma = new byte[4];
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(gamma, 45455);
|
||||||
|
var png = TestImages.Png(("IHDR", TestImages.Ihdr(2, 2, 16, 2)), ("gAMA", gamma), ("sRGB", [0]), ("IDAT", TestImages.Zlib(raw)), ("IEND", []));
|
||||||
|
var info = PngDecoder.Identify(png);
|
||||||
|
Assert.AreEqual(16, info.BitsPerSample);
|
||||||
|
CollectionAssert.AreEqual(new[] { "gAMA", "sRGB" }, info.Metadata.ColorChunks.ToArray());
|
||||||
|
foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP })
|
||||||
|
{
|
||||||
|
var result = ImageConverter.Convert(png, target);
|
||||||
|
var said = string.Join("; ", result.NotCarried);
|
||||||
|
Assert.IsTrue(result.Lossy, $"{target}: 16 bit diventano 8");
|
||||||
|
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("16 bit", StringComparison.Ordinal)), said);
|
||||||
|
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("gAMA", StringComparison.Ordinal)), said);
|
||||||
|
Assert.IsTrue(result.NotCarried.Any(n => n.Contains("sRGB", StringComparison.Ordinal)), said);
|
||||||
|
}
|
||||||
|
|
||||||
|
// An 8-bit PNG without colour chunks converts losslessly and says nothing.
|
||||||
|
var plain = PngEncoder.Encode(TestImages.Random(5, 4, 2, opaque: true));
|
||||||
|
Assert.AreEqual(8, PngDecoder.Identify(plain).BitsPerSample);
|
||||||
|
var clean = ImageConverter.Convert(plain, ImageFormat.WebP);
|
||||||
|
Assert.IsFalse(clean.Lossy);
|
||||||
|
Assert.IsEmpty(clean.NotCarried);
|
||||||
|
|
||||||
|
// The precision of a 12-bit JPEG is reported too.
|
||||||
|
var twelve = JpegEncoder.TransformPlanes(8, 8, 12, [(1, 1, 1, 0, new int[64])], [Enumerable.Repeat((ushort)1, 64).ToArray()], 0xC1);
|
||||||
|
Assert.AreEqual(12, JpegDecoder.Identify(JpegTestEncoder.Write(twelve, new JpegTestOptions())).BitsPerSample);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OnlyJpegPngAndWebPAreWritten()
|
||||||
|
{
|
||||||
|
Assert.IsTrue(ImageConverter.CanWrite(ImageFormat.Jpeg));
|
||||||
|
Assert.IsTrue(ImageConverter.CanWrite(ImageFormat.Png));
|
||||||
|
Assert.IsTrue(ImageConverter.CanWrite(ImageFormat.WebP));
|
||||||
|
Assert.IsFalse(ImageConverter.CanWrite(ImageFormat.Gif));
|
||||||
|
var png = PngEncoder.Encode(TestImages.Random(4, 4, 1));
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => ImageConverter.Convert(png, ImageFormat.Gif));
|
||||||
|
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageConverter.Convert(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, ImageFormat.Png));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- PNG texts ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PngTextsAreWrittenAsTextOrInternationalText()
|
||||||
|
{
|
||||||
|
using var image = TestImages.Random(3, 3, 4);
|
||||||
|
var texts = new[]
|
||||||
|
{
|
||||||
|
new ImageText("Title", "Caffè"),
|
||||||
|
new ImageText("Comment", "Ελληνικά"),
|
||||||
|
new ImageText("Author", "Alberto", "it", "Autore"),
|
||||||
|
};
|
||||||
|
var png = PngEncoder.Encode(image, new PngEncoderOptions { Texts = texts });
|
||||||
|
var types = TestImages.PngChunks(png).Select(c => c.Type).ToArray();
|
||||||
|
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "tEXt", "iTXt", "iTXt", "IEND" }, types);
|
||||||
|
var info = PngDecoder.Identify(png);
|
||||||
|
CollectionAssert.AreEqual(texts, info.Metadata.Texts.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void PngKeywordsFollowTheSpecification()
|
||||||
|
{
|
||||||
|
Assert.IsTrue(PngEncoder.IsValidKeyword("Title"));
|
||||||
|
Assert.IsTrue(PngEncoder.IsValidKeyword(new string('k', 79)));
|
||||||
|
Assert.IsFalse(PngEncoder.IsValidKeyword(string.Empty));
|
||||||
|
Assert.IsFalse(PngEncoder.IsValidKeyword(new string('k', 80)));
|
||||||
|
Assert.IsFalse(PngEncoder.IsValidKeyword(" Title"));
|
||||||
|
Assert.IsFalse(PngEncoder.IsValidKeyword("Two spaces"));
|
||||||
|
Assert.IsFalse(PngEncoder.IsValidKeyword("Ελληνικά"));
|
||||||
|
using var image = TestImages.Random(2, 2, 1);
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { Texts = [new ImageText("", "x")] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Rasteriser ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ACircleCoversItsArea()
|
||||||
|
{
|
||||||
|
foreach (var (cx, cy, r) in new[] { (32f, 32f, 20f), (31.3f, 30.7f, 9.5f), (40f, 24f, 2.5f) })
|
||||||
|
{
|
||||||
|
var covered = Coverage(64, 64, canvas => canvas.FillCircle(cx, cy, r, Color.White));
|
||||||
|
Assert.AreEqual(Math.PI * r * r, covered, Math.PI * r * r * 0.01, $"cerchio di raggio {r}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ARectangleCoversExactlyItsPixels()
|
||||||
|
{
|
||||||
|
using var image = new RgbaImage(16, 16);
|
||||||
|
using (var canvas = new Canvas(image))
|
||||||
|
{
|
||||||
|
canvas.FillRect(3, 4, 5, 6, Color.White);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var y = 0; y < 16; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < 16; x++)
|
||||||
|
{
|
||||||
|
var inside = x is >= 3 and < 8 && y is >= 4 and < 10;
|
||||||
|
Assert.AreEqual(inside ? 255 : 0, image.GetPixel(x, y).A, $"({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Half a pixel in: the border pixels are half covered.
|
||||||
|
var half = Coverage(16, 16, canvas => canvas.FillRect(2.5f, 2.5f, 4, 4, Color.White));
|
||||||
|
Assert.AreEqual(16.0, half, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ARotatedSquareKeepsItsArea()
|
||||||
|
{
|
||||||
|
var covered = Coverage(64, 64, canvas =>
|
||||||
|
{
|
||||||
|
canvas.Translate(32, 32);
|
||||||
|
canvas.Rotate(30);
|
||||||
|
canvas.FillRect(-12, -12, 24, 24, Color.White);
|
||||||
|
});
|
||||||
|
Assert.AreEqual(576.0, covered, 1.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ARingAndAHoleAreLeftEmptyInside()
|
||||||
|
{
|
||||||
|
var ring = Coverage(80, 80, canvas => canvas.StrokeCircle(40, 40, 25, 4, Color.White));
|
||||||
|
Assert.AreEqual(Math.PI * ((27.0 * 27) - (23.0 * 23)), ring, 6.0);
|
||||||
|
|
||||||
|
// A contour turning the other way inside another cuts a hole (non-zero rule); the same way, it adds nothing.
|
||||||
|
var hole = Coverage(40, 40, canvas => canvas.Fill(new PathBuilder().AddRect(5, 5, 30, 30).AddRect(15, 15, 10, 10, clockwise: false), Color.White));
|
||||||
|
Assert.AreEqual(800.0, hole, 0.5);
|
||||||
|
var same = Coverage(40, 40, canvas => canvas.Fill(new PathBuilder().AddRect(5, 5, 30, 30).AddRect(15, 15, 10, 10), Color.White));
|
||||||
|
Assert.AreEqual(900.0, same, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ShapesOutsideTheCanvasAreClipped()
|
||||||
|
{
|
||||||
|
// A circle centred on the corner: a quarter of it is inside.
|
||||||
|
var covered = Coverage(32, 32, canvas => canvas.FillCircle(0, 0, 20, Color.White));
|
||||||
|
Assert.AreEqual(Math.PI * 400 / 4, covered, 4.0);
|
||||||
|
var nothing = Coverage(32, 32, canvas => canvas.FillCircle(-50, 10, 20, Color.White));
|
||||||
|
Assert.AreEqual(0.0, nothing);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AGradientRunsBetweenItsColours()
|
||||||
|
{
|
||||||
|
using var image = new RgbaImage(101, 4);
|
||||||
|
using (var canvas = new Canvas(image))
|
||||||
|
{
|
||||||
|
canvas.FillRect(0, 0, 101, 4, new LinearGradientBrush(new Vector2(0.5f, 0), new Vector2(100.5f, 0), [Color.Black, Color.White]));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsLessThanOrEqualTo(1, (int)image.GetPixel(0, 2).R);
|
||||||
|
Assert.IsLessThanOrEqualTo(1, Math.Abs(image.GetPixel(50, 2).R - 128));
|
||||||
|
Assert.IsGreaterThanOrEqualTo(254, (int)image.GetPixel(100, 2).R);
|
||||||
|
for (var x = 1; x < 101; x++)
|
||||||
|
{
|
||||||
|
Assert.IsGreaterThanOrEqualTo((int)image.GetPixel(x - 1, 2).R, (int)image.GetPixel(x, 2).R, $"x = {x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void HalfTransparentPaintMixesWithWhatIsBelow()
|
||||||
|
{
|
||||||
|
using var image = new RgbaImage(4, 4);
|
||||||
|
using (var canvas = new Canvas(image))
|
||||||
|
{
|
||||||
|
canvas.Clear(new Color(0, 0, 255));
|
||||||
|
canvas.FillRect(0, 0, 4, 4, new Color(255, 0, 0, 128));
|
||||||
|
}
|
||||||
|
|
||||||
|
var p = image.GetPixel(1, 1);
|
||||||
|
Assert.AreEqual(255, p.A);
|
||||||
|
Assert.IsLessThanOrEqualTo(1, Math.Abs(p.R - 128));
|
||||||
|
Assert.IsLessThanOrEqualTo(1, Math.Abs(p.B - 127));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers ----
|
||||||
|
|
||||||
|
private static RgbaImage Flat(int width, int height, byte r, byte g, byte b, byte a)
|
||||||
|
{
|
||||||
|
var image = new RgbaImage(width, height);
|
||||||
|
var pixels = image.Pixels;
|
||||||
|
for (var i = 0; i < pixels.Length; i += 4)
|
||||||
|
{
|
||||||
|
(pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]) = (r, g, b, a);
|
||||||
|
}
|
||||||
|
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertEveryPixel(RgbaImage image, (int R, int G, int B, int A) expected, int tolerance, string what)
|
||||||
|
{
|
||||||
|
for (var y = 0; y < image.Height; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < image.Width; x++)
|
||||||
|
{
|
||||||
|
var p = image.GetPixel(x, y);
|
||||||
|
if (Math.Abs(p.R - expected.R) > tolerance || Math.Abs(p.G - expected.G) > tolerance
|
||||||
|
|| Math.Abs(p.B - expected.B) > tolerance || Math.Abs(p.A - expected.A) > tolerance)
|
||||||
|
{
|
||||||
|
Assert.Fail($"{what}: ({x}, {y}) è {p}, atteso {expected}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Pixels covered by what <paramref name="draw"/> paints on a transparent canvas: the sum of alpha / 255.</summary>
|
||||||
|
private static double Coverage(int width, int height, Action<Canvas> draw)
|
||||||
|
{
|
||||||
|
using var image = new RgbaImage(width, height);
|
||||||
|
using (var canvas = new Canvas(image))
|
||||||
|
{
|
||||||
|
draw(canvas);
|
||||||
|
}
|
||||||
|
|
||||||
|
var sum = 0L;
|
||||||
|
var pixels = image.Pixels;
|
||||||
|
for (var i = 3; i < pixels.Length; i += 4)
|
||||||
|
{
|
||||||
|
sum += pixels[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum / 255.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A small big-endian TIFF block with one Orientation entry and one ASCII Make entry.</summary>
|
||||||
|
private static byte[] Tiff(ushort orientation)
|
||||||
|
{
|
||||||
|
var make = Encoding.ASCII.GetBytes("Febe\0");
|
||||||
|
var tiff = new byte[8 + 2 + (2 * 12) + 4 + make.Length];
|
||||||
|
"MM\0*"u8.CopyTo(tiff);
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(4), 8);
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(8), 2);
|
||||||
|
var entry = tiff.AsSpan(10);
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(entry, 0x010F); // Make
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(entry[2..], 2); // ASCII
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(entry[4..], (uint)make.Length);
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(entry[8..], (uint)(tiff.Length - make.Length));
|
||||||
|
entry = tiff.AsSpan(22);
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(entry, 0x0112); // Orientation
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(entry[2..], 3); // SHORT
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(entry[4..], 1);
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(entry[8..], orientation);
|
||||||
|
make.CopyTo(tiff.AsSpan(tiff.Length - make.Length));
|
||||||
|
return tiff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bytes standing in for an ICC profile (the codecs carry it without reading it).</summary>
|
||||||
|
/// <summary>A stand-in ICC profile: arbitrary bytes with the data colour space of its header (bytes 16-19) set.</summary>
|
||||||
|
private static byte[] Profile(int length, string colorSpace = "RGB ")
|
||||||
|
{
|
||||||
|
var bytes = new byte[length];
|
||||||
|
for (var i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
bytes[i] = (byte)((i * 7) + (i >> 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
Encoding.ASCII.GetBytes(colorSpace, bytes.AsSpan(16, 4));
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI.</summary>
|
||||||
|
private static byte[] WithIcc(byte[] jpeg, byte[] profile)
|
||||||
|
{
|
||||||
|
byte[] payload = [.. Encoding.ASCII.GetBytes("ICC_PROFILE"), 0, 1, 1, .. profile];
|
||||||
|
var segment = new byte[4 + payload.Length];
|
||||||
|
segment[0] = 0xFF;
|
||||||
|
segment[1] = 0xE2;
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(segment.AsSpan(2), (ushort)(payload.Length + 2));
|
||||||
|
payload.CopyTo(segment, 4);
|
||||||
|
return [.. jpeg.AsSpan(0, 2), .. segment, .. jpeg.AsSpan(2)];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>How close a lossy decode is to its reference: PSNR per channel and the share of pixels far off.</summary>
|
||||||
|
/// <param name="PsnrRed">PSNR of the red channel, dB (infinity when identical).</param>
|
||||||
|
/// <param name="PsnrGreen">PSNR of the green channel, dB.</param>
|
||||||
|
/// <param name="PsnrBlue">PSNR of the blue channel, dB.</param>
|
||||||
|
/// <param name="PsnrAlpha">PSNR of the alpha channel, dB.</param>
|
||||||
|
/// <param name="FarOff">Share (0-1) of pixels with some channel off by more than <see cref="ImageQuality.FarThreshold"/>.</param>
|
||||||
|
/// <param name="MaxDifference">Largest difference of any channel.</param>
|
||||||
|
internal sealed record ImageQualityResult(double PsnrRed, double PsnrGreen, double PsnrBlue, double PsnrAlpha, double FarOff, int MaxDifference)
|
||||||
|
{
|
||||||
|
/// <summary>The smallest PSNR of the colour channels.</summary>
|
||||||
|
public double MinPsnr => Math.Min(PsnrRed, Math.Min(PsnrGreen, PsnrBlue));
|
||||||
|
|
||||||
|
public override string ToString() => string.Create(
|
||||||
|
CultureInfo.InvariantCulture,
|
||||||
|
$"PSNR R {PsnrRed:F2} G {PsnrGreen:F2} B {PsnrBlue:F2} A {PsnrAlpha:F2} dB, oltre {ImageQuality.FarThreshold}: {FarOff * 100:F3}%, scarto massimo {MaxDifference}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Measures and orientation helpers for comparing decoded images.</summary>
|
||||||
|
internal static class ImageQuality
|
||||||
|
{
|
||||||
|
/// <summary>A pixel counts as far off when one of its channels differs by more than this.</summary>
|
||||||
|
public const int FarThreshold = 16;
|
||||||
|
|
||||||
|
/// <summary>Lossy decodes must reach this PSNR on every colour channel (SPECIFICA §14.1, proposal of C1).</summary>
|
||||||
|
public const double MinimumPsnr = 40;
|
||||||
|
|
||||||
|
/// <summary>Lossy decodes may have at most this share of pixels far off.</summary>
|
||||||
|
public const double MaximumFarOff = 0.001;
|
||||||
|
|
||||||
|
public static ImageQualityResult Compare(RgbaImage expected, RgbaImage actual)
|
||||||
|
{
|
||||||
|
Assert.AreEqual((expected.Width, expected.Height), (actual.Width, actual.Height), "misura diversa");
|
||||||
|
var e = expected.Pixels;
|
||||||
|
var a = actual.Pixels;
|
||||||
|
Span<double> squares = stackalloc double[4];
|
||||||
|
var far = 0;
|
||||||
|
var max = 0;
|
||||||
|
for (var i = 0; i < e.Length; i += 4)
|
||||||
|
{
|
||||||
|
var isFar = false;
|
||||||
|
for (var ch = 0; ch < 4; ch++)
|
||||||
|
{
|
||||||
|
var d = Math.Abs(e[i + ch] - a[i + ch]);
|
||||||
|
squares[ch] += d * d;
|
||||||
|
max = Math.Max(max, d);
|
||||||
|
isFar |= d > FarThreshold;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFar)
|
||||||
|
{
|
||||||
|
far++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var pixels = e.Length / 4;
|
||||||
|
return new ImageQualityResult(Psnr(squares[0], pixels), Psnr(squares[1], pixels), Psnr(squares[2], pixels), Psnr(squares[3], pixels), (double)far / pixels, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Asserts the thresholds of a lossy decode.</summary>
|
||||||
|
public static void AssertClose(ImageQualityResult result, string what)
|
||||||
|
{
|
||||||
|
Assert.IsGreaterThanOrEqualTo(MinimumPsnr, result.MinPsnr, $"{what}: {result}");
|
||||||
|
Assert.IsLessThanOrEqualTo(MaximumFarOff, result.FarOff, $"{what}: {result}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double Psnr(double squares, int pixels) =>
|
||||||
|
squares == 0 ? double.PositiveInfinity : 10 * Math.Log10(255.0 * 255.0 / (squares / pixels));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The image as it should be shown for EXIF orientation <paramref name="orientation"/> (1-8): mirrored, rotated
|
||||||
|
/// or transposed from the stored pixels.
|
||||||
|
/// </summary>
|
||||||
|
public static RgbaImage Orient(RgbaImage stored, int orientation)
|
||||||
|
{
|
||||||
|
var w = stored.Width;
|
||||||
|
var h = stored.Height;
|
||||||
|
var swap = orientation >= 5;
|
||||||
|
var result = new RgbaImage(swap ? h : w, swap ? w : h);
|
||||||
|
for (var dy = 0; dy < result.Height; dy++)
|
||||||
|
{
|
||||||
|
var row = result.GetRow(dy);
|
||||||
|
for (var dx = 0; dx < result.Width; dx++)
|
||||||
|
{
|
||||||
|
var (sx, sy) = orientation switch
|
||||||
|
{
|
||||||
|
2 => (w - 1 - dx, dy),
|
||||||
|
3 => (w - 1 - dx, h - 1 - dy),
|
||||||
|
4 => (dx, h - 1 - dy),
|
||||||
|
5 => (dy, dx),
|
||||||
|
6 => (dy, h - 1 - dx),
|
||||||
|
7 => (w - 1 - dy, h - 1 - dx),
|
||||||
|
8 => (w - 1 - dy, dx),
|
||||||
|
_ => (dx, dy),
|
||||||
|
};
|
||||||
|
stored.GetRow(sy).Slice(sx * 4, 4).CopyTo(row[(dx * 4)..]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>The common pieces of the in-house image codecs: format recognition, the RGBA image, the limits.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ImagingBaseTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
public void FormatsAreRecognisedFromTheirFirstBytes()
|
||||||
|
{
|
||||||
|
var bmp = new byte[18];
|
||||||
|
"BM"u8.CopyTo(bmp);
|
||||||
|
bmp[14] = 40;
|
||||||
|
var cases = new (byte[] Bytes, ImageFormat Format)[]
|
||||||
|
{
|
||||||
|
([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0], ImageFormat.Png),
|
||||||
|
([0xFF, 0xD8, 0xFF, 0xE0], ImageFormat.Jpeg),
|
||||||
|
("GIF89a"u8.ToArray(), ImageFormat.Gif),
|
||||||
|
("GIF87a"u8.ToArray(), ImageFormat.Gif),
|
||||||
|
(bmp, ImageFormat.Bmp),
|
||||||
|
("RIFF\0\0\0\0WEBPVP8 "u8.ToArray(), ImageFormat.WebP),
|
||||||
|
("II*\0"u8.ToArray(), ImageFormat.Tiff),
|
||||||
|
("MM\0*"u8.ToArray(), ImageFormat.Tiff),
|
||||||
|
("\0\0\0\u0018ftypheic"u8.ToArray(), ImageFormat.Heif),
|
||||||
|
("\0\0\0\u0018ftypmif1"u8.ToArray(), ImageFormat.Heif),
|
||||||
|
("\0\0\0\u0018ftypavif"u8.ToArray(), ImageFormat.Avif),
|
||||||
|
("\0\0\0\u0018ftypisom"u8.ToArray(), ImageFormat.Unknown),
|
||||||
|
("RIFF\0\0\0\0AVI "u8.ToArray(), ImageFormat.Unknown),
|
||||||
|
("GIF89"u8.ToArray(), ImageFormat.Unknown),
|
||||||
|
("BM"u8.ToArray(), ImageFormat.Unknown),
|
||||||
|
([0x89, 0x50, 0x4E, 0x47], ImageFormat.Unknown),
|
||||||
|
([], ImageFormat.Unknown),
|
||||||
|
(Encoding.ASCII.GetBytes("<html>"), ImageFormat.Unknown),
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var (bytes, format) in cases)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(format, ImageFormatSniffer.Detect(bytes), Convert.ToHexString(bytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A BMP whose information header has a size no version has is not taken for one.
|
||||||
|
bmp[14] = 41;
|
||||||
|
Assert.AreEqual(ImageFormat.Unknown, ImageFormatSniffer.Detect(bmp));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnImageHasRowsOfFourBytesPerPixel()
|
||||||
|
{
|
||||||
|
using var image = new RgbaImage(3, 2);
|
||||||
|
Assert.AreEqual((12, 24), (image.Stride, image.Length));
|
||||||
|
Assert.IsTrue(image.Pixels.ToArray().All(b => b == 0));
|
||||||
|
Assert.IsFalse(image.IsOpaque());
|
||||||
|
image.GetRow(1)[4..8].Fill(200);
|
||||||
|
Assert.AreEqual((200, 200, 200, 200), image.GetPixel(1, 1));
|
||||||
|
Assert.AreEqual(200, image.ToArray()[16]);
|
||||||
|
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => image.GetRow(2).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => image.GetPixel(3, 0));
|
||||||
|
|
||||||
|
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => new RgbaImage(0, 1));
|
||||||
|
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => new RgbaImage(50_000, 50_000));
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => new RgbaImage(2, 2, new byte[15]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ARentedImageStartsClearAndGoesBackToThePool()
|
||||||
|
{
|
||||||
|
for (var round = 0; round < 3; round++)
|
||||||
|
{
|
||||||
|
var image = RgbaImage.Rent(33, 17);
|
||||||
|
Assert.IsTrue(image.IsPooled);
|
||||||
|
Assert.IsTrue(image.Pixels.ToArray().All(b => b == 0), $"giro {round}: un array del pool arriva sporco");
|
||||||
|
image.Pixels.Fill(0xAB);
|
||||||
|
image.Dispose();
|
||||||
|
Assert.ThrowsExactly<ObjectDisposedException>(() => image.GetRow(0).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disposing an image that owns its array changes nothing.
|
||||||
|
var owned = new RgbaImage(1, 1);
|
||||||
|
owned.Dispose();
|
||||||
|
Assert.AreEqual(4, owned.Pixels.Length);
|
||||||
|
|
||||||
|
// A picture above 16 MiB is rented as a plain array, not from the pool, and still starts clear.
|
||||||
|
var large = RgbaImage.Rent(2100, 2100);
|
||||||
|
Assert.IsTrue(large.IsPooled);
|
||||||
|
Assert.IsTrue(large.Pixels.IndexOfAnyExcept((byte)0) < 0);
|
||||||
|
large.Dispose();
|
||||||
|
Assert.ThrowsExactly<ObjectDisposedException>(() => large.GetRow(0).Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LargeWorkingArraysDoNotStayInTheSharedPool()
|
||||||
|
{
|
||||||
|
// Up to 16 MiB the shared pool, rounded up to a power of two; above, an array of exactly the size asked,
|
||||||
|
// which the pool would otherwise round to the next power of two and keep after it was given back.
|
||||||
|
var small = ImageBuffers.Rent<byte>(1000);
|
||||||
|
Assert.AreEqual(1024, small.Length);
|
||||||
|
Assert.IsTrue(ImageBuffers.IsPooled(small));
|
||||||
|
ImageBuffers.Return(small);
|
||||||
|
|
||||||
|
var limit = ImageBuffers.Rent<byte>(ImageBuffers.PooledBytes);
|
||||||
|
Assert.AreEqual(ImageBuffers.PooledBytes, limit.Length);
|
||||||
|
Assert.IsTrue(ImageBuffers.IsPooled(limit));
|
||||||
|
ImageBuffers.Return(limit);
|
||||||
|
|
||||||
|
var large = ImageBuffers.Rent<byte>(ImageBuffers.PooledBytes + 1);
|
||||||
|
Assert.AreEqual(ImageBuffers.PooledBytes + 1, large.Length, "non arrotondato a 32 MiB: non viene dal pool");
|
||||||
|
Assert.IsFalse(ImageBuffers.IsPooled(large));
|
||||||
|
ImageBuffers.Return(large); // left to the collector: the pool would refuse an array it did not give
|
||||||
|
|
||||||
|
// The threshold is in bytes, whatever the element.
|
||||||
|
var shorts = ImageBuffers.Rent<short>((ImageBuffers.PooledBytes / 2) + 1);
|
||||||
|
Assert.AreEqual((ImageBuffers.PooledBytes / 2) + 1, shorts.Length);
|
||||||
|
ImageBuffers.Return(shorts);
|
||||||
|
var words = ImageBuffers.Rent<uint>(1000);
|
||||||
|
Assert.AreEqual(1024, words.Length);
|
||||||
|
ImageBuffers.Return(words);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheFacadeSaysWhichFormatsItCannotReadYet()
|
||||||
|
{
|
||||||
|
var tiff = "II*\0\u0008\0\0\0\0\0"u8.ToArray();
|
||||||
|
var error = Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(tiff));
|
||||||
|
Assert.Contains("TIFF", error.Message);
|
||||||
|
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi")));
|
||||||
|
Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg) && ImageDecoder.CanDecode(ImageFormat.WebP));
|
||||||
|
Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Tiff) || ImageDecoder.CanDecode(ImageFormat.Heif) || ImageDecoder.CanDecode(ImageFormat.Unknown));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,549 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The decoding processes the reference set has no file for, checked at coefficient level: the same quantized
|
||||||
|
/// coefficients are written by the baseline encoder and by the test encoder in every other way (progressive with
|
||||||
|
/// spectral selection and successive approximation, restart intervals, separate scans, DNL, arithmetic coding,
|
||||||
|
/// 12 bits, odd sampling factors), and the decoder must read back exactly those coefficients. Lossless files are
|
||||||
|
/// checked sample by sample; CMYK and YCCK through the colours.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class JpegCodingTests
|
||||||
|
{
|
||||||
|
public TestContext TestContext { get; set; } = null!;
|
||||||
|
|
||||||
|
/// <summary>Images and encoder settings the cross-checks run on.</summary>
|
||||||
|
public static IEnumerable<object[]> Sources =>
|
||||||
|
[
|
||||||
|
["gradiente-420", 61, 37, JpegSubsampling.Ratio420, false],
|
||||||
|
["gradiente-444", 45, 29, JpegSubsampling.Ratio444, false],
|
||||||
|
["grigio", 33, 50, JpegSubsampling.Ratio420, true],
|
||||||
|
["riferimento-420", 0, 0, JpegSubsampling.Ratio420, false],
|
||||||
|
];
|
||||||
|
|
||||||
|
private static RgbaImage SourceImage(int width, int height)
|
||||||
|
{
|
||||||
|
if (width == 0)
|
||||||
|
{
|
||||||
|
// A real-looking picture with edges: the PNG of the reference set.
|
||||||
|
return PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput());
|
||||||
|
}
|
||||||
|
|
||||||
|
return TestImages.Gradient(width, height, width * height);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JpegEncoderOptions Settings(JpegSubsampling subsampling, bool grey, int quality = 90) =>
|
||||||
|
new() { Quality = quality, Subsampling = subsampling, Grayscale = grey };
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(Sources))]
|
||||||
|
public void TheBaselineFileHoldsExactlyTheEncodersCoefficients(string name, int width, int height, JpegSubsampling subsampling, bool grey)
|
||||||
|
{
|
||||||
|
using var image = SourceImage(width, height);
|
||||||
|
var settings = Settings(subsampling, grey);
|
||||||
|
var expected = JpegEncoder.Transform(image, settings);
|
||||||
|
var file = JpegEncoder.Encode(image, settings);
|
||||||
|
var actual = JpegDecoder.DecodeCoefficients(file);
|
||||||
|
Assert.AreEqual(0xC0, actual.FrameMarker, name);
|
||||||
|
AssertSameCoefficients(expected, actual, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(Sources))]
|
||||||
|
public void EveryOtherCodingOfTheSameCoefficientsDecodesToThem(string name, int width, int height, JpegSubsampling subsampling, bool grey)
|
||||||
|
{
|
||||||
|
using var image = SourceImage(width, height);
|
||||||
|
var settings = Settings(subsampling, grey);
|
||||||
|
var coefficients = JpegEncoder.Transform(image, settings);
|
||||||
|
using var baseline = JpegDecoder.Decode(JpegEncoder.Encode(image, settings));
|
||||||
|
var count = coefficients.Components.Count;
|
||||||
|
|
||||||
|
var variants = new (string What, JpegTestOptions Options, int Marker)[]
|
||||||
|
{
|
||||||
|
("sequenziale esteso", new JpegTestOptions(), 0xC1),
|
||||||
|
("scansioni separate", new JpegTestOptions { SeparateScans = true }, 0xC1),
|
||||||
|
("ripristino ogni 3", new JpegTestOptions { RestartInterval = 3 }, 0xC1),
|
||||||
|
("altezza in DNL", new JpegTestOptions { HeightInDnl = true }, 0xC1),
|
||||||
|
("progressivo", new JpegTestOptions { Progressive = true }, 0xC2),
|
||||||
|
("progressivo con ripristino", new JpegTestOptions { Progressive = true, RestartInterval = 2 }, 0xC2),
|
||||||
|
("solo selezione spettrale", new JpegTestOptions { Progressive = true, Script = SpectralOnly(count) }, 0xC2),
|
||||||
|
("approssimazioni fini", new JpegTestOptions { Progressive = true, Script = ManyApproximations(count) }, 0xC2),
|
||||||
|
("aritmetico", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic }, 0xC9),
|
||||||
|
("aritmetico con ripristino", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 5 }, 0xC9),
|
||||||
|
("aritmetico condizionato", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, DcConditioning = (2, 4), AcConditioning = 12 }, 0xC9),
|
||||||
|
("aritmetico progressivo", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true }, 0xCA),
|
||||||
|
("aritmetico progressivo fine", new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true, Script = ManyApproximations(count), RestartInterval = 4 }, 0xCA),
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var (what, options, marker) in variants)
|
||||||
|
{
|
||||||
|
var file = JpegTestEncoder.Write(coefficients, options);
|
||||||
|
var decoded = JpegDecoder.DecodeCoefficients(file);
|
||||||
|
Assert.AreEqual(marker, decoded.FrameMarker, $"{name}, {what}");
|
||||||
|
AssertSameCoefficients(coefficients, decoded, $"{name}, {what}");
|
||||||
|
|
||||||
|
// The same coefficients make the same pixels, whatever the coding.
|
||||||
|
using var pixels = JpegDecoder.Decode(file);
|
||||||
|
ImageAssert.AreEqual(baseline, pixels, $"{name}, {what}");
|
||||||
|
TestContext.WriteLine($"{name}, {what}: {file.Length} byte");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheProductionEncodersRestartIntervalsChangeNoCoefficient()
|
||||||
|
{
|
||||||
|
using var image = TestImages.Gradient(83, 51, 5);
|
||||||
|
foreach (var interval in new[] { 1, 2, 7, 100 })
|
||||||
|
{
|
||||||
|
var settings = new JpegEncoderOptions { Quality = 80, RestartInterval = interval };
|
||||||
|
var file = JpegEncoder.Encode(image, settings);
|
||||||
|
var decoded = JpegDecoder.DecodeCoefficients(file);
|
||||||
|
Assert.AreEqual(interval, decoded.RestartInterval);
|
||||||
|
AssertSameCoefficients(JpegEncoder.Transform(image, settings), decoded, $"intervallo {interval}");
|
||||||
|
var markers = CountRestartMarkers(file);
|
||||||
|
var mcus = ((83 + 15) / 16) * ((51 + 15) / 16);
|
||||||
|
Assert.AreEqual((mcus - 1) / interval, markers, $"intervallo {interval}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> TwelveBitCases =>
|
||||||
|
[
|
||||||
|
[JpegTestCoding.Huffman, false],
|
||||||
|
[JpegTestCoding.Huffman, true],
|
||||||
|
[JpegTestCoding.Arithmetic, false],
|
||||||
|
[JpegTestCoding.Arithmetic, true],
|
||||||
|
];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(TwelveBitCases))]
|
||||||
|
public void TwelveBitFilesDecodeToTheirCoefficientsAndCloseToTheirSamples(JpegTestCoding coding, bool progressive)
|
||||||
|
{
|
||||||
|
const int width = 43;
|
||||||
|
const int height = 27;
|
||||||
|
var random = new Random(12);
|
||||||
|
var grey = new int[width * height];
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
grey[(y * width) + x] = Math.Clamp((x * 4095 / (width - 1)) + random.Next(-20, 21), 0, 4095);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fine 16-bit quantization: 12-bit coefficients need categories up to 15 (DC) and 14 (AC).
|
||||||
|
var table = Enumerable.Repeat((ushort)2, 64).ToArray();
|
||||||
|
table[0] = 1;
|
||||||
|
var coefficients = JpegEncoder.TransformPlanes(width, height, 12, [(1, 1, 1, 0, grey)], [table], 0xC1);
|
||||||
|
var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = coding, Progressive = progressive, RestartInterval = 4 });
|
||||||
|
var decoded = JpegDecoder.DecodeCoefficients(file);
|
||||||
|
Assert.AreEqual(12, decoded.Precision);
|
||||||
|
AssertSameCoefficients(coefficients, decoded, $"{coding}, progressivo {progressive}");
|
||||||
|
|
||||||
|
using var image = JpegDecoder.Decode(file);
|
||||||
|
var worst = 0;
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
var expected = ((grey[(y * width) + x] * 255) + 2047) / 4095;
|
||||||
|
worst = Math.Max(worst, Math.Abs(image.GetPixel(x, y).R - expected));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsLessThanOrEqualTo(1, worst, "a 12 bit con quantizzazione fine l'errore resta sotto un livello di 8 bit");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> SamplingCases =>
|
||||||
|
[
|
||||||
|
["4:2:2", 2, 1],
|
||||||
|
["4:4:0", 1, 2],
|
||||||
|
["4:1:1", 4, 1],
|
||||||
|
["4:1:0", 4, 2],
|
||||||
|
["3×1 (rapporto non intero con 2×1)", 3, 1],
|
||||||
|
];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(SamplingCases))]
|
||||||
|
public void AnySamplingFactorsDecode(string name, int lumaH, int lumaV)
|
||||||
|
{
|
||||||
|
using var image = TestImages.Gradient(57, 41, 9);
|
||||||
|
var (yPlane, cbPlane, crPlane) = YCbCrPlanes(image);
|
||||||
|
const int width = 57;
|
||||||
|
const int height = 41;
|
||||||
|
var chromaH = name.StartsWith('3') ? 2 : 1;
|
||||||
|
var planes = new List<(int Id, int H, int V, int Table, int[] Samples)>
|
||||||
|
{
|
||||||
|
(1, lumaH, lumaV, 0, yPlane),
|
||||||
|
(2, chromaH, 1, 1, Downsample(cbPlane, width, height, lumaH, lumaV, chromaH, 1)),
|
||||||
|
(3, chromaH, 1, 1, Downsample(crPlane, width, height, lumaH, lumaV, chromaH, 1)),
|
||||||
|
};
|
||||||
|
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||||||
|
var coefficients = JpegEncoder.TransformPlanes(width, height, 8, planes, [fine, fine], 0xC1);
|
||||||
|
foreach (var options in new[] { new JpegTestOptions(), new JpegTestOptions { Progressive = true, RestartInterval = 3 }, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic } })
|
||||||
|
{
|
||||||
|
var file = JpegTestEncoder.Write(coefficients, options);
|
||||||
|
AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), name);
|
||||||
|
using var decoded = JpegDecoder.Decode(file);
|
||||||
|
var quality = ImageQuality.Compare(Opaque(image), decoded);
|
||||||
|
TestContext.WriteLine($"{name}: {quality}");
|
||||||
|
|
||||||
|
// The chroma of a smooth gradient survives subsampling well; the luma is lossless but for rounding.
|
||||||
|
Assert.IsGreaterThanOrEqualTo(30, quality.MinPsnr, $"{name}: {quality}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AdobeCmykAndYcckBecomeRgb()
|
||||||
|
{
|
||||||
|
using var image = TestImages.Gradient(40, 24, 3);
|
||||||
|
const int width = 40;
|
||||||
|
const int height = 24;
|
||||||
|
var c = new int[width * height];
|
||||||
|
var m = new int[width * height];
|
||||||
|
var yellow = new int[width * height];
|
||||||
|
var k = new int[width * height];
|
||||||
|
for (var i = 0; i < c.Length; i++)
|
||||||
|
{
|
||||||
|
var p = image.Pixels.Slice(i * 4, 4);
|
||||||
|
|
||||||
|
// Adobe's inverted CMYK: stored values are 255 minus the ink, so R = C × K / 255 with K = the brightest.
|
||||||
|
var key = Math.Max(p[0], Math.Max(p[1], Math.Max(p[2], (byte)1)));
|
||||||
|
k[i] = key;
|
||||||
|
c[i] = Math.Min(255, ((p[0] * 255) + (key / 2)) / key);
|
||||||
|
m[i] = Math.Min(255, ((p[1] * 255) + (key / 2)) / key);
|
||||||
|
yellow[i] = Math.Min(255, ((p[2] * 255) + (key / 2)) / key);
|
||||||
|
}
|
||||||
|
|
||||||
|
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||||||
|
var cmyk = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, c), (2, 1, 1, 0, m), (3, 1, 1, 0, yellow), (4, 1, 1, 0, k)], [fine], 0xC1);
|
||||||
|
var cmykFile = JpegTestEncoder.Write(cmyk, new JpegTestOptions { Jfif = false, AdobeTransform = 0 });
|
||||||
|
using var fromCmyk = JpegDecoder.Decode(cmykFile);
|
||||||
|
var cmykQuality = ImageQuality.Compare(Opaque(image), fromCmyk);
|
||||||
|
TestContext.WriteLine($"CMYK: {cmykQuality}");
|
||||||
|
Assert.IsGreaterThanOrEqualTo(40, cmykQuality.MinPsnr, cmykQuality.ToString());
|
||||||
|
|
||||||
|
// YCCK: the inverted C, M, Y as RGB (255 − stored), to YCbCr; K as it is.
|
||||||
|
var yy = new int[c.Length];
|
||||||
|
var cb = new int[c.Length];
|
||||||
|
var cr = new int[c.Length];
|
||||||
|
for (var i = 0; i < c.Length; i++)
|
||||||
|
{
|
||||||
|
(yy[i], cb[i], cr[i]) = ToYCbCr(255 - c[i], 255 - m[i], 255 - yellow[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var ycck = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, yy), (2, 1, 1, 0, cb), (3, 1, 1, 0, cr), (4, 1, 1, 0, k)], [fine], 0xC1);
|
||||||
|
var ycckFile = JpegTestEncoder.Write(ycck, new JpegTestOptions { Jfif = false, AdobeTransform = 2, Progressive = true });
|
||||||
|
using var fromYcck = JpegDecoder.Decode(ycckFile);
|
||||||
|
var ycckQuality = ImageQuality.Compare(Opaque(image), fromYcck);
|
||||||
|
TestContext.WriteLine($"YCCK: {ycckQuality}");
|
||||||
|
Assert.IsGreaterThanOrEqualTo(38, ycckQuality.MinPsnr, ycckQuality.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ThreeComponentsAreRgbWithAdobeTransformZeroOrRgbIdentifiers()
|
||||||
|
{
|
||||||
|
using var image = TestImages.Gradient(24, 16, 4);
|
||||||
|
var (r, g, b) = Channels(image);
|
||||||
|
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||||||
|
foreach (var (ids, adobe) in new[] { ((1, 2, 3), 0), (('R', 'G', 'B'), -1) })
|
||||||
|
{
|
||||||
|
var coefficients = JpegEncoder.TransformPlanes(24, 16, 8, [(ids.Item1, 1, 1, 0, r), (ids.Item2, 1, 1, 0, g), (ids.Item3, 1, 1, 0, b)], [fine], 0xC1);
|
||||||
|
using var decoded = JpegDecoder.Decode(JpegTestEncoder.Write(coefficients, new JpegTestOptions { Jfif = false, AdobeTransform = adobe }));
|
||||||
|
var quality = ImageQuality.Compare(Opaque(image), decoded);
|
||||||
|
Assert.IsGreaterThanOrEqualTo(45, quality.MinPsnr, quality.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> LosslessCases()
|
||||||
|
{
|
||||||
|
foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic })
|
||||||
|
{
|
||||||
|
for (var predictor = 1; predictor <= 7; predictor++)
|
||||||
|
{
|
||||||
|
yield return [coding, 8, predictor, 0, 1, 0];
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return [coding, 8, 4, 2, 3, 0];
|
||||||
|
yield return [coding, 12, 7, 0, 1, 5];
|
||||||
|
yield return [coding, 16, 4, 0, 3, 0];
|
||||||
|
yield return [coding, 16, 6, 3, 1, 9];
|
||||||
|
yield return [coding, 2, 1, 0, 1, 0];
|
||||||
|
yield return [coding, 8, 5, 0, 3, 4];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(LosslessCases))]
|
||||||
|
public void LosslessFilesGiveBackTheirSamples(JpegTestCoding coding, int precision, int predictor, int pointTransform, int components, int restart)
|
||||||
|
{
|
||||||
|
const int width = 23;
|
||||||
|
const int height = 14;
|
||||||
|
var random = new Random((precision * 100) + predictor);
|
||||||
|
var max = (1 << precision) - 1;
|
||||||
|
var planes = new List<(int Id, int H, int V, int[] Samples)>();
|
||||||
|
for (var c = 0; c < components; c++)
|
||||||
|
{
|
||||||
|
var samples = new int[width * height];
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
// A ramp with noise, plus a hard step: large and small differences both occur.
|
||||||
|
var value = ((x + (2 * y) + (c * 7)) * max / (width + (2 * height) + 14)) + random.Next(-3, 4) + (x > 15 ? max / 3 : 0);
|
||||||
|
samples[(y * width) + x] = Math.Clamp(value, 0, max);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
planes.Add(((byte)"RGB"[c % 3] + (c / 3), 1, 1, samples));
|
||||||
|
}
|
||||||
|
|
||||||
|
var options = new JpegTestOptions { Coding = coding, Jfif = false, RestartInterval = restart, DcConditioning = restart == 9 ? (1, 3) : (0, 1) };
|
||||||
|
var file = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options);
|
||||||
|
using var image = JpegDecoder.Decode(file);
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
var pixel = image.GetPixel(x, y);
|
||||||
|
for (var c = 0; c < 3; c++)
|
||||||
|
{
|
||||||
|
var sample = planes[components == 1 ? 0 : c].Samples[(y * width) + x];
|
||||||
|
var restored = (sample >> pointTransform) << pointTransform;
|
||||||
|
var expected = precision == 8 ? restored : (int)(((restored * 255L) + (max >> 1)) / max);
|
||||||
|
var actual = c == 0 ? pixel.R : c == 1 ? pixel.G : pixel.B;
|
||||||
|
Assert.AreEqual(expected, actual, $"({x}, {y}) canale {c}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (components == 3)
|
||||||
|
{
|
||||||
|
// The same samples as three separate scans.
|
||||||
|
var separate = JpegTestEncoder.WriteLossless(width, height, precision, planes, predictor, pointTransform, options with { SeparateScans = true });
|
||||||
|
using var again = JpegDecoder.Decode(separate);
|
||||||
|
ImageAssert.AreEqual(image, again, "scansioni separate");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void LosslessWithSamplingFactorsAndInterleavedMcus()
|
||||||
|
{
|
||||||
|
// Grey with factors 2×2 (one component: MCU of one sample) and two components... no: three, with a 2×1 luma.
|
||||||
|
const int width = 19;
|
||||||
|
const int height = 11;
|
||||||
|
var random = new Random(4);
|
||||||
|
var luma = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray();
|
||||||
|
var chroma = Enumerable.Range(0, 10 * height).Select(_ => 128).ToArray();
|
||||||
|
var planes = new List<(int Id, int H, int V, int[] Samples)> { (1, 2, 1, luma), (2, 1, 1, chroma), (3, 1, 1, chroma) };
|
||||||
|
foreach (var coding in new[] { JpegTestCoding.Huffman, JpegTestCoding.Arithmetic })
|
||||||
|
{
|
||||||
|
var file = JpegTestEncoder.WriteLossless(width, height, 8, planes, 1, 0, new JpegTestOptions { Coding = coding, RestartInterval = 10 });
|
||||||
|
using var image = JpegDecoder.Decode(file);
|
||||||
|
|
||||||
|
// Neutral chroma: every pixel is grey with the luma sample.
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
var expected = luma[(y * width) + x];
|
||||||
|
Assert.AreEqual(((byte)expected, (byte)expected, (byte)expected), (image.GetPixel(x, y).R, image.GetPixel(x, y).G, image.GetPixel(x, y).B), $"{coding} ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheArithmeticCoderRoundTripsLongRandomDecisions()
|
||||||
|
{
|
||||||
|
// Many blocks of random coefficients exercise carries, stacked 0xFF bytes and every state of Table D.2.
|
||||||
|
var random = new Random(31);
|
||||||
|
const int width = 64;
|
||||||
|
const int height = 64;
|
||||||
|
var samples = Enumerable.Range(0, width * height).Select(_ => random.Next(256)).ToArray();
|
||||||
|
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||||||
|
var coefficients = JpegEncoder.TransformPlanes(width, height, 8, [(1, 1, 1, 0, samples)], [fine], 0xC9);
|
||||||
|
foreach (var progressive in new[] { false, true })
|
||||||
|
{
|
||||||
|
var file = JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = progressive });
|
||||||
|
AssertSameCoefficients(coefficients, JpegDecoder.DecodeCoefficients(file), $"progressivo {progressive}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheArithmeticTablesHaveOneEntryPerState()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(114, JpegArithmeticTable.Qe.Length);
|
||||||
|
Assert.AreEqual(114, JpegArithmeticTable.NextLps.Length);
|
||||||
|
Assert.AreEqual(114, JpegArithmeticTable.NextMps.Length);
|
||||||
|
for (var i = 0; i < 113; i++)
|
||||||
|
{
|
||||||
|
Assert.IsLessThan(113, (int)JpegArithmeticTable.NextLps[i], $"stato {i}");
|
||||||
|
Assert.IsLessThan(113, (int)JpegArithmeticTable.NextMps[i], $"stato {i}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A few rows of T.81 Table D.2, checked by hand against the Recommendation.
|
||||||
|
Assert.AreEqual((0x5A1D, 1, 1, true), (JpegArithmeticTable.Qe[0], (int)JpegArithmeticTable.NextLps[0], (int)JpegArithmeticTable.NextMps[0], JpegArithmeticTable.Switches(0)));
|
||||||
|
Assert.AreEqual((0x0001, 12, 13, false), (JpegArithmeticTable.Qe[13], (int)JpegArithmeticTable.NextLps[13], (int)JpegArithmeticTable.NextMps[13], JpegArithmeticTable.Switches(13)));
|
||||||
|
Assert.AreEqual((0x002C, 33, 9, false), (JpegArithmeticTable.Qe[35], (int)JpegArithmeticTable.NextLps[35], (int)JpegArithmeticTable.NextMps[35], JpegArithmeticTable.Switches(35)));
|
||||||
|
Assert.AreEqual((0x2516, 86, 71, false), (JpegArithmeticTable.Qe[87], (int)JpegArithmeticTable.NextLps[87], (int)JpegArithmeticTable.NextMps[87], JpegArithmeticTable.Switches(87)));
|
||||||
|
Assert.AreEqual((0x59EB, 112, 111, true), (JpegArithmeticTable.Qe[112], (int)JpegArithmeticTable.NextLps[112], (int)JpegArithmeticTable.NextMps[112], JpegArithmeticTable.Switches(112)));
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void AssertSameCoefficients(JpegCoefficients expected, JpegCoefficients actual, string what)
|
||||||
|
{
|
||||||
|
Assert.AreEqual((expected.Width, expected.Height, expected.Precision), (actual.Width, actual.Height, actual.Precision), what);
|
||||||
|
Assert.HasCount(expected.Components.Count, actual.Components, what);
|
||||||
|
for (var i = 0; i < expected.Components.Count; i++)
|
||||||
|
{
|
||||||
|
var e = expected.Components[i];
|
||||||
|
var a = actual.Components[i];
|
||||||
|
Assert.AreEqual((e.Id, e.H, e.V, e.BlocksWide, e.BlocksHigh), (a.Id, a.H, a.V, a.BlocksWide, a.BlocksHigh), $"{what}, componente {i}");
|
||||||
|
CollectionAssert.AreEqual(e.Quantization, a.Quantization, $"{what}, quantizzazione {i}");
|
||||||
|
for (var by = 0; by < e.BlocksHigh; by++)
|
||||||
|
{
|
||||||
|
for (var bx = 0; bx < e.BlocksWide; bx++)
|
||||||
|
{
|
||||||
|
var eb = e.Block(bx, by);
|
||||||
|
var ab = a.Block(bx, by);
|
||||||
|
if (!eb.SequenceEqual(ab))
|
||||||
|
{
|
||||||
|
var k = 0;
|
||||||
|
while (eb[k] == ab[k])
|
||||||
|
{
|
||||||
|
k++;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Fail($"{what}: componente {i}, blocco ({bx}, {by}), coefficiente {k}: atteso {eb[k]}, letto {ab[k]}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int CountRestartMarkers(byte[] file)
|
||||||
|
{
|
||||||
|
var count = 0;
|
||||||
|
for (var i = 0; i + 1 < file.Length; i++)
|
||||||
|
{
|
||||||
|
if (file[i] == 0xFF && file[i + 1] is >= 0xD0 and <= 0xD7)
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<JpegTestScan> SpectralOnly(int count)
|
||||||
|
{
|
||||||
|
var all = Enumerable.Range(0, count).ToArray();
|
||||||
|
var scans = new List<JpegTestScan> { new(all, 0, 0, 0, 0) };
|
||||||
|
foreach (var c in all)
|
||||||
|
{
|
||||||
|
scans.Add(new([c], 1, 1, 0, 0));
|
||||||
|
scans.Add(new([c], 2, 9, 0, 0));
|
||||||
|
scans.Add(new([c], 10, 63, 0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
return scans;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<JpegTestScan> ManyApproximations(int count)
|
||||||
|
{
|
||||||
|
var all = Enumerable.Range(0, count).ToArray();
|
||||||
|
var scans = new List<JpegTestScan> { new(all, 0, 0, 0, 4) };
|
||||||
|
for (var al = 3; al >= 0; al--)
|
||||||
|
{
|
||||||
|
scans.Add(new(all, 0, 0, al + 1, al));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var c in all)
|
||||||
|
{
|
||||||
|
scans.Add(new([c], 1, 63, 0, 5));
|
||||||
|
for (var al = 4; al >= 0; al--)
|
||||||
|
{
|
||||||
|
scans.Add(new([c], 1, 63, al + 1, al));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return scans;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RgbaImage Opaque(RgbaImage image)
|
||||||
|
{
|
||||||
|
var copy = new RgbaImage(image.Width, image.Height, image.ToArray());
|
||||||
|
var pixels = copy.Pixels;
|
||||||
|
for (var i = 3; i < pixels.Length; i += 4)
|
||||||
|
{
|
||||||
|
pixels[i] = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int[] R, int[] G, int[] B) Channels(RgbaImage image)
|
||||||
|
{
|
||||||
|
var n = image.Width * image.Height;
|
||||||
|
var r = new int[n];
|
||||||
|
var g = new int[n];
|
||||||
|
var b = new int[n];
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
r[i] = image.Pixels[i * 4];
|
||||||
|
g[i] = image.Pixels[(i * 4) + 1];
|
||||||
|
b[i] = image.Pixels[(i * 4) + 2];
|
||||||
|
}
|
||||||
|
|
||||||
|
return (r, g, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int Y, int Cb, int Cr) ToYCbCr(int r, int g, int b) =>
|
||||||
|
(
|
||||||
|
Math.Clamp((int)Math.Round((0.299 * r) + (0.587 * g) + (0.114 * b)), 0, 255),
|
||||||
|
Math.Clamp((int)Math.Round((-0.168736 * r) - (0.331264 * g) + (0.5 * b) + 128), 0, 255),
|
||||||
|
Math.Clamp((int)Math.Round((0.5 * r) - (0.418688 * g) - (0.081312 * b) + 128), 0, 255));
|
||||||
|
|
||||||
|
private static (int[] Y, int[] Cb, int[] Cr) YCbCrPlanes(RgbaImage image)
|
||||||
|
{
|
||||||
|
var (r, g, b) = Channels(image);
|
||||||
|
var y = new int[r.Length];
|
||||||
|
var cb = new int[r.Length];
|
||||||
|
var cr = new int[r.Length];
|
||||||
|
for (var i = 0; i < r.Length; i++)
|
||||||
|
{
|
||||||
|
(y[i], cb[i], cr[i]) = ToYCbCr(r[i], g[i], b[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (y, cb, cr);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A full-resolution plane averaged down to a component with factors (h, v) of a frame with maxima (maxH, maxV).</summary>
|
||||||
|
private static int[] Downsample(int[] plane, int width, int height, int maxH, int maxV, int h, int v)
|
||||||
|
{
|
||||||
|
var cw = ((width * h) + maxH - 1) / maxH;
|
||||||
|
var ch = ((height * v) + maxV - 1) / maxV;
|
||||||
|
var result = new int[cw * ch];
|
||||||
|
for (var y = 0; y < ch; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < cw; x++)
|
||||||
|
{
|
||||||
|
var sum = 0;
|
||||||
|
var count = 0;
|
||||||
|
for (var sy = y * maxV / v; sy < Math.Min(height, (y + 1) * maxV / v); sy++)
|
||||||
|
{
|
||||||
|
for (var sx = x * maxH / h; sx < Math.Min(width, (x + 1) * maxH / h); sx++)
|
||||||
|
{
|
||||||
|
sum += plane[(sy * width) + sx];
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result[(y * cw) + x] = count == 0 ? 128 : (sum + (count / 2)) / count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The in-house baseline JPEG encoder: the files it writes read back close to the source with our decoder, quality
|
||||||
|
/// moves size and fidelity the right way, metadata (EXIF, ICC in chunks, XMP, comments) survives the round trip, and
|
||||||
|
/// what cannot be written is refused.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class JpegEncoderTests
|
||||||
|
{
|
||||||
|
public TestContext TestContext { get; set; } = null!;
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheAnnexKTablesAreComplete()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(12, Sum(JpegTables.LuminanceDcCounts));
|
||||||
|
Assert.AreEqual(12, Sum(JpegTables.ChrominanceDcCounts));
|
||||||
|
Assert.AreEqual(162, Sum(JpegTables.LuminanceAcCounts));
|
||||||
|
Assert.AreEqual(162, Sum(JpegTables.ChrominanceAcCounts));
|
||||||
|
Assert.HasCount(162, JpegTables.LuminanceAcValues);
|
||||||
|
Assert.HasCount(162, JpegTables.ChrominanceAcValues);
|
||||||
|
|
||||||
|
// Every (run, size) pair with size 1..10, plus EOB and ZRL: the full AC alphabet.
|
||||||
|
var expected = new HashSet<byte> { 0x00, 0xF0 };
|
||||||
|
for (var run = 0; run < 16; run++)
|
||||||
|
{
|
||||||
|
for (var size = 1; size <= 10; size++)
|
||||||
|
{
|
||||||
|
expected.Add((byte)((run << 4) | size));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(expected.SetEquals(JpegTables.LuminanceAcValues.ToArray()));
|
||||||
|
Assert.IsTrue(expected.SetEquals(JpegTables.ChrominanceAcValues.ToArray()));
|
||||||
|
|
||||||
|
// Zig-zag is a permutation that starts 0, 1, 8, 16, 9, 2 and ends at 63.
|
||||||
|
var zigzag = JpegTables.ZigZag.ToArray();
|
||||||
|
CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), zigzag.Select(v => (int)v).ToArray());
|
||||||
|
CollectionAssert.AreEqual(new[] { 0, 1, 8, 16, 9, 2 }, zigzag.Take(6).Select(v => (int)v).ToArray());
|
||||||
|
Assert.AreEqual(63, (int)zigzag[63]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void QualityScalesTheStandardTables()
|
||||||
|
{
|
||||||
|
var at50 = JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 50);
|
||||||
|
CollectionAssert.AreEqual(JpegTables.LuminanceQuantization.ToArray().Select(v => (int)v).ToArray(), at50.Select(v => (int)v).ToArray());
|
||||||
|
Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 100).All(v => v == 1));
|
||||||
|
Assert.IsTrue(JpegTables.ScaledQuantization(JpegTables.ChrominanceQuantization, 1).All(v => v == 255));
|
||||||
|
|
||||||
|
// 16 at q50 becomes (16 × 20 + 50) / 100 = 3 at q90.
|
||||||
|
Assert.AreEqual(3, (int)JpegTables.ScaledQuantization(JpegTables.LuminanceQuantization, 90)[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> RoundTrips =>
|
||||||
|
[
|
||||||
|
[JpegSubsampling.Ratio420, false, 90, 38.0],
|
||||||
|
[JpegSubsampling.Ratio444, false, 90, 40.0],
|
||||||
|
[JpegSubsampling.Ratio444, false, 100, 48.0],
|
||||||
|
[JpegSubsampling.Ratio420, true, 85, 40.0],
|
||||||
|
];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(RoundTrips))]
|
||||||
|
public void EncodedImagesReadBackCloseToTheSource(JpegSubsampling subsampling, bool grey, int quality, double minimum)
|
||||||
|
{
|
||||||
|
using var source = Opaque(TestImages.Gradient(97, 61, 21), grey);
|
||||||
|
var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = subsampling, Grayscale = grey });
|
||||||
|
Assert.IsTrue(JpegDecoder.IsJpeg(file));
|
||||||
|
using var decoded = JpegDecoder.Decode(file, out var info);
|
||||||
|
Assert.AreEqual((97, 61, false, ImageFormat.Jpeg), (info.Width, info.Height, info.HasAlpha, info.Format));
|
||||||
|
var result = ImageQuality.Compare(source, decoded);
|
||||||
|
TestContext.WriteLine($"{subsampling}, grigio {grey}, q{quality}: {file.Length} byte, {result}");
|
||||||
|
Assert.IsGreaterThanOrEqualTo(minimum, result.MinPsnr, result.ToString());
|
||||||
|
Assert.AreEqual(0.0, result.FarOff, result.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void HigherQualityMeansLargerFilesAndCloserPixels()
|
||||||
|
{
|
||||||
|
using var source = Opaque(PngDecoder.Decode(ReferenceImages.Get("png-skia-rgb").ReadInput()), false);
|
||||||
|
var lastSize = 0;
|
||||||
|
var lastPsnr = 0.0;
|
||||||
|
foreach (var quality in new[] { 10, 30, 50, 75, 90, 100 })
|
||||||
|
{
|
||||||
|
// 4:4:4: the image is pixel-level noise in blue, which 4:2:0 cannot keep at any quality.
|
||||||
|
var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality, Subsampling = JpegSubsampling.Ratio444 });
|
||||||
|
using var decoded = JpegDecoder.Decode(file);
|
||||||
|
var result = ImageQuality.Compare(source, decoded);
|
||||||
|
TestContext.WriteLine($"q{quality}: {file.Length} byte, {result}");
|
||||||
|
Assert.IsGreaterThan(lastSize, file.Length, $"q{quality}");
|
||||||
|
Assert.IsGreaterThan(lastPsnr, result.MinPsnr, $"q{quality}");
|
||||||
|
lastSize = file.Length;
|
||||||
|
lastPsnr = result.MinPsnr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheReferenceImagesSurviveReEncoding()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
|
||||||
|
{
|
||||||
|
using var original = JpegDecoder.Decode(reference.ReadInput());
|
||||||
|
var file = JpegEncoder.Encode(original, new JpegEncoderOptions { Quality = 100, Subsampling = JpegSubsampling.Ratio444 });
|
||||||
|
using var again = JpegDecoder.Decode(file);
|
||||||
|
var result = ImageQuality.Compare(original, again);
|
||||||
|
TestContext.WriteLine($"{reference.Name}: {result}");
|
||||||
|
ImageQuality.AssertClose(result, reference.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TinyAndOddSizesWork()
|
||||||
|
{
|
||||||
|
foreach (var (width, height) in new[] { (1, 1), (1, 17), (17, 1), (8, 8), (9, 9), (15, 16), (16, 15), (33, 7) })
|
||||||
|
{
|
||||||
|
using var source = Opaque(TestImages.Gradient(width, height, width + height), false);
|
||||||
|
foreach (var subsampling in new[] { JpegSubsampling.Ratio420, JpegSubsampling.Ratio444 })
|
||||||
|
{
|
||||||
|
var file = JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = 100, Subsampling = subsampling });
|
||||||
|
using var decoded = JpegDecoder.Decode(file);
|
||||||
|
Assert.AreEqual((width, height), (decoded.Width, decoded.Height));
|
||||||
|
var result = ImageQuality.Compare(source, decoded);
|
||||||
|
if (subsampling == JpegSubsampling.Ratio444)
|
||||||
|
{
|
||||||
|
Assert.IsLessThanOrEqualTo(8, result.MaxDifference, $"{width}×{height} {subsampling}: {result}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// The source has per-pixel noise: averaged chroma loses some of it.
|
||||||
|
Assert.IsGreaterThanOrEqualTo(25, result.MinPsnr, $"{width}×{height} {subsampling}: {result}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void RestartIntervalsDoNotChangeThePixels()
|
||||||
|
{
|
||||||
|
using var source = Opaque(TestImages.Gradient(70, 45, 8), false);
|
||||||
|
using var plain = JpegDecoder.Decode(JpegEncoder.Encode(source));
|
||||||
|
foreach (var interval in new[] { 1, 3, 65535 })
|
||||||
|
{
|
||||||
|
using var restarted = JpegDecoder.Decode(JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = interval }));
|
||||||
|
ImageAssert.AreEqual(plain, restarted, $"intervallo {interval}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheStreamOverloadWritesTheSameBytes()
|
||||||
|
{
|
||||||
|
using var source = TestImages.Gradient(20, 20, 1);
|
||||||
|
using var stream = new MemoryStream();
|
||||||
|
JpegEncoder.Encode(source, stream);
|
||||||
|
CollectionAssert.AreEqual(JpegEncoder.Encode(source), stream.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MetadataSurvivesTheRoundTrip()
|
||||||
|
{
|
||||||
|
using var source = TestImages.Gradient(30, 20, 2);
|
||||||
|
var exif = Tiff(orientation: 6);
|
||||||
|
var random = new Random(66);
|
||||||
|
var icc = new byte[150_000];
|
||||||
|
random.NextBytes(icc);
|
||||||
|
"acsp"u8.CopyTo(icc.AsSpan(36));
|
||||||
|
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF/></x:xmpmeta>";
|
||||||
|
var options = new JpegEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp, Comments = ["primo commento", "secondo, con àccenti"] };
|
||||||
|
var file = JpegEncoder.Encode(source, options);
|
||||||
|
|
||||||
|
// 150 000 bytes need three APP2 chunks of at most 65 519.
|
||||||
|
Assert.AreEqual(3, CountSegments(file, 0xE2));
|
||||||
|
|
||||||
|
var info = JpegDecoder.Identify(file);
|
||||||
|
CollectionAssert.AreEqual(exif, info.Metadata.Exif);
|
||||||
|
Assert.AreEqual(6, info.Metadata.Orientation);
|
||||||
|
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
|
||||||
|
Assert.AreEqual(xmp, info.Metadata.Xmp);
|
||||||
|
CollectionAssert.AreEqual(new[] { "primo commento", "secondo, con àccenti" }, info.Metadata.Texts.Select(t => t.Text).ToArray());
|
||||||
|
|
||||||
|
// The orientation is reported, not applied: the pixels keep their stored layout.
|
||||||
|
using var decoded = JpegDecoder.Decode(file);
|
||||||
|
Assert.AreEqual((30, 20), (decoded.Width, decoded.Height));
|
||||||
|
Assert.IsGreaterThan(30, ImageQuality.Compare(Opaque(source, false), decoded).MinPsnr);
|
||||||
|
|
||||||
|
// Without metadata only JFIF is written.
|
||||||
|
var bare = JpegDecoder.Identify(JpegEncoder.Encode(source));
|
||||||
|
Assert.IsNull(bare.Metadata.Exif);
|
||||||
|
Assert.IsNull(bare.Metadata.IccProfile);
|
||||||
|
Assert.IsNull(bare.Metadata.Xmp);
|
||||||
|
Assert.IsEmpty(bare.Metadata.Texts);
|
||||||
|
Assert.AreEqual(1, bare.Metadata.Orientation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void WhatCannotBeWrittenIsRefused()
|
||||||
|
{
|
||||||
|
using var source = TestImages.Gradient(8, 8, 1);
|
||||||
|
foreach (var quality in new[] { 0, -5, 101 })
|
||||||
|
{
|
||||||
|
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality }), $"qualità {quality}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = -1 }));
|
||||||
|
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = 65536 }));
|
||||||
|
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = "non TIFF"u8.ToArray() }));
|
||||||
|
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = Tiff(1, padding: 70_000) }));
|
||||||
|
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Xmp = new string('x', 70_000) }));
|
||||||
|
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { IccProfile = new byte[256 * 65519] }));
|
||||||
|
Assert.Throws<ArgumentException>(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Comments = [new string('c', 70_000)] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Tiff(int orientation, int padding = 0)
|
||||||
|
{
|
||||||
|
// Little-endian TIFF header, IFD0 at 8 with one entry: Orientation (0x0112), SHORT, count 1.
|
||||||
|
var tiff = new byte[8 + 2 + 12 + 4 + padding];
|
||||||
|
"II*\0"u8.CopyTo(tiff);
|
||||||
|
tiff[4] = 8;
|
||||||
|
tiff[8] = 1;
|
||||||
|
tiff[10] = 0x12;
|
||||||
|
tiff[11] = 0x01;
|
||||||
|
tiff[12] = 3;
|
||||||
|
tiff[14] = 1;
|
||||||
|
tiff[18] = (byte)orientation;
|
||||||
|
return tiff;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int CountSegments(byte[] file, int marker)
|
||||||
|
{
|
||||||
|
var count = 0;
|
||||||
|
var pos = 2;
|
||||||
|
while (pos + 4 <= file.Length && file[pos] == 0xFF && file[pos + 1] != 0xDA)
|
||||||
|
{
|
||||||
|
if (file[pos + 1] == marker)
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Sum(ReadOnlySpan<byte> counts)
|
||||||
|
{
|
||||||
|
var sum = 0;
|
||||||
|
foreach (var c in counts)
|
||||||
|
{
|
||||||
|
sum += c;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The image with alpha 255 (JPEG has none) and, for grey, R = G = B.</summary>
|
||||||
|
private static RgbaImage Opaque(RgbaImage image, bool grey)
|
||||||
|
{
|
||||||
|
var pixels = image.ToArray();
|
||||||
|
for (var i = 0; i < pixels.Length; i += 4)
|
||||||
|
{
|
||||||
|
if (grey)
|
||||||
|
{
|
||||||
|
var y = (byte)(((pixels[i] * 299) + (pixels[i + 1] * 587) + (pixels[i + 2] * 114) + 500) / 1000);
|
||||||
|
pixels[i] = pixels[i + 1] = pixels[i + 2] = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
pixels[i + 3] = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RgbaImage(image.Width, image.Height, pixels);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (no EOI, bytes after EOI,
|
||||||
|
/// no DHT as in Motion JPEG), refuses what it cannot read with the right exception, and never fails in any other way.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class JpegMalformedTests
|
||||||
|
{
|
||||||
|
private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 };
|
||||||
|
|
||||||
|
private static byte[] Baseline(int width = 37, int height = 21, int restart = 0) =>
|
||||||
|
JpegEncoder.Encode(TestImages.Gradient(width, height, 3), new JpegEncoderOptions { Quality = 80, RestartInterval = restart });
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ABaselineFileCutInsideItsScanIsDamaged()
|
||||||
|
{
|
||||||
|
foreach (var restart in new[] { 0, 2 })
|
||||||
|
{
|
||||||
|
var file = Baseline(restart: restart);
|
||||||
|
// Identify needs the headers up to the frame, not the scan.
|
||||||
|
var sof = SegmentOffset(file, 0xC0);
|
||||||
|
var frameEnd = sof + 2 + ((file[sof + 2] << 8) | file[sof + 3]);
|
||||||
|
using var whole = JpegDecoder.Decode(file);
|
||||||
|
for (var length = 0; length < file.Length - 2; length++)
|
||||||
|
{
|
||||||
|
var cut = file[..length];
|
||||||
|
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(cut), $"ripristino {restart}, {length} di {file.Length} byte");
|
||||||
|
if (length < frameEnd)
|
||||||
|
{
|
||||||
|
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Identify(cut), $"Identify, {length} byte");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the EOI missing: complete scans are accepted.
|
||||||
|
using var withoutEoi = JpegDecoder.Decode(file[..^2]);
|
||||||
|
ImageAssert.AreEqual(whole, withoutEoi, $"senza EOI, ripristino {restart}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AFileCutAfterItsHeadersFailsAtTheFirstMcuRow()
|
||||||
|
{
|
||||||
|
// Headers of 8192×8192 (64 megapixels, within the default limits) and not one byte of the scan. The reader
|
||||||
|
// gives zero bits past the end, which are valid codes of the Annex K tables, so before the check per MCU row
|
||||||
|
// the decoder went through all 262,144 MCUs (seconds of IDCT) before failing; now it stops after one row.
|
||||||
|
foreach (var lossless in new[] { false, true })
|
||||||
|
{
|
||||||
|
var file = lossless ? JpegTestEncoder.WriteLossless(16, 16, 8, [(1, 1, 1, new int[256])], 1, 0, new JpegTestOptions()) : Baseline(16, 16);
|
||||||
|
var sof = SegmentOffset(file, lossless ? 0xC3 : 0xC0);
|
||||||
|
var sos = SegmentOffset(file, 0xDA);
|
||||||
|
var headers = file[..(sos + 2 + ((file[sos + 2] << 8) | file[sos + 3]))];
|
||||||
|
headers[sof + 5] = headers[sof + 7] = 0x20;
|
||||||
|
headers[sof + 6] = headers[sof + 8] = 0x00;
|
||||||
|
var clock = System.Diagnostics.Stopwatch.StartNew();
|
||||||
|
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(headers), lossless ? "senza perdita" : "base");
|
||||||
|
clock.Stop();
|
||||||
|
StringAssert.Contains(error.Message, "troncato");
|
||||||
|
|
||||||
|
// Planes of 64 MB are still allocated; decoding every MCU took several seconds even in Release.
|
||||||
|
Assert.IsLessThan(2000, clock.ElapsedMilliseconds, $"{(lossless ? "senza perdita" : "base")}: {clock.ElapsedMilliseconds} ms");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void BytesAfterTheEndAreIgnored()
|
||||||
|
{
|
||||||
|
var file = Baseline();
|
||||||
|
using var whole = JpegDecoder.Decode(file);
|
||||||
|
var random = new Random(5);
|
||||||
|
var tail = new byte[300];
|
||||||
|
random.NextBytes(tail);
|
||||||
|
byte[] longer = [.. file, .. tail];
|
||||||
|
using var withTail = JpegDecoder.Decode(longer);
|
||||||
|
ImageAssert.AreEqual(whole, withTail, "byte dopo EOI");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void FillBytesAndGarbageBetweenSegmentsAreSkipped()
|
||||||
|
{
|
||||||
|
var file = Baseline();
|
||||||
|
using var whole = JpegDecoder.Decode(file);
|
||||||
|
var dqt = SegmentOffset(file, 0xDB);
|
||||||
|
|
||||||
|
// T.81 B.1.1.2: any marker may be preceded by fill bytes 0xFF.
|
||||||
|
byte[] padded = [.. file[..dqt], 0xFF, 0xFF, 0xFF, .. file[dqt..]];
|
||||||
|
using var filled = JpegDecoder.Decode(padded);
|
||||||
|
ImageAssert.AreEqual(whole, filled, "byte di riempimento");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void WithoutDhtTheAnnexKTablesAreUsed()
|
||||||
|
{
|
||||||
|
// Motion JPEG frames omit DHT and rely on the tables of Annex K, which are the ones our encoder writes.
|
||||||
|
var file = Baseline();
|
||||||
|
using var whole = JpegDecoder.Decode(file);
|
||||||
|
var stripped = RemoveSegments(file, 0xC4);
|
||||||
|
Assert.IsLessThan(file.Length, stripped.Length);
|
||||||
|
using var decoded = JpegDecoder.Decode(stripped);
|
||||||
|
ImageAssert.AreEqual(whole, decoded, "senza DHT");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void HierarchicalAndTwoComponentFilesAreNotSupported()
|
||||||
|
{
|
||||||
|
var file = Baseline();
|
||||||
|
foreach (var marker in new byte[] { 0xC5, 0xC6, 0xC7, 0xCD, 0xCE, 0xCF })
|
||||||
|
{
|
||||||
|
var changed = file.ToArray();
|
||||||
|
changed[SegmentOffset(file, 0xC0) + 1] = marker;
|
||||||
|
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(changed), $"SOF 0x{marker:X2}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var fine = Enumerable.Repeat((ushort)1, 64).ToArray();
|
||||||
|
var samples = new int[16 * 16];
|
||||||
|
var two = JpegEncoder.TransformPlanes(16, 16, 8, [(1, 1, 1, 0, samples), (2, 1, 1, 0, samples)], [fine], 0xC1);
|
||||||
|
var twoFile = JpegTestEncoder.Write(two, new JpegTestOptions());
|
||||||
|
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => JpegDecoder.Decode(twoFile));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DamagedHeadersAreRefused()
|
||||||
|
{
|
||||||
|
var file = Baseline();
|
||||||
|
var sof = SegmentOffset(file, 0xC0);
|
||||||
|
var sos = SegmentOffset(file, 0xDA);
|
||||||
|
|
||||||
|
// Width 0.
|
||||||
|
var zeroWidth = file.ToArray();
|
||||||
|
zeroWidth[sof + 7] = 0;
|
||||||
|
zeroWidth[sof + 8] = 0;
|
||||||
|
AssertDamaged(zeroWidth, "larghezza 0");
|
||||||
|
|
||||||
|
// Height 0 and no DNL segment after the first scan.
|
||||||
|
var zeroHeight = file.ToArray();
|
||||||
|
zeroHeight[sof + 5] = 0;
|
||||||
|
zeroHeight[sof + 6] = 0;
|
||||||
|
AssertDamaged(zeroHeight, "altezza 0 senza DNL");
|
||||||
|
|
||||||
|
// Precision 7.
|
||||||
|
var precision = file.ToArray();
|
||||||
|
precision[sof + 4] = 7;
|
||||||
|
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(precision), "precisione 7");
|
||||||
|
|
||||||
|
// Sampling factor 0 and 5.
|
||||||
|
foreach (var factor in new byte[] { 0x01, 0x10, 0x51, 0x15 })
|
||||||
|
{
|
||||||
|
var sampling = file.ToArray();
|
||||||
|
sampling[sof + 11] = factor;
|
||||||
|
AssertDamaged(sampling, $"campionamento 0x{factor:X2}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A scan naming a component the frame does not have.
|
||||||
|
var unknown = file.ToArray();
|
||||||
|
unknown[sos + 5] = 99;
|
||||||
|
AssertDamaged(unknown, "componente sconosciuto");
|
||||||
|
|
||||||
|
// A scan referring to a Huffman table that was never defined (slot 3).
|
||||||
|
var table = file.ToArray();
|
||||||
|
table[sos + 6] = 0x33;
|
||||||
|
AssertDamaged(table, "tabella di Huffman assente");
|
||||||
|
|
||||||
|
// No quantization table.
|
||||||
|
AssertDamaged(RemoveSegments(file, 0xDB), "senza DQT");
|
||||||
|
|
||||||
|
// A Huffman table with more codes than its lengths allow; the total stays that of the segment's values, so
|
||||||
|
// the error is the oversubscription itself and not a truncated segment.
|
||||||
|
var dht = SegmentOffset(file, 0xC4);
|
||||||
|
var badTable = file.ToArray();
|
||||||
|
// The luminance DC table counts 0,1,5,1,1,...: three codes of length 1, none of length 2, three of length 3.
|
||||||
|
badTable[dht + 5] = 3;
|
||||||
|
badTable[dht + 6] = 0;
|
||||||
|
badTable[dht + 7] = 3;
|
||||||
|
AssertOversubscribed(badTable, "tabella di Huffman impossibile");
|
||||||
|
|
||||||
|
// A segment length that runs past the end.
|
||||||
|
var longSegment = file.ToArray();
|
||||||
|
longSegment[sof + 2] = 0xFF;
|
||||||
|
AssertDamaged(longSegment, "segmento oltre la fine");
|
||||||
|
|
||||||
|
// No SOI, no frame, no scan.
|
||||||
|
AssertDamaged(file[2..], "senza SOI");
|
||||||
|
AssertDamaged([0xFF, 0xD8, 0xFF, 0xD9], "solo SOI ed EOI");
|
||||||
|
AssertDamaged(file[..sos], "senza scansioni");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OversubscribedHuffmanTablesAreRefusedAtEveryLength()
|
||||||
|
{
|
||||||
|
// One code of each length below L leaves room for two codes of length L; three overflow it. The symbols
|
||||||
|
// match the counts, so only the oversubscription can be at fault. Lengths up to 9 used to index past the
|
||||||
|
// lookup table and threw ArgumentOutOfRangeException.
|
||||||
|
for (var length = 1; length <= 16; length++)
|
||||||
|
{
|
||||||
|
var counts = new byte[16];
|
||||||
|
for (var shorter = 1; shorter < length; shorter++)
|
||||||
|
{
|
||||||
|
counts[shorter - 1] = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
counts[length - 1] = 3;
|
||||||
|
Assert.IsTrue(Oversubscribed(counts), $"lunghezza {length}");
|
||||||
|
var values = new byte[length + 2];
|
||||||
|
for (var i = 0; i < values.Length; i++)
|
||||||
|
{
|
||||||
|
values[i] = (byte)i;
|
||||||
|
}
|
||||||
|
|
||||||
|
var error = Assert.ThrowsExactly<ImageDecodeException>(() => JpegHuffmanTable.Build(counts, values), $"lunghezza {length}");
|
||||||
|
StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", $"lunghezza {length}");
|
||||||
|
|
||||||
|
// Two codes of length L fill the code space exactly and are valid.
|
||||||
|
counts[length - 1] = 2;
|
||||||
|
_ = JpegHuffmanTable.Build(counts, values.AsSpan(0, length + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Three codes of length 1 (the case of the review) and a full table that is still valid.
|
||||||
|
var three = new byte[16];
|
||||||
|
three[0] = 3;
|
||||||
|
Assert.ThrowsExactly<ImageDecodeException>(() => JpegHuffmanTable.Build(three, [0, 1, 2]));
|
||||||
|
var full = new byte[16];
|
||||||
|
full[0] = 1;
|
||||||
|
full[1] = 2;
|
||||||
|
_ = JpegHuffmanTable.Build(full, [0, 1, 2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool Oversubscribed(byte[] counts)
|
||||||
|
{
|
||||||
|
long code = 0;
|
||||||
|
for (var length = 1; length <= 16; length++)
|
||||||
|
{
|
||||||
|
code += counts[length - 1];
|
||||||
|
if (code > 1L << length)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
code <<= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheLimitsAreEnforcedBeforeDecoding()
|
||||||
|
{
|
||||||
|
var file = Baseline(200, 150);
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxPixels = 10_000 }));
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWidth = 100 }));
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(file, new ImageLimits { MaxWorkingBytes = 40_000 }));
|
||||||
|
|
||||||
|
// A header claiming 65535 × 65535 is refused at once, not after allocating.
|
||||||
|
var huge = file.ToArray();
|
||||||
|
var sof = SegmentOffset(file, 0xC0);
|
||||||
|
huge[sof + 5] = huge[sof + 6] = huge[sof + 7] = huge[sof + 8] = 0xFF;
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => JpegDecoder.Decode(huge, Small));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnIccProfileWithAMissingChunkIsDropped()
|
||||||
|
{
|
||||||
|
var icc = new byte[140_000];
|
||||||
|
new Random(8).NextBytes(icc);
|
||||||
|
var file = JpegEncoder.Encode(TestImages.Gradient(10, 10, 1), new JpegEncoderOptions { IccProfile = icc });
|
||||||
|
CollectionAssert.AreEqual(icc, JpegDecoder.Identify(file).Metadata.IccProfile);
|
||||||
|
|
||||||
|
// Remove the second of three APP2 chunks.
|
||||||
|
var second = SegmentOffsets(file, 0xE2)[1];
|
||||||
|
var length = (file[second + 2] << 8) | file[second + 3];
|
||||||
|
byte[] missing = [.. file[..second], .. file[(second + 2 + length)..]];
|
||||||
|
Assert.IsNull(JpegDecoder.Identify(missing).Metadata.IccProfile);
|
||||||
|
using var image = JpegDecoder.Decode(missing);
|
||||||
|
Assert.AreEqual(10, image.Width);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void OtherFormatsAreNotJpeg()
|
||||||
|
{
|
||||||
|
var png = ReferenceImages.Of(ReferenceFormat.Png).First().ReadInput();
|
||||||
|
Assert.IsFalse(JpegDecoder.IsJpeg(png));
|
||||||
|
Assert.IsFalse(JpegDecoder.IsJpeg([0xFF, 0xD8]));
|
||||||
|
Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(png));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ChangedBytesInEveryCodingNeverBreakTheDecoder()
|
||||||
|
{
|
||||||
|
using var image = TestImages.Gradient(45, 30, 6);
|
||||||
|
var coefficients = JpegEncoder.Transform(image, new JpegEncoderOptions { Quality = 75 });
|
||||||
|
var lossless = new List<(int Id, int H, int V, int[] Samples)>
|
||||||
|
{
|
||||||
|
(1, 2, 2, Enumerable.Range(0, 45 * 30).Select(i => i % 251).ToArray()),
|
||||||
|
(2, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 13).ToArray()),
|
||||||
|
(3, 1, 1, Enumerable.Range(0, 23 * 15).Select(i => i % 7).ToArray()),
|
||||||
|
};
|
||||||
|
var files = new (string Name, byte[] File)[]
|
||||||
|
{
|
||||||
|
("progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Progressive = true, RestartInterval = 3 })),
|
||||||
|
("aritmetico", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, RestartInterval = 4 })),
|
||||||
|
("aritmetico progressivo", JpegTestEncoder.Write(coefficients, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic, Progressive = true })),
|
||||||
|
("DNL", JpegTestEncoder.Write(coefficients, new JpegTestOptions { HeightInDnl = true })),
|
||||||
|
("senza perdita", JpegTestEncoder.WriteLossless(45, 30, 8, lossless, 4, 0, new JpegTestOptions { RestartInterval = 7 })),
|
||||||
|
("senza perdita aritmetico", JpegTestEncoder.WriteLossless(45, 30, 12, lossless, 7, 1, new JpegTestOptions { Coding = JpegTestCoding.Arithmetic })),
|
||||||
|
};
|
||||||
|
|
||||||
|
var random = new Random(2026);
|
||||||
|
foreach (var (name, file) in files)
|
||||||
|
{
|
||||||
|
using (JpegDecoder.Decode(file, Small))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 150; i++)
|
||||||
|
{
|
||||||
|
var mutated = Mutate(file, random);
|
||||||
|
TryDecode(mutated, $"{name}, modifica {i}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every cut of the file, as the network would leave it.
|
||||||
|
for (var length = 0; length < file.Length; length += 1 + (file.Length / 200))
|
||||||
|
{
|
||||||
|
TryDecode(file[..length], $"{name}, {length} byte");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TryDecode(byte[] bytes, string what)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var decoded = JpegDecoder.Decode(bytes, Small);
|
||||||
|
Assert.IsGreaterThan(0, decoded.Width, what);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
JpegDecoder.Identify(bytes, Small);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Mutate(byte[] original, Random random)
|
||||||
|
{
|
||||||
|
var bytes = original.ToArray();
|
||||||
|
switch (random.Next(3))
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
for (var k = random.Next(1, 9); k > 0; k--)
|
||||||
|
{
|
||||||
|
bytes[random.Next(2, bytes.Length)] = (byte)random.Next(256);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
// Headers: the first segments hold the tables and the frame.
|
||||||
|
bytes[random.Next(2, Math.Min(bytes.Length, 700))] = (byte)(random.Next(3) switch { 0 => 0, 1 => 0xFF, _ => random.Next(256) });
|
||||||
|
return bytes;
|
||||||
|
|
||||||
|
default:
|
||||||
|
var start = random.Next(2, bytes.Length);
|
||||||
|
var length = Math.Min(bytes.Length - start, random.Next(1, 64));
|
||||||
|
for (var k = 0; k < length; k++)
|
||||||
|
{
|
||||||
|
bytes[start + k] ^= 0x5A;
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertDamaged(byte[] file, string what)
|
||||||
|
{
|
||||||
|
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(file), what);
|
||||||
|
Assert.IsNotInstanceOfType<ImageLimitException>(error, what);
|
||||||
|
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void AssertOversubscribed(byte[] file, string what)
|
||||||
|
{
|
||||||
|
var error = Assert.ThrowsExactly<ImageDecodeException>(() => JpegDecoder.Decode(file), what);
|
||||||
|
StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", what);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Offset of the first marker segment of type <paramref name="marker"/> (the 0xFF byte).</summary>
|
||||||
|
private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0];
|
||||||
|
|
||||||
|
private static List<int> SegmentOffsets(byte[] file, int marker)
|
||||||
|
{
|
||||||
|
var found = new List<int>();
|
||||||
|
var pos = 2;
|
||||||
|
while (pos + 4 <= file.Length && file[pos] == 0xFF)
|
||||||
|
{
|
||||||
|
if (file[pos + 1] == marker)
|
||||||
|
{
|
||||||
|
found.Add(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file[pos + 1] == 0xDA)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += 2 + ((file[pos + 2] << 8) | file[pos + 3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] RemoveSegments(byte[] file, int marker)
|
||||||
|
{
|
||||||
|
var result = new List<byte>(file.Length);
|
||||||
|
result.AddRange(file.AsSpan(0, 2));
|
||||||
|
var pos = 2;
|
||||||
|
while (file[pos + 1] != 0xDA)
|
||||||
|
{
|
||||||
|
var length = 2 + ((file[pos + 2] << 8) | file[pos + 3]);
|
||||||
|
if (file[pos + 1] != marker)
|
||||||
|
{
|
||||||
|
result.AddRange(file.AsSpan(pos, length));
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += length;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.AddRange(file.AsSpan(pos));
|
||||||
|
return [.. result];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The in-house JPEG decoder against the SkiaSharp (libjpeg-turbo) reads of the reference set. JPEG is lossy and two
|
||||||
|
/// correct decoders differ by the rounding of their IDCT and upsampling, so the comparison has thresholds instead of
|
||||||
|
/// equality: every colour channel at least <see cref="ImageQuality.MinimumPsnr"/> dB and at most
|
||||||
|
/// <see cref="ImageQuality.MaximumFarOff"/> of the pixels off by more than <see cref="ImageQuality.FarThreshold"/>.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class JpegReferenceTests
|
||||||
|
{
|
||||||
|
public TestContext TestContext { get; set; } = null!;
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> JpegCases => ReferenceImages.NamesOf(ReferenceFormat.Jpeg);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(JpegCases))]
|
||||||
|
public void TheJpegDecoderIsCloseToTheReference(string name)
|
||||||
|
{
|
||||||
|
var reference = ReferenceImages.Get(name);
|
||||||
|
var input = reference.ReadInput();
|
||||||
|
using var stored = JpegDecoder.Decode(input, out var info);
|
||||||
|
Assert.AreEqual((reference.StoredWidth, reference.StoredHeight), (stored.Width, stored.Height), name);
|
||||||
|
Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, name);
|
||||||
|
Assert.IsTrue(stored.IsOpaque(), name);
|
||||||
|
|
||||||
|
using var shown = ImageQuality.Orient(stored, info.Metadata.Orientation);
|
||||||
|
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
|
||||||
|
var result = ImageQuality.Compare(expected, shown);
|
||||||
|
TestContext.WriteLine($"{name}: {result}");
|
||||||
|
ImageQuality.AssertClose(result, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheFacadeReadsJpegAndIdentifyAgreesWithDecode()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
|
||||||
|
{
|
||||||
|
var input = reference.ReadInput();
|
||||||
|
using var viaFacade = ImageDecoder.Decode(input);
|
||||||
|
using var direct = JpegDecoder.Decode(input, pooled: true);
|
||||||
|
ImageAssert.AreEqual(direct, viaFacade, reference.Name);
|
||||||
|
|
||||||
|
var info = ImageDecoder.Identify(input);
|
||||||
|
Assert.AreEqual((ImageFormat.Jpeg, reference.StoredWidth, reference.StoredHeight, 1, false), (info.Format, info.Width, info.Height, info.FrameCount, info.HasAlpha), reference.Name);
|
||||||
|
Assert.AreEqual(reference.Orientation, info.Metadata.Orientation, reference.Name);
|
||||||
|
if (reference.Orientation != 1)
|
||||||
|
{
|
||||||
|
Assert.IsNotNull(info.Metadata.Exif, reference.Name);
|
||||||
|
Assert.IsTrue(info.Metadata.Exif.AsSpan().StartsWith("II*\0"u8) || info.Metadata.Exif.AsSpan().StartsWith("MM\0*"u8), reference.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,383 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Text;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using static Febe.Tests.Imaging.TestImages;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>The in-house PNG decoder and encoder, beyond the reference set: round trips, metadata, damaged files.</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class PngCodecTests
|
||||||
|
{
|
||||||
|
// An 8-bit RGBA row of 2 pixels, filter 0: red opaque, green half transparent.
|
||||||
|
private static readonly byte[] TwoPixels = [0, 255, 0, 0, 255, 0, 255, 0, 128];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheCrcIsTheOneOfThePngSpecification()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(0xCBF43926u, Crc32.Compute("123456789"u8));
|
||||||
|
Assert.AreEqual(0xAE426082u, Crc32.Compute("IEND"u8));
|
||||||
|
|
||||||
|
// Eight bytes at a time and one at a time agree on every length and every split.
|
||||||
|
var data = new byte[300];
|
||||||
|
new Random(7).NextBytes(data);
|
||||||
|
for (var length = 0; length <= data.Length; length += 7)
|
||||||
|
{
|
||||||
|
var whole = Crc32.Compute(data.AsSpan(0, length));
|
||||||
|
Assert.AreEqual(BitwiseCrc(data.AsSpan(0, length)), whole, $"lunghezza {length}");
|
||||||
|
var split = length / 3;
|
||||||
|
Assert.AreEqual(whole, Crc32.Append(Crc32.Compute(data.AsSpan(0, split)), data.AsSpan(split, length - split)), $"divisa a {split}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DataRow(PngFilterStrategy.Adaptive)]
|
||||||
|
[DataRow(PngFilterStrategy.None)]
|
||||||
|
[DataRow(PngFilterStrategy.Sub)]
|
||||||
|
[DataRow(PngFilterStrategy.Up)]
|
||||||
|
[DataRow(PngFilterStrategy.Average)]
|
||||||
|
[DataRow(PngFilterStrategy.Paeth)]
|
||||||
|
public void EveryFilterStrategyRoundTrips(PngFilterStrategy filter)
|
||||||
|
{
|
||||||
|
var seed = 11;
|
||||||
|
foreach (var (width, height) in new[] { (1, 1), (2, 3), (17, 5), (300, 7), (5, 300) })
|
||||||
|
{
|
||||||
|
using var image = TestImages.Random(width, height, seed++);
|
||||||
|
var png = PngEncoder.Encode(image, new PngEncoderOptions { Filter = filter });
|
||||||
|
using var back = PngDecoder.Decode(png);
|
||||||
|
ImageAssert.AreEqual(image, back, $"{filter} {width}×{height}");
|
||||||
|
|
||||||
|
using var smooth = Gradient(width, height, seed++);
|
||||||
|
using var smoothBack = PngDecoder.Decode(PngEncoder.Encode(smooth, new PngEncoderOptions { Filter = filter }));
|
||||||
|
ImageAssert.AreEqual(smooth, smoothBack, $"{filter} {width}×{height} sfumato");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AdaptiveFilteringUsesTheFiveFiltersAndCompressesBetterThanNone()
|
||||||
|
{
|
||||||
|
using var image = Gradient(200, 120, 3);
|
||||||
|
var adaptive = PngEncoder.Encode(image);
|
||||||
|
var none = PngEncoder.Encode(image, new PngEncoderOptions { Filter = PngFilterStrategy.None });
|
||||||
|
Assert.IsLessThan(none.Length, adaptive.Length);
|
||||||
|
|
||||||
|
var raw = Inflate(Join(PngChunks(adaptive).Where(c => c.Type == "IDAT").Select(c => c.Payload).ToArray()));
|
||||||
|
var rowBytes = (200 * 4) + 1;
|
||||||
|
var used = Enumerable.Range(0, 120).Select(y => raw[y * rowBytes]).ToHashSet();
|
||||||
|
Assert.IsTrue(used.All(f => f <= 4), "filtro fuori dalla specifica");
|
||||||
|
Assert.IsGreaterThan(1, used.Count, "il filtro adattivo sceglie per ogni riga");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AutoWritesRgbForAnOpaqueImageAndRgbaOtherwise()
|
||||||
|
{
|
||||||
|
using var opaque = TestImages.Random(9, 4, 1, opaque: true);
|
||||||
|
var png = PngEncoder.Encode(opaque);
|
||||||
|
Assert.AreEqual(2, PngChunks(png)[0].Payload[9], "tipo di colore");
|
||||||
|
using (var back = PngDecoder.Decode(png))
|
||||||
|
{
|
||||||
|
ImageAssert.AreEqual(opaque, back, "RGB");
|
||||||
|
}
|
||||||
|
|
||||||
|
using var translucent = TestImages.Random(9, 4, 2);
|
||||||
|
Assert.AreEqual(6, PngChunks(PngEncoder.Encode(translucent))[0].Payload[9], "tipo di colore");
|
||||||
|
|
||||||
|
// Rgb drops alpha, Rgba keeps it even for an opaque image.
|
||||||
|
using var dropped = PngDecoder.Decode(PngEncoder.Encode(translucent, new PngEncoderOptions { ColorMode = PngColorMode.Rgb }));
|
||||||
|
for (var i = 0; i < dropped.Length; i += 4)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(dropped.Pixels.Slice(i, 3).SequenceEqual(translucent.Pixels.Slice(i, 3)) && dropped.Pixels[i + 3] == 255, $"pixel {i / 4}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(6, PngChunks(PngEncoder.Encode(opaque, new PngEncoderOptions { ColorMode = PngColorMode.Rgba }))[0].Payload[9]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ALargeImageIsSplitIntoSeveralIdatChunks()
|
||||||
|
{
|
||||||
|
using var image = TestImages.Random(300, 300, 5);
|
||||||
|
var png = PngEncoder.Encode(image, new PngEncoderOptions { CompressionLevel = CompressionLevel.NoCompression });
|
||||||
|
var chunks = PngChunks(png);
|
||||||
|
Assert.IsGreaterThan(5, chunks.Count(c => c.Type == "IDAT"));
|
||||||
|
Assert.IsTrue(chunks.Where(c => c.Type == "IDAT").SkipLast(1).All(c => c.Payload.Length == 64 * 1024));
|
||||||
|
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "IEND" }, chunks.Select(c => c.Type).Distinct().ToArray());
|
||||||
|
using var back = PngDecoder.Decode(png);
|
||||||
|
ImageAssert.AreEqual(image, back, "300×300");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryReferenceImageRoundTripsThroughTheEncoder()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.All)
|
||||||
|
{
|
||||||
|
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
|
||||||
|
using var back = PngDecoder.Decode(PngEncoder.Encode(expected));
|
||||||
|
ImageAssert.AreEqual(expected, back, reference.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ExifIccAndXmpAreWrittenBeforeTheDataAndReadBack()
|
||||||
|
{
|
||||||
|
var exif = Join("MM\0*"u8.ToArray(), [0, 0, 0, 8, 0, 0]);
|
||||||
|
var icc = new byte[3000];
|
||||||
|
new Random(9).NextBytes(icc);
|
||||||
|
const string xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><dc:title>Città è più</dc:title></x:xmpmeta>";
|
||||||
|
using var image = TestImages.Random(4, 4, 3);
|
||||||
|
var png = PngEncoder.Encode(image, new PngEncoderOptions
|
||||||
|
{
|
||||||
|
Exif = Join("Exif\0\0"u8.ToArray(), exif),
|
||||||
|
IccProfile = icc,
|
||||||
|
IccProfileName = "Profilo di prova",
|
||||||
|
Xmp = xmp,
|
||||||
|
});
|
||||||
|
|
||||||
|
var types = PngChunks(png).Select(c => c.Type).ToList();
|
||||||
|
CollectionAssert.AreEqual(new[] { "IHDR", "iCCP", "eXIf", "iTXt", "IDAT", "IEND" }, types);
|
||||||
|
|
||||||
|
var info = PngDecoder.Identify(png);
|
||||||
|
CollectionAssert.AreEqual(exif, info.Metadata.Exif, "l'«Exif\\0\\0» di JPEG è tolto");
|
||||||
|
CollectionAssert.AreEqual(icc, info.Metadata.IccProfile);
|
||||||
|
Assert.AreEqual("Profilo di prova", info.Metadata.IccProfileName);
|
||||||
|
Assert.AreEqual(xmp, info.Metadata.Xmp);
|
||||||
|
Assert.IsEmpty(info.Metadata.Texts, "l'XMP non è fra i testi");
|
||||||
|
|
||||||
|
using var decoded = PngDecoder.Decode(png, out var again);
|
||||||
|
Assert.AreEqual(xmp, again.Metadata.Xmp);
|
||||||
|
ImageAssert.AreEqual(image, decoded, "con i metadati");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheEncoderRefusesMetadataItCannotWrite()
|
||||||
|
{
|
||||||
|
using var image = new RgbaImage(1, 1);
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { Exif = [1, 2, 3, 4, 5, 6, 7, 8] }));
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = "" }));
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = new string('a', 80) }));
|
||||||
|
Assert.ThrowsExactly<ArgumentException>(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = "Città€" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TextsAreReadFromTextZtxtAndItxt()
|
||||||
|
{
|
||||||
|
var png = Png(
|
||||||
|
("IHDR", Ihdr(2, 1, 8, 6)),
|
||||||
|
("tEXt", Join(Latin1("Title"), [0], Latin1("Città"))),
|
||||||
|
("zTXt", Join(Latin1("Comment"), [0, 0], Zlib(Latin1(new string('z', 5000))))),
|
||||||
|
("iTXt", Join(Latin1("Description"), [0, 1, 0], Encoding.ASCII.GetBytes("it"), [0], Encoding.UTF8.GetBytes("Descrizione"), [0], Zlib(Encoding.UTF8.GetBytes("Un po' di più €")))),
|
||||||
|
("iTXt", Join(Latin1("Author"), [0, 0, 0, 0, 0], Encoding.UTF8.GetBytes("Alberto"))),
|
||||||
|
("IDAT", Zlib(TwoPixels)),
|
||||||
|
("IEND", []));
|
||||||
|
|
||||||
|
var texts = PngDecoder.Identify(png).Metadata.Texts;
|
||||||
|
Assert.HasCount(4, texts);
|
||||||
|
Assert.AreEqual(new ImageText("Title", "Città"), texts[0]);
|
||||||
|
Assert.AreEqual(new ImageText("Comment", new string('z', 5000)), texts[1]);
|
||||||
|
Assert.AreEqual(new ImageText("Description", "Un po' di più €", "it", "Descrizione"), texts[2]);
|
||||||
|
Assert.AreEqual(new ImageText("Author", "Alberto"), texts[3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void MetadataBeyondTheBudgetIsDroppedAndTheImageStillDecodes()
|
||||||
|
{
|
||||||
|
var bomb = Zlib(new byte[2_000_000]);
|
||||||
|
var png = Png(
|
||||||
|
("IHDR", Ihdr(2, 1, 8, 6)),
|
||||||
|
("zTXt", Join(Latin1("Comment"), [0, 0], bomb)),
|
||||||
|
("iCCP", Join(Latin1("p"), [0, 0], bomb)),
|
||||||
|
("tEXt", Join(Latin1("Title"), [0], Latin1("breve"))),
|
||||||
|
("IDAT", Zlib(TwoPixels)),
|
||||||
|
("IEND", []));
|
||||||
|
var limits = new ImageLimits { MaxMetadataBytes = 1000 };
|
||||||
|
using var image = PngDecoder.Decode(png, out var info, limits);
|
||||||
|
Assert.AreEqual(new ImageText("Title", "breve"), info.Metadata.Texts.Single());
|
||||||
|
Assert.IsNull(info.Metadata.IccProfile);
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((0, 255, 0, 128), image.GetPixel(1, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnAnimatedPngCountsItsFramesAndDecodesTheDefaultImage()
|
||||||
|
{
|
||||||
|
var actl = new byte[8];
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(actl, 3);
|
||||||
|
var png = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("acTL", actl), ("IDAT", Zlib(TwoPixels)), ("fcTL", new byte[26]), ("IEND", []));
|
||||||
|
using var image = PngDecoder.Decode(png, out var info);
|
||||||
|
Assert.AreEqual(3, info.FrameCount);
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void APaletteIndexBeyondThePaletteIsOpaqueBlack()
|
||||||
|
{
|
||||||
|
var png = Png(
|
||||||
|
("IHDR", Ihdr(3, 1, 8, 3)),
|
||||||
|
("PLTE", [10, 20, 30, 40, 50, 60]),
|
||||||
|
("tRNS", [7, 8, 9, 9, 9]),
|
||||||
|
("IDAT", Zlib([0, 0, 1, 2])),
|
||||||
|
("IEND", []));
|
||||||
|
using var image = PngDecoder.Decode(png, out var info);
|
||||||
|
Assert.IsTrue(info.HasAlpha);
|
||||||
|
Assert.AreEqual((10, 20, 30, 7), image.GetPixel(0, 0));
|
||||||
|
Assert.AreEqual((40, 50, 60, 8), image.GetPixel(1, 0));
|
||||||
|
Assert.AreEqual((0, 0, 0, 255), image.GetPixel(2, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ADamagedAncillaryChunkIsSkippedAndADamagedCriticalOneStopsTheDecoding()
|
||||||
|
{
|
||||||
|
var text = Chunk("tEXt", Join(Latin1("Title"), [0], Latin1("x")));
|
||||||
|
text[^1] ^= 1;
|
||||||
|
var png = Join(Png(("IHDR", Ihdr(2, 1, 8, 6))), text, Chunk("IDAT", Zlib(TwoPixels)), Chunk("IEND", []));
|
||||||
|
using (var image = PngDecoder.Decode(png, out var info))
|
||||||
|
{
|
||||||
|
Assert.IsEmpty(info.Metadata.Texts);
|
||||||
|
Assert.AreEqual((0, 255, 0, 128), image.GetPixel(1, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
var idat = Chunk("IDAT", Zlib(TwoPixels));
|
||||||
|
idat[10] ^= 0x40;
|
||||||
|
var broken = Join(Png(("IHDR", Ihdr(2, 1, 8, 6))), idat, Chunk("IEND", []));
|
||||||
|
var error = Assert.ThrowsExactly<ImageDecodeException>(() => PngDecoder.Decode(broken));
|
||||||
|
Assert.Contains("CRC", error.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void DamagedFilesThrowAnImageDecodeException()
|
||||||
|
{
|
||||||
|
var header = ("IHDR", Ihdr(2, 1, 8, 6));
|
||||||
|
var end = ("IEND", Array.Empty<byte>());
|
||||||
|
var cases = new Dictionary<string, byte[]>
|
||||||
|
{
|
||||||
|
["vuoto"] = [],
|
||||||
|
["solo la firma"] = Png(),
|
||||||
|
["non PNG"] = Encoding.ASCII.GetBytes("non sono un'immagine, solo testo"),
|
||||||
|
["senza IHDR"] = Png(("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
["senza IDAT"] = Png(header, end),
|
||||||
|
["IHDR corto"] = Png(("IHDR", new byte[12]), ("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
["larghezza zero"] = Png(("IHDR", Ihdr(0, 1, 8, 6)), ("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
["RGB a 4 bit"] = Png(("IHDR", Ihdr(2, 1, 4, 2)), ("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
["tipo di colore 5"] = Png(("IHDR", Ihdr(2, 1, 8, 5)), ("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
["interlacciamento 2"] = Png(("IHDR", Ihdr(2, 1, 8, 6, interlace: 2)), ("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
["tavolozza senza PLTE"] = Png(("IHDR", Ihdr(2, 1, 8, 3)), ("IDAT", Zlib([0, 0, 0])), end),
|
||||||
|
["PLTE in scala di grigi"] = Png(("IHDR", Ihdr(2, 1, 8, 0)), ("PLTE", [1, 2, 3]), ("IDAT", Zlib([0, 0, 0])), end),
|
||||||
|
["PLTE di 4 byte"] = Png(("IHDR", Ihdr(2, 1, 8, 3)), ("PLTE", [1, 2, 3, 4]), ("IDAT", Zlib([0, 0, 0])), end),
|
||||||
|
["IDAT separati"] = Png(header, ("IDAT", Zlib(TwoPixels)[..4]), ("tEXt", Join(Latin1("a"), [0])), ("IDAT", Zlib(TwoPixels)[4..]), end),
|
||||||
|
["zlib non valido"] = Png(header, ("IDAT", [0x78, 0x9C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]), end),
|
||||||
|
["dati corti"] = Png(header, ("IDAT", Zlib(TwoPixels[..5])), end),
|
||||||
|
["filtro 5"] = Png(header, ("IDAT", Zlib(Join([5], TwoPixels[1..]))), end),
|
||||||
|
["IHDR doppio"] = Png(header, header, ("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
["tipo di blocco con una cifra"] = Png(header, ("ab1d", []), ("IDAT", Zlib(TwoPixels)), end),
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var (name, bytes) in cases)
|
||||||
|
{
|
||||||
|
var error = Assert.Throws<ImageDecodeException>(() => PngDecoder.Decode(bytes), name);
|
||||||
|
Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AnUnknownCriticalChunkIsNotSupportedAndAnUnknownAncillaryOneIsSkipped()
|
||||||
|
{
|
||||||
|
var crushed = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("CgBI", [0, 0, 0, 0]), ("IDAT", Zlib(TwoPixels)), ("IEND", []));
|
||||||
|
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => PngDecoder.Decode(crushed));
|
||||||
|
|
||||||
|
var extra = Png(("IHDR", Ihdr(2, 1, 8, 6)), ("vpAg", [1, 2, 3]), ("IDAT", Zlib(TwoPixels)), ("prVt", []), ("IEND", []));
|
||||||
|
using var image = PngDecoder.Decode(Join(extra, Encoding.ASCII.GetBytes("dopo IEND")));
|
||||||
|
Assert.AreEqual((255, 0, 0, 255), image.GetPixel(0, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryTruncationEitherFailsOrGivesTheWholeImage()
|
||||||
|
{
|
||||||
|
var reference = ReferenceImages.Get("png-tav-4-adam7");
|
||||||
|
var full = reference.ReadInput();
|
||||||
|
using var expected = PngDecoder.Decode(full);
|
||||||
|
var whole = 0;
|
||||||
|
for (var length = 0; length < full.Length; length++)
|
||||||
|
{
|
||||||
|
var cut = full[..length];
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var image = PngDecoder.Decode(cut);
|
||||||
|
ImageAssert.AreEqual(expected, image, $"tagliato a {length}");
|
||||||
|
whole++;
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only cuts at a chunk boundary after the last IDAT keep everything (a missing IEND is accepted).
|
||||||
|
var lastIdatEnd = 8;
|
||||||
|
var boundaries = new List<int>();
|
||||||
|
for (var pos = 8; pos < full.Length;)
|
||||||
|
{
|
||||||
|
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(full.AsSpan(pos));
|
||||||
|
var type = Encoding.ASCII.GetString(full, pos + 4, 4);
|
||||||
|
pos += length + 12;
|
||||||
|
boundaries.Add(pos);
|
||||||
|
if (type == "IDAT")
|
||||||
|
{
|
||||||
|
lastIdatEnd = pos;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(boundaries.Count(b => b >= lastIdatEnd && b < full.Length), whole);
|
||||||
|
Assert.IsGreaterThanOrEqualTo(1, whole);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ImagesBeyondTheLimitsAreRefusedBeforeDecoding()
|
||||||
|
{
|
||||||
|
var huge = Png(("IHDR", Ihdr(70_000, 1, 8, 6)), ("IDAT", Zlib([0])), ("IEND", []));
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(huge));
|
||||||
|
Assert.AreEqual(70_000, PngDecoder.Identify(huge).Width, "la misura si legge anche oltre i limiti");
|
||||||
|
|
||||||
|
using var image = TestImages.Random(50, 50, 4);
|
||||||
|
var png = PngEncoder.Encode(image);
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(png, new ImageLimits { MaxPixels = 2499 }));
|
||||||
|
Assert.ThrowsExactly<ImageLimitException>(() => PngDecoder.Decode(png, new ImageLimits { MaxWidth = 49 }));
|
||||||
|
using var allowed = PngDecoder.Decode(png, new ImageLimits { MaxPixels = 2500 });
|
||||||
|
ImageAssert.AreEqual(image, allowed, "al limite");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void APooledDecodeGivesTheSamePixels()
|
||||||
|
{
|
||||||
|
var reference = ReferenceImages.Get("png-rgba-16");
|
||||||
|
using var plain = PngDecoder.Decode(reference.ReadInput());
|
||||||
|
var pooled = PngDecoder.Decode(reference.ReadInput(), pooled: true);
|
||||||
|
Assert.IsTrue(pooled.IsPooled);
|
||||||
|
ImageAssert.AreEqual(plain, pooled, reference.Name);
|
||||||
|
pooled.Dispose();
|
||||||
|
pooled.Dispose();
|
||||||
|
Assert.ThrowsExactly<ObjectDisposedException>(() => pooled.Pixels.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static uint BitwiseCrc(ReadOnlySpan<byte> data)
|
||||||
|
{
|
||||||
|
var crc = 0xFFFFFFFFu;
|
||||||
|
foreach (var b in data)
|
||||||
|
{
|
||||||
|
crc ^= b;
|
||||||
|
for (var k = 0; k < 8; k++)
|
||||||
|
{
|
||||||
|
crc = (crc & 1) != 0 ? 0xEDB88320u ^ (crc >> 1) : crc >> 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ~crc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Inflate(byte[] zlib)
|
||||||
|
{
|
||||||
|
using var input = new MemoryStream(zlib);
|
||||||
|
using var stream = new ZLibStream(input, CompressionMode.Decompress);
|
||||||
|
using var output = new MemoryStream();
|
||||||
|
stream.CopyTo(output);
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The in-house PNG, GIF and BMP decoders against the reference set (Imaging/Riferimenti/LEGGIMI.md): every pixel
|
||||||
|
/// must be the one SkiaSharp read, exactly. The expected images are read with our own PNG decoder, which is first
|
||||||
|
/// checked on them against a reader of a dozen lines that only knows their trivial layout.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ReferenceDecodeTests
|
||||||
|
{
|
||||||
|
public static IEnumerable<object[]> PngCases => ReferenceImages.NamesOf(ReferenceFormat.Png);
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> GifCases => ReferenceImages.NamesOf(ReferenceFormat.Gif);
|
||||||
|
|
||||||
|
public static IEnumerable<object[]> BmpCases => ReferenceImages.NamesOf(ReferenceFormat.Bmp);
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryExpectedImageReadsTheSameWithTheDecoderAndWithTheTrivialReader()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.All)
|
||||||
|
{
|
||||||
|
var png = reference.ReadExpectedPng();
|
||||||
|
using var image = PngDecoder.Decode(png);
|
||||||
|
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height), reference.Name);
|
||||||
|
ImageAssert.AreEqual(reference.Width, TrivialRead(png, reference.Width, reference.Height), image.Pixels, reference.Name + ".atteso.png");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(PngCases))]
|
||||||
|
public void ThePngDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => PngDecoder.Decode(data));
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(GifCases))]
|
||||||
|
public void TheGifDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => GifDecoder.Decode(data));
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[DynamicData(nameof(BmpCases))]
|
||||||
|
public void TheBmpDecoderReadsTheReferenceExactly(string name) => CheckExact(name, data => BmpDecoder.Decode(data));
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheFacadeChoosesTheDecoderFromTheFirstBytes()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.All)
|
||||||
|
{
|
||||||
|
var input = reference.ReadInput();
|
||||||
|
var format = ImageFormatSniffer.Detect(input);
|
||||||
|
var expected = reference.Format switch
|
||||||
|
{
|
||||||
|
ReferenceFormat.Png => ImageFormat.Png,
|
||||||
|
ReferenceFormat.Jpeg => ImageFormat.Jpeg,
|
||||||
|
ReferenceFormat.WebP => ImageFormat.WebP,
|
||||||
|
ReferenceFormat.Gif => ImageFormat.Gif,
|
||||||
|
_ => ImageFormat.Bmp,
|
||||||
|
};
|
||||||
|
Assert.AreEqual(expected, format, reference.Name);
|
||||||
|
if (!ImageDecoder.CanDecode(format))
|
||||||
|
{
|
||||||
|
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Decode(input), reference.Name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reference.Format == ReferenceFormat.Jpeg || (reference.Format == ReferenceFormat.WebP && !reference.Name.Contains("senza-perdita", StringComparison.Ordinal)))
|
||||||
|
{
|
||||||
|
// Lossy: JpegReferenceTests and WebPReferenceTests compare it with thresholds (JPEG with the EXIF
|
||||||
|
// orientation applied).
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var image = ImageDecoder.Decode(input);
|
||||||
|
using var expectedImage = PngDecoder.Decode(reference.ReadExpectedPng());
|
||||||
|
ImageAssert.AreEqual(expectedImage, image, reference.Name);
|
||||||
|
|
||||||
|
var info = ImageDecoder.Identify(input);
|
||||||
|
Assert.AreEqual((format, reference.Width, reference.Height), (info.Format, info.Width, info.Height), reference.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheAnimatedGifHasMoreThanOneFrameAndTheOthersOne()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Gif))
|
||||||
|
{
|
||||||
|
var info = GifDecoder.Identify(reference.ReadInput());
|
||||||
|
if (reference.Name == "gif-animata")
|
||||||
|
{
|
||||||
|
Assert.IsGreaterThan(1, info.FrameCount, reference.Name);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Assert.AreEqual(1, info.FrameCount, reference.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
using var image = GifDecoder.Decode(reference.ReadInput(), out var again);
|
||||||
|
Assert.AreEqual(info.FrameCount, again.FrameCount, reference.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void HandBuiltPngsCarryTheirTextChunk()
|
||||||
|
{
|
||||||
|
// LEGGIMI.md: every hand-built PNG has a tEXt to skip; the metadata reader finds it.
|
||||||
|
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Png).Where(c => !c.Name.StartsWith("png-skia", StringComparison.Ordinal)))
|
||||||
|
{
|
||||||
|
var info = PngDecoder.Identify(reference.ReadInput());
|
||||||
|
Assert.IsNotEmpty(info.Metadata.Texts, reference.Name);
|
||||||
|
Assert.AreEqual(1, info.FrameCount, reference.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckExact(string name, Func<byte[], RgbaImage> decode)
|
||||||
|
{
|
||||||
|
var reference = ReferenceImages.Get(name);
|
||||||
|
using var expected = PngDecoder.Decode(reference.ReadExpectedPng());
|
||||||
|
using var actual = decode(reference.ReadInput());
|
||||||
|
ImageAssert.AreEqual(expected, actual, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads an expected image knowing only how they were written: IHDR, IDAT chunks, one zlib stream of rows that
|
||||||
|
/// all use filter 0, RGBA8. Independent of <see cref="PngDecoder"/>.
|
||||||
|
/// </summary>
|
||||||
|
private static byte[] TrivialRead(byte[] png, int width, int height)
|
||||||
|
{
|
||||||
|
using var idat = new MemoryStream();
|
||||||
|
var pos = 8;
|
||||||
|
while (pos < png.Length)
|
||||||
|
{
|
||||||
|
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos));
|
||||||
|
if (png.AsSpan(pos + 4, 4).SequenceEqual("IDAT"u8))
|
||||||
|
{
|
||||||
|
idat.Write(png, pos + 8, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += length + 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
idat.Position = 0;
|
||||||
|
using var zlib = new ZLibStream(idat, CompressionMode.Decompress);
|
||||||
|
var pixels = new byte[width * height * 4];
|
||||||
|
var row = new byte[1 + (width * 4)];
|
||||||
|
for (var y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
zlib.ReadExactly(row);
|
||||||
|
Assert.AreEqual(0, row[0], "le immagini attese usano solo il filtro 0");
|
||||||
|
row.AsSpan(1).CopyTo(pixels.AsSpan(y * width * 4));
|
||||||
|
}
|
||||||
|
|
||||||
|
return pixels;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>The format of a reference case's input file, from its extension.</summary>
|
||||||
|
public enum ReferenceFormat
|
||||||
|
{
|
||||||
|
Png,
|
||||||
|
Jpeg,
|
||||||
|
WebP,
|
||||||
|
Gif,
|
||||||
|
Bmp,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One case of the reference set in Imaging/Riferimenti (see LEGGIMI.md there): an input file and, beside it,
|
||||||
|
/// «<see cref="Name"/>.atteso.png», SkiaSharp's straight (unpremultiplied) RGBA8 decode of it, upright.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Folder">The folder of the set.</param>
|
||||||
|
/// <param name="Name">The case name, as elenco.txt lists it.</param>
|
||||||
|
/// <param name="Format">The format of the input file.</param>
|
||||||
|
/// <param name="InputFileName">The input file name, inside <paramref name="Folder"/>.</param>
|
||||||
|
/// <param name="Width">Width of the expected image (after the EXIF orientation, for a JPEG that has one).</param>
|
||||||
|
/// <param name="Height">Height of the expected image (after the EXIF orientation, for a JPEG that has one).</param>
|
||||||
|
public sealed record ReferenceCase(string Folder, string Name, ReferenceFormat Format, string InputFileName, int Width, int Height)
|
||||||
|
{
|
||||||
|
/// <summary>Full path of the input file.</summary>
|
||||||
|
public string InputPath => Path.Combine(Folder, InputFileName);
|
||||||
|
|
||||||
|
/// <summary>Full path of the expected image («.atteso.png»).</summary>
|
||||||
|
public string ExpectedPath => Path.Combine(Folder, Name + ReferenceImages.ExpectedSuffix);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The EXIF orientation (1-8) the input carries by construction: only the «jpeg-orientamento-N» cases have one.
|
||||||
|
/// The integrity test checks it against the file.
|
||||||
|
/// </summary>
|
||||||
|
public int Orientation =>
|
||||||
|
Name.StartsWith(ReferenceImages.OrientationPrefix, StringComparison.Ordinal)
|
||||||
|
? int.Parse(Name.AsSpan(ReferenceImages.OrientationPrefix.Length), System.Globalization.CultureInfo.InvariantCulture)
|
||||||
|
: 1;
|
||||||
|
|
||||||
|
/// <summary>Width of the image as stored in the input file (orientations 5-8 swap the two sides).</summary>
|
||||||
|
public int StoredWidth => Orientation >= 5 ? Height : Width;
|
||||||
|
|
||||||
|
/// <summary>Height of the image as stored in the input file (orientations 5-8 swap the two sides).</summary>
|
||||||
|
public int StoredHeight => Orientation >= 5 ? Width : Height;
|
||||||
|
|
||||||
|
/// <summary>The bytes of the input file.</summary>
|
||||||
|
public byte[] ReadInput() => File.ReadAllBytes(InputPath);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The bytes of the expected image: an 8-bit RGBA PNG (colour type 6), one filter-0 row after the other in a single
|
||||||
|
/// zlib stream. From step 2 of track C1 Febe's own PNG decoder reads it; SkiaSharp is no longer needed for that.
|
||||||
|
/// </summary>
|
||||||
|
public byte[] ReadExpectedPng() => File.ReadAllBytes(ExpectedPath);
|
||||||
|
|
||||||
|
/// <inheritdoc/>
|
||||||
|
public override string ToString() => Name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Loads the reference set of the in-house image codecs from the test output folder.</summary>
|
||||||
|
public static class ReferenceImages
|
||||||
|
{
|
||||||
|
/// <summary>Suffix of the expected images.</summary>
|
||||||
|
public const string ExpectedSuffix = ".atteso.png";
|
||||||
|
|
||||||
|
/// <summary>The list of the cases, one «name WxH» per line.</summary>
|
||||||
|
public const string ListFileName = "elenco.txt";
|
||||||
|
|
||||||
|
/// <summary>The description of the set.</summary>
|
||||||
|
public const string ReadmeFileName = "LEGGIMI.md";
|
||||||
|
|
||||||
|
/// <summary>Name prefix of the JPEG cases with an EXIF orientation.</summary>
|
||||||
|
public const string OrientationPrefix = "jpeg-orientamento-";
|
||||||
|
|
||||||
|
private static readonly (string Extension, ReferenceFormat Format)[] InputExtensions =
|
||||||
|
[
|
||||||
|
(".png", ReferenceFormat.Png),
|
||||||
|
(".jpg", ReferenceFormat.Jpeg),
|
||||||
|
(".webp", ReferenceFormat.WebP),
|
||||||
|
(".gif", ReferenceFormat.Gif),
|
||||||
|
(".bmp", ReferenceFormat.Bmp),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>The folder of the set in the test output (copied there by Febe.Tests.csproj).</summary>
|
||||||
|
public static string Folder { get; } = Path.Combine(AppContext.BaseDirectory, "Imaging", "Riferimenti");
|
||||||
|
|
||||||
|
private static readonly Lazy<IReadOnlyList<ReferenceCase>> Cases = new(() => Load(Folder));
|
||||||
|
|
||||||
|
/// <summary>Every case, in the order of elenco.txt.</summary>
|
||||||
|
public static IReadOnlyList<ReferenceCase> All => Cases.Value;
|
||||||
|
|
||||||
|
/// <summary>The case with that name.</summary>
|
||||||
|
public static ReferenceCase Get(string name)
|
||||||
|
{
|
||||||
|
foreach (var reference in All)
|
||||||
|
{
|
||||||
|
if (reference.Name == name)
|
||||||
|
{
|
||||||
|
return reference;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new KeyNotFoundException($"No reference case named '{name}' in {ListFileName}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The cases whose input has that format.</summary>
|
||||||
|
public static IEnumerable<ReferenceCase> Of(ReferenceFormat format) => All.Where(c => c.Format == format);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The case names of a format, for <c>[DynamicData]</c>: the test receives the name and calls <see cref="Get"/>,
|
||||||
|
/// so each case shows up as its own row in the results.
|
||||||
|
/// </summary>
|
||||||
|
public static IEnumerable<object[]> NamesOf(ReferenceFormat format) => Of(format).Select(c => new object[] { c.Name });
|
||||||
|
|
||||||
|
/// <summary>The input formats, with their extensions.</summary>
|
||||||
|
public static IReadOnlyList<(string Extension, ReferenceFormat Format)> Extensions => InputExtensions;
|
||||||
|
|
||||||
|
/// <summary>Reads elenco.txt in <paramref name="folder"/> and finds the input file of every case.</summary>
|
||||||
|
public static IReadOnlyList<ReferenceCase> Load(string folder)
|
||||||
|
{
|
||||||
|
var list = new List<ReferenceCase>();
|
||||||
|
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
var lineNumber = 0;
|
||||||
|
foreach (var rawLine in File.ReadLines(Path.Combine(folder, ListFileName)))
|
||||||
|
{
|
||||||
|
lineNumber++;
|
||||||
|
var line = rawLine.Trim();
|
||||||
|
if (line.Length == 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var parts = line.Split(' ');
|
||||||
|
var size = parts.Length == 2 ? parts[1].Split('x') : [];
|
||||||
|
if (size.Length != 2
|
||||||
|
|| !int.TryParse(size[0], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var width)
|
||||||
|
|| !int.TryParse(size[1], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var height)
|
||||||
|
|| width <= 0
|
||||||
|
|| height <= 0)
|
||||||
|
{
|
||||||
|
throw new InvalidDataException($"{ListFileName}, line {lineNumber}: expected 'name WxH', found '{line}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = parts[0];
|
||||||
|
if (!seen.Add(name))
|
||||||
|
{
|
||||||
|
throw new InvalidDataException($"{ListFileName}, line {lineNumber}: '{name}' is listed twice.");
|
||||||
|
}
|
||||||
|
|
||||||
|
ReferenceCase? found = null;
|
||||||
|
foreach (var (extension, format) in InputExtensions)
|
||||||
|
{
|
||||||
|
if (!File.Exists(Path.Combine(folder, name + extension)))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (found is not null)
|
||||||
|
{
|
||||||
|
throw new InvalidDataException($"'{name}' has more than one input file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
found = new ReferenceCase(folder, name, format, name + extension, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
list.Add(found ?? throw new FileNotFoundException($"'{name}' has no input file in {folder}."));
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Febe.Tests.Imaging;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Integrity of the reference set in Imaging/Riferimenti: every listed file is there and nothing else, each input starts
|
||||||
|
/// with the magic of its format and has the listed size, each expected image is a well-formed straight RGBA8 PNG of the
|
||||||
|
/// listed size. The pixels are not read here: <see cref="ReferenceDecodeTests"/> reads them with Febe's own PNG decoder
|
||||||
|
/// (step 2 of track C1), without SkiaSharp.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ReferenceSetTests
|
||||||
|
{
|
||||||
|
/// <summary>The number of cases SkiaSharp's references were made for (LEGGIMI.md lists them).</summary>
|
||||||
|
private const int CaseCount = 57;
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheListNamesEveryFileOfTheFolderAndNothingElse()
|
||||||
|
{
|
||||||
|
var cases = ReferenceImages.All;
|
||||||
|
Assert.HasCount(CaseCount, cases);
|
||||||
|
|
||||||
|
var expectedFiles = new HashSet<string>(StringComparer.Ordinal) { ReferenceImages.ListFileName, ReferenceImages.ReadmeFileName };
|
||||||
|
foreach (var reference in cases)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(expectedFiles.Add(reference.InputFileName), $"{reference.Name}: input listed twice.");
|
||||||
|
Assert.IsTrue(expectedFiles.Add(reference.Name + ReferenceImages.ExpectedSuffix), $"{reference.Name}: expected image listed twice.");
|
||||||
|
Assert.IsTrue(File.Exists(reference.ExpectedPath), $"{reference.Name}: the expected image is missing.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var actualFiles = Directory.EnumerateFiles(ReferenceImages.Folder, "*", SearchOption.AllDirectories)
|
||||||
|
.Select(path => Path.GetRelativePath(ReferenceImages.Folder, path))
|
||||||
|
.ToHashSet(StringComparer.Ordinal);
|
||||||
|
CollectionAssert.AreEquivalent(expectedFiles.Order(StringComparer.Ordinal).ToList(), actualFiles.Order(StringComparer.Ordinal).ToList());
|
||||||
|
|
||||||
|
foreach (var (_, format) in ReferenceImages.Extensions)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(ReferenceImages.Of(format).Any(), $"No case for {format}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheListIsReadTheSameWithWindowsLineEnds()
|
||||||
|
{
|
||||||
|
// A checkout with core.autocrlf must not change what the list says (.gitattributes also keeps it LF).
|
||||||
|
var folder = Path.Combine(Path.GetTempPath(), "febe-riferimenti-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(folder);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var listed = File.ReadAllText(Path.Combine(ReferenceImages.Folder, ReferenceImages.ListFileName));
|
||||||
|
File.WriteAllText(Path.Combine(folder, ReferenceImages.ListFileName), listed.ReplaceLineEndings("\r\n"));
|
||||||
|
foreach (var reference in ReferenceImages.All)
|
||||||
|
{
|
||||||
|
File.WriteAllBytes(Path.Combine(folder, reference.InputFileName), []);
|
||||||
|
}
|
||||||
|
|
||||||
|
var again = ReferenceImages.Load(folder);
|
||||||
|
CollectionAssert.AreEqual(
|
||||||
|
ReferenceImages.All.Select(c => (c.Name, c.Format, c.Width, c.Height)).ToList(),
|
||||||
|
again.Select(c => (c.Name, c.Format, c.Width, c.Height)).ToList());
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Directory.Delete(folder, recursive: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryInputStartsWithTheMagicOfItsFormatAndHasTheListedSize()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.All)
|
||||||
|
{
|
||||||
|
var bytes = reference.ReadInput();
|
||||||
|
var (width, height) = reference.Format switch
|
||||||
|
{
|
||||||
|
ReferenceFormat.Png => PngSize(reference.Name, bytes),
|
||||||
|
ReferenceFormat.Jpeg => JpegSize(reference, bytes),
|
||||||
|
ReferenceFormat.WebP => WebPSize(reference.Name, bytes),
|
||||||
|
ReferenceFormat.Gif => GifSize(reference.Name, bytes),
|
||||||
|
ReferenceFormat.Bmp => BmpSize(reference.Name, bytes),
|
||||||
|
_ => throw new AssertFailedException($"{reference.Name}: unknown format."),
|
||||||
|
};
|
||||||
|
Assert.AreEqual((reference.StoredWidth, reference.StoredHeight), (width, height), $"{reference.Name}: size of the input.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryExpectedImageIsAStraightRgba8PngWithTheListedSize()
|
||||||
|
{
|
||||||
|
foreach (var reference in ReferenceImages.All)
|
||||||
|
{
|
||||||
|
var bytes = reference.ReadExpectedPng();
|
||||||
|
var chunks = PngChunks(reference.Name + ReferenceImages.ExpectedSuffix, bytes);
|
||||||
|
var types = chunks.Select(c => c.Type).Distinct().ToList();
|
||||||
|
CollectionAssert.AreEqual(new[] { "IHDR", "IDAT", "IEND" }, types, $"{reference.Name}: only IHDR, IDAT and IEND, in this order.");
|
||||||
|
|
||||||
|
var ihdr = bytes.AsSpan(chunks[0].Offset, chunks[0].Length);
|
||||||
|
Assert.AreEqual(13, ihdr.Length, $"{reference.Name}: IHDR length.");
|
||||||
|
Assert.AreEqual(reference.Width, BinaryPrimitives.ReadInt32BigEndian(ihdr), $"{reference.Name}: width.");
|
||||||
|
Assert.AreEqual(reference.Height, BinaryPrimitives.ReadInt32BigEndian(ihdr[4..]), $"{reference.Name}: height.");
|
||||||
|
Assert.AreEqual(8, ihdr[8], $"{reference.Name}: bit depth.");
|
||||||
|
Assert.AreEqual(6, ihdr[9], $"{reference.Name}: colour type (RGBA).");
|
||||||
|
Assert.AreEqual(0, ihdr[10] | ihdr[11] | ihdr[12], $"{reference.Name}: compression, filter method and interlace.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheJpegInputsAreBaselineWithoutRestartIntervalsOrAdobeColour()
|
||||||
|
{
|
||||||
|
// LEGGIMI.md says progressive JPEG, restart intervals and CMYK/Adobe have no SkiaSharp reference: they are covered
|
||||||
|
// by our own encoders in the JPEG tests. This keeps that sentence true if the set is ever regenerated.
|
||||||
|
foreach (var reference in ReferenceImages.Of(ReferenceFormat.Jpeg))
|
||||||
|
{
|
||||||
|
foreach (var (marker, _, _) in JpegSegments(reference.Name, reference.ReadInput()))
|
||||||
|
{
|
||||||
|
Assert.IsFalse(marker is >= 0xC1 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC, $"{reference.Name}: SOF marker FF{marker:X2}, not baseline.");
|
||||||
|
Assert.AreNotEqual(0xDD, marker, $"{reference.Name}: restart interval (DRI).");
|
||||||
|
Assert.AreNotEqual(0xEE, marker, $"{reference.Name}: Adobe segment (APP14).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheSetStaysSmall()
|
||||||
|
{
|
||||||
|
long total = 0;
|
||||||
|
foreach (var path in Directory.EnumerateFiles(ReferenceImages.Folder))
|
||||||
|
{
|
||||||
|
var length = new FileInfo(path).Length;
|
||||||
|
Assert.IsGreaterThan(0L, length, $"{Path.GetFileName(path)} is empty.");
|
||||||
|
Assert.IsLessThan(512L * 1024, length, $"{Path.GetFileName(path)} is larger than 512 KiB.");
|
||||||
|
total += length;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsLessThan(4L * 1024 * 1024, total, "The whole set should stay under 4 MiB.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheCrcOfTheChecksIsTheOneOfThePngSpecification()
|
||||||
|
{
|
||||||
|
// PNG specification, annex D: the CRC of "IEND" with no data.
|
||||||
|
Assert.AreEqual(0xAE426082u, Crc32("IEND"u8, []));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int Width, int Height) PngSize(string name, byte[] bytes)
|
||||||
|
{
|
||||||
|
var chunks = PngChunks(name, bytes);
|
||||||
|
Assert.AreEqual("IHDR", chunks[0].Type, $"{name}: the first chunk.");
|
||||||
|
var ihdr = bytes.AsSpan(chunks[0].Offset, chunks[0].Length);
|
||||||
|
return (BinaryPrimitives.ReadInt32BigEndian(ihdr), BinaryPrimitives.ReadInt32BigEndian(ihdr[4..]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Walks the chunks of a PNG, checking signature, lengths, CRCs and that IEND ends the file.</summary>
|
||||||
|
private static List<(string Type, int Offset, int Length)> PngChunks(string name, byte[] bytes)
|
||||||
|
{
|
||||||
|
ReadOnlySpan<byte> signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||||
|
Assert.IsTrue(bytes.AsSpan().StartsWith(signature), $"{name}: PNG signature.");
|
||||||
|
var chunks = new List<(string, int, int)>();
|
||||||
|
var position = signature.Length;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
Assert.IsLessThanOrEqualTo(bytes.Length, position + 12, $"{name}: truncated chunk at {position}.");
|
||||||
|
var length = BinaryPrimitives.ReadInt32BigEndian(bytes.AsSpan(position));
|
||||||
|
Assert.IsTrue(length >= 0 && position + 12 + (long)length <= bytes.Length, $"{name}: chunk length at {position}.");
|
||||||
|
var type = bytes.AsSpan(position + 4, 4);
|
||||||
|
var data = bytes.AsSpan(position + 8, length);
|
||||||
|
var crc = BinaryPrimitives.ReadUInt32BigEndian(bytes.AsSpan(position + 8 + length));
|
||||||
|
var typeName = Encoding.ASCII.GetString(type);
|
||||||
|
Assert.AreEqual(Crc32(type, data), crc, $"{name}: CRC of {typeName} at {position}.");
|
||||||
|
chunks.Add((typeName, position + 8, length));
|
||||||
|
position += 12 + length;
|
||||||
|
if (typeName == "IEND")
|
||||||
|
{
|
||||||
|
Assert.AreEqual(0, length, $"{name}: IEND has no data.");
|
||||||
|
Assert.AreEqual(bytes.Length, position, $"{name}: bytes after IEND.");
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int Width, int Height) JpegSize(ReferenceCase reference, byte[] bytes)
|
||||||
|
{
|
||||||
|
var name = reference.Name;
|
||||||
|
Assert.IsTrue(bytes is [0xFF, 0xD8, ..] && bytes[^2] == 0xFF && bytes[^1] == 0xD9, $"{name}: SOI at the start and EOI at the end.");
|
||||||
|
(int, int)? size = null;
|
||||||
|
var orientation = 1;
|
||||||
|
foreach (var (marker, offset, length) in JpegSegments(name, bytes))
|
||||||
|
{
|
||||||
|
var segment = bytes.AsSpan(offset, length);
|
||||||
|
if (marker == 0xC0)
|
||||||
|
{
|
||||||
|
Assert.IsNull(size, $"{name}: more than one SOF.");
|
||||||
|
size = (BinaryPrimitives.ReadUInt16BigEndian(segment[3..]), BinaryPrimitives.ReadUInt16BigEndian(segment[1..]));
|
||||||
|
}
|
||||||
|
else if (marker == 0xE1 && segment.StartsWith("Exif\0\0"u8))
|
||||||
|
{
|
||||||
|
orientation = ExifOrientation(name, segment[6..]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(reference.Orientation, orientation, $"{name}: EXIF orientation.");
|
||||||
|
return size ?? throw new AssertFailedException($"{name}: no baseline SOF.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The marker segments of a JPEG up to the start of scan: marker, offset and length of the payload.</summary>
|
||||||
|
private static List<(byte Marker, int Offset, int Length)> JpegSegments(string name, byte[] bytes)
|
||||||
|
{
|
||||||
|
var segments = new List<(byte, int, int)>();
|
||||||
|
var position = 2;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
Assert.IsLessThanOrEqualTo(bytes.Length, position + 4, $"{name}: truncated before the start of scan.");
|
||||||
|
Assert.AreEqual(0xFF, bytes[position], $"{name}: marker expected at {position}.");
|
||||||
|
var marker = bytes[position + 1];
|
||||||
|
var length = BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(position + 2));
|
||||||
|
Assert.IsTrue(length >= 2 && position + 2 + length <= bytes.Length, $"{name}: segment length at {position}.");
|
||||||
|
segments.Add((marker, position + 4, length - 2));
|
||||||
|
if (marker == 0xDA)
|
||||||
|
{
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
|
position += 2 + length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The Orientation tag (0x0112) of IFD0 of an EXIF TIFF block, 1 when absent.</summary>
|
||||||
|
private static int ExifOrientation(string name, ReadOnlySpan<byte> tiff)
|
||||||
|
{
|
||||||
|
var bigEndian = tiff.StartsWith("MM"u8);
|
||||||
|
Assert.IsTrue(bigEndian || tiff.StartsWith("II"u8), $"{name}: TIFF byte order.");
|
||||||
|
int U16(ReadOnlySpan<byte> s) => bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(s) : BinaryPrimitives.ReadUInt16LittleEndian(s);
|
||||||
|
var ifd = (int)(bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(tiff[4..]) : BinaryPrimitives.ReadUInt32LittleEndian(tiff[4..]));
|
||||||
|
Assert.AreEqual(42, U16(tiff[2..]), $"{name}: TIFF magic.");
|
||||||
|
var count = U16(tiff[ifd..]);
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var entry = tiff.Slice(ifd + 2 + (i * 12), 12);
|
||||||
|
if (U16(entry) == 0x0112)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(3, U16(entry[2..]), $"{name}: Orientation is a SHORT.");
|
||||||
|
return U16(entry[8..]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int Width, int Height) WebPSize(string name, byte[] bytes)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(bytes.AsSpan().StartsWith("RIFF"u8) && bytes.AsSpan(8).StartsWith("WEBP"u8), $"{name}: RIFF/WEBP header.");
|
||||||
|
Assert.AreEqual(bytes.Length - 8, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(4)), $"{name}: RIFF size.");
|
||||||
|
var chunk = Encoding.ASCII.GetString(bytes, 12, 4);
|
||||||
|
var data = bytes.AsSpan(20);
|
||||||
|
switch (chunk)
|
||||||
|
{
|
||||||
|
case "VP8 ":
|
||||||
|
// RFC 9649 §2.5 and RFC 6386 §9.1: 3-byte frame tag, start code, then 14-bit width and height.
|
||||||
|
Assert.IsTrue(data[3..].StartsWith((ReadOnlySpan<byte>)[0x9D, 0x01, 0x2A]), $"{name}: VP8 start code.");
|
||||||
|
return (BinaryPrimitives.ReadUInt16LittleEndian(data[6..]) & 0x3FFF, BinaryPrimitives.ReadUInt16LittleEndian(data[8..]) & 0x3FFF);
|
||||||
|
case "VP8L":
|
||||||
|
// RFC 9649 §3.2: signature 0x2F, then 14 bits of width - 1 and 14 bits of height - 1.
|
||||||
|
Assert.AreEqual(0x2F, data[0], $"{name}: VP8L signature.");
|
||||||
|
var bits = BinaryPrimitives.ReadUInt32LittleEndian(data[1..]);
|
||||||
|
return ((int)(bits & 0x3FFF) + 1, (int)((bits >> 14) & 0x3FFF) + 1);
|
||||||
|
case "VP8X":
|
||||||
|
// RFC 9649 §2.7: flags, 3 reserved bytes, 24-bit canvas width - 1 and height - 1.
|
||||||
|
return (U24(data[4..]) + 1, U24(data[7..]) + 1);
|
||||||
|
default:
|
||||||
|
throw new AssertFailedException($"{name}: unknown first chunk '{chunk}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
static int U24(ReadOnlySpan<byte> s) => s[0] | (s[1] << 8) | (s[2] << 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int Width, int Height) GifSize(string name, byte[] bytes)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(bytes.AsSpan().StartsWith("GIF89a"u8), $"{name}: GIF89a signature.");
|
||||||
|
Assert.AreEqual(0x3B, bytes[^1], $"{name}: trailer.");
|
||||||
|
return (BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(6)), BinaryPrimitives.ReadUInt16LittleEndian(bytes.AsSpan(8)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int Width, int Height) BmpSize(string name, byte[] bytes)
|
||||||
|
{
|
||||||
|
Assert.IsTrue(bytes is [(byte)'B', (byte)'M', ..], $"{name}: BM signature.");
|
||||||
|
Assert.AreEqual(bytes.Length, BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(2)), $"{name}: file size in the header.");
|
||||||
|
var offset = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(10));
|
||||||
|
Assert.IsTrue(offset > 14 && offset < bytes.Length, $"{name}: offset of the pixels.");
|
||||||
|
var height = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(22));
|
||||||
|
return (BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(18)), Math.Abs(height));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly uint[] CrcTable = BuildCrcTable();
|
||||||
|
|
||||||
|
private static uint[] BuildCrcTable()
|
||||||
|
{
|
||||||
|
// PNG specification, annex D (ISO 3309 polynomial, reflected).
|
||||||
|
var table = new uint[256];
|
||||||
|
for (uint n = 0; n < 256; n++)
|
||||||
|
{
|
||||||
|
var c = n;
|
||||||
|
for (var k = 0; k < 8; k++)
|
||||||
|
{
|
||||||
|
c = (c & 1) != 0 ? 0xEDB88320u ^ (c >> 1) : c >> 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
table[n] = c;
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static uint Crc32(ReadOnlySpan<byte> type, ReadOnlySpan<byte> data)
|
||||||
|
{
|
||||||
|
var crc = 0xFFFFFFFFu;
|
||||||
|
foreach (var b in type)
|
||||||
|
{
|
||||||
|
crc = CrcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var b in data)
|
||||||
|
{
|
||||||
|
crc = CrcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
return crc ^ 0xFFFFFFFFu;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
# Immagini di riferimento dei codec di casa
|
||||||
|
|
||||||
|
Insieme fisso di immagini con cui si provano i lettori di immagini scritti in casa (tappa C1: SkiaSharp esce da
|
||||||
|
Febe). Ogni caso è una coppia:
|
||||||
|
|
||||||
|
- il **file d'ingresso** (`nome.png`, `.jpg`, `.webp`, `.gif`, `.bmp`);
|
||||||
|
- `nome.atteso.png`, **l'immagine attesa**: ciò che SkiaSharp ha letto da quel file, in RGBA a 8 bit per canale con
|
||||||
|
l'alfa non premoltiplicata, già raddrizzata secondo l'orientamento EXIF quando c'è.
|
||||||
|
|
||||||
|
`elenco.txt` nomina ogni caso con la misura dell'immagine attesa (`nome LxA`, una riga per caso, righe Unix).
|
||||||
|
|
||||||
|
## Come sono state fatte
|
||||||
|
|
||||||
|
Una volta sola, il 18 novembre 2026, con il permesso di Alberto, da un programma usa e getta con SkiaSharp 4.153.1
|
||||||
|
(lo stesso di `Directory.Packages.props` in quel momento) che **non è nel repository**: nel repository c'è solo ciò che
|
||||||
|
ha prodotto. Non si rigenerano: quando SkiaSharp sarà tolto non si potrà, ed è voluto. Un caso nuovo si costruisce con
|
||||||
|
il nostro codice, non si aggiunge qui.
|
||||||
|
|
||||||
|
- **Contenuto solo sintetico.** Le scene sono calcolate: sfumature, un disco, righe a colori invertiti, una zona di
|
||||||
|
rumore da un generatore congruenziale con seme fisso, alfa a rampa con una banda trasparente e una opaca. Nessuna
|
||||||
|
fotografia, nessun dato di terzi, nessun campione della sonda.
|
||||||
|
- **Lettura di riferimento.** `SKCodec.GetPixels` in `Rgba8888` con alfa `Unpremul`, prima immagine soltanto.
|
||||||
|
- **Orientamento.** Per i casi `jpeg-orientamento-N` il programma ha raddrizzato a mano i pixel letti e li ha
|
||||||
|
confrontati, uguali, con il disegno con matrice di SkiaSharp (quello che faceva `ImageDecoding`).
|
||||||
|
- **L'immagine attesa** non è scritta dal codificatore di SkiaSharp ma da uno scritto a mano nel programma: PNG RGBA a
|
||||||
|
8 bit (tipo di colore 6), senza interlacciamento, ogni riga con il filtro 0, un solo `IDAT` (zlib della BCL), nessun
|
||||||
|
altro blocco oltre a `IHDR`, `IDAT`, `IEND`. Così il lettore PNG di casa (tappa C1, passo 2) la legge senza SkiaSharp,
|
||||||
|
e un lettore minimo nelle prove, che conosce solo questa forma, controlla che legga giusto.
|
||||||
|
|
||||||
|
## I casi
|
||||||
|
|
||||||
|
Misura 101×67 se non detto altrimenti (dispari, per provare i bordi dei blocchi e il sottocampionamento).
|
||||||
|
|
||||||
|
### Costruiti a mano dalle specifiche
|
||||||
|
|
||||||
|
Byte scritti dal programma seguendo la specifica del formato; SkiaSharp li ha solo letti.
|
||||||
|
|
||||||
|
| Gruppo | Casi | Che cosa provano |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| PNG a tavolozza | `png-tav-1`, `png-tav-2`, `png-tav-4-trns`, `png-tav-8-trns`, `png-tav-4-adam7` | profondità 1–8, `tRNS` più corto della tavolozza, Adam7 |
|
||||||
|
| PNG grigio | `png-grigio-1`, `-2`, `-4`, `-8`, `-16`, `png-grigio-16-adam7`, `png-grigio-8-trns` | tutte le profondità, 16 bit, Adam7, colore trasparente |
|
||||||
|
| PNG grigio con alfa | `png-grigioalfa-8`, `png-grigioalfa-16` | 8 e 16 bit |
|
||||||
|
| PNG RGB / RGBA | `png-rgb-8`, `png-rgb-8-trns`, `png-rgb-16`, `png-rgba-8`, `png-rgba-16`, `png-rgba-8-adam7` | 16 bit (l'atteso è a 8), colore trasparente, Adam7 |
|
||||||
|
| GIF | `gif-globale`, `gif-locale-interlacciata`, `gif-animata`, `gif-2-colori` | tavolozza globale e locale, indice trasparente, interlacciamento, riquadro più piccolo della tela, LZW con codici fino a 12 bit e, in `gif-animata`, il dizionario pieno e azzerato; blocchi di commento e NETSCAPE2.0 da saltare |
|
||||||
|
| BMP | `bmp-24`, `bmp-24-dall-alto`, `bmp-32-campi-v5`, `bmp-32-senza-alfa`, `bmp-16-565` (`BI_BITFIELDS`), `bmp-16-555`, `bmp-8`, `bmp-4`, `bmp-1`, `bmp-rle8`, `bmp-rle4` | dal basso e dall'alto, intestazione V5 con maschere e alfa, 32 bit con il quarto byte a zero, 16 bit 565 e 555, tavolozze, RLE8 e RLE4 con tratti assoluti |
|
||||||
|
|
||||||
|
Ogni PNG costruito a mano usa a turno i cinque filtri di riga (nessuno, Sub, Up, Average, Paeth), divide i dati in due
|
||||||
|
`IDAT` e ha un `tEXt` da saltare.
|
||||||
|
|
||||||
|
### Codificati da SkiaSharp
|
||||||
|
|
||||||
|
| Gruppo | Casi | Che cosa provano |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| PNG | `png-skia-rgba`, `png-skia-rgb` | il codificatore di SkiaSharp, con tutti i filtri |
|
||||||
|
| JPEG | `jpeg-420-q90`, `jpeg-422-q75`, `jpeg-444-q95`, `jpeg-420-q40`, `jpeg-grigio-q85` | base (SOF0, Huffman), 4:2:0, 4:2:2, 4:4:4, una sola componente |
|
||||||
|
| JPEG grande | `jpeg-grande-420-q85` (333×250) | più blocchi, bordi non multipli di 16 |
|
||||||
|
| JPEG con orientamento | `jpeg-orientamento-2`, `-3`, `-5`, `-6`, `-7`, `-8` | un `APP1` EXIF con il solo tag Orientation, inserito a mano dopo `SOI` in un JPEG di SkiaSharp; da 5 a 8 l'immagine attesa è 67×101 |
|
||||||
|
| WebP con perdita | `webp-perdita-q80`, `webp-perdita-q30`, `webp-perdita-alfa-q80` | VP8, e VP8X con `ALPH` |
|
||||||
|
| WebP senza perdita | `webp-senza-perdita`, `webp-senza-perdita-opaco`, `webp-senza-perdita-rapido` | VP8L con alfa, opaco, con lo sforzo minimo |
|
||||||
|
| WebP grandi | `webp-grande-perdita-q75`, `webp-grande-senza-perdita` (333×250) | più macroblocchi; nel senza perdita, più spazio per trasformate e gruppi di Huffman |
|
||||||
|
|
||||||
|
### Che cosa dice l'immagine attesa, dove serve saperlo
|
||||||
|
|
||||||
|
- `gif-animata`: solo il primo fotogramma.
|
||||||
|
- `gif-locale-interlacciata`: il fotogramma è 80×50 in (7, 9) su una tela 101×67 senza tavolozza globale; fuori dal
|
||||||
|
fotogramma l'immagine attesa è trasparente (0, 0, 0, 0).
|
||||||
|
- Alfa non premoltiplicata: per i PNG il colore sotto un'alfa 0 resta quello del file.
|
||||||
|
- JPEG e WebP con perdita: l'immagine attesa è la lettura di libjpeg-turbo e libwebp dentro SkiaSharp (IDCT,
|
||||||
|
ricampionamento della crominanza, conversione dei colori). Il nostro lettore può differire di poco: per JPEG la
|
||||||
|
tolleranza è almeno 40 dB di PSNR per canale e al più lo 0,1% dei pixel con uno scarto oltre 16 (il lettore di casa
|
||||||
|
sta fra 59 e 67 dB, scarto massimo 3, nessun pixel oltre 16). Per WebP con perdita la tolleranza è la stessa e l'alfa
|
||||||
|
deve coincidere: il lettore di casa (passo 4) sta fra 68,7 e 74,4 dB, scarto massimo 1, nessun pixel oltre 16, alfa
|
||||||
|
esatta. PNG, GIF, BMP e WebP senza perdita devono coincidere byte per byte.
|
||||||
|
|
||||||
|
## Che cosa qui non c'è
|
||||||
|
|
||||||
|
Nessuno di questi casi ha un riferimento di SkiaSharp, e la prova d'integrità controlla che i JPEG dell'insieme restino
|
||||||
|
così (SOF0, nessun `DRI`, nessun `APP14`):
|
||||||
|
|
||||||
|
- **JPEG progressivo** (T.81, allegato G);
|
||||||
|
- **intervalli di ripristino** (`DRI`, marcatori `RSTn`);
|
||||||
|
- **CMYK e YCCK con il segmento Adobe** (`APP14`).
|
||||||
|
|
||||||
|
Si provano con codificatori di prova nostri, scritti dalla specifica T.81 (allegato F per il sequenziale, allegato G
|
||||||
|
per il progressivo): il codificatore scrive coefficienti noti e la prova confronta, esatti, i coefficienti che il
|
||||||
|
lettore ricava prima della trasformata inversa, poi i pixel di un'immagine semplice.
|
||||||
|
|
||||||
|
## Le prove
|
||||||
|
|
||||||
|
- `Imaging/ReferenceImages.cs`: carica `elenco.txt` e dà i casi (`ReferenceImages.All`, `Get`, `Of`, `NamesOf` per
|
||||||
|
`[DynamicData]`).
|
||||||
|
- `Imaging/ReferenceSetTests.cs`: integrità dell'insieme. Ogni file elencato c'è e non c'è altro; ogni ingresso
|
||||||
|
comincia con la firma del suo formato e ha la misura elencata (ruotata per l'orientamento EXIF 5–8); ogni immagine
|
||||||
|
attesa è un PNG RGBA a 8 bit ben formato (CRC di ogni blocco) della misura elencata; l'insieme resta piccolo.
|
||||||
|
- `Imaging/ReferenceDecodeTests.cs` (dalla tappa C1, passo 2): ogni immagine attesa si legge uguale con il lettore PNG
|
||||||
|
di casa e con un lettore minimo indipendente; i lettori PNG, GIF e BMP di casa danno, per ogni caso del loro formato,
|
||||||
|
esattamente i pixel dell'immagine attesa; la facciata `ImageDecoder` sceglie il lettore dai primi byte e i WebP
|
||||||
|
senza perdita devono coincidere; i JPEG li confronta con la tolleranza sopra `Imaging/JpegReferenceTests.cs` (dal
|
||||||
|
passo 3), che applica anche l'orientamento EXIF riportato dal lettore, e i WebP con perdita
|
||||||
|
`Imaging/WebPReferenceTests.cs` (dal passo 4).
|
||||||
|
- `Imaging/JpegCodingTests.cs`, `JpegEncoderTests.cs`, `JpegMalformedTests.cs` (dal passo 3): i casi qui assenti
|
||||||
|
(progressivo, ripristino, codifica aritmetica, 12 bit, senza perdita, CMYK e YCCK, campionamenti insoliti) scritti
|
||||||
|
dal codificatore di prova `JpegTestEncoder.cs` e confrontati coefficiente per coefficiente con la codifica di base
|
||||||
|
delle stesse immagini; il codificatore di casa; i file danneggiati.
|
||||||
|
- `Imaging/WebPReferenceTests.cs`, `WebPEncoderTests.cs`, `WebPContainerTests.cs`, `Vp8BitstreamTests.cs` (dal passo
|
||||||
|
4): i WebP dell'insieme contro l'immagine attesa (senza perdita esatti, con perdita con la tolleranza sopra); lo
|
||||||
|
scrittore senza perdita di casa, che rilegge esatti tutti i 57 riferimenti; le varianti che qui mancano, costruite
|
||||||
|
dalle prove a partire dai file dell'insieme (`ALPH` grezzo e compresso con ogni filtro, VP8X con ICCP, EXIF e XMP,
|
||||||
|
animazioni con scostamento e fusione) o scritte bit per bit (`Vp8TestWriter.cs`: segmenti, delta del filtro, più
|
||||||
|
partizioni, filtro semplice); i file danneggiati o tagliati.
|
||||||
|
- `Febe.Tests.csproj` copia la cartella nell'uscita delle prove; `.gitattributes` segna le estensioni delle immagini
|
||||||
|
come binarie e tiene `elenco.txt` con le righe Unix.
|
||||||
|
After Width: | Height: | Size: 383 B |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 18 KiB |