diff --git a/.gitattributes b/.gitattributes index c760a48..ccd596d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,11 @@ *.nsi text eol=lf # Binari: mai conversioni. *.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 diff --git a/.gitea/workflows/rilascio.yml b/.gitea/workflows/rilascio.yml index 017551d..e80825a 100644 --- a/.gitea/workflows/rilascio.yml +++ b/.gitea/workflows/rilascio.yml @@ -65,6 +65,9 @@ jobs: runs-on: ubuntu-latest needs: prove timeout-minutes: 30 + env: + # Come l'installatore di verifica.yml: l'immagine del runner non garantisce ICU, e qui non serve. + DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true" steps: - uses: actions/checkout@v4 diff --git a/.gitea/workflows/verifica.yml b/.gitea/workflows/verifica.yml index 23cd7d6..11bbd59 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -150,6 +150,9 @@ jobs: timeout-minutes: 30 env: NUMERO: ${{ gitea.run_number }} + # Questo lavoro gira sull'immagine del runner, che non garantisce ICU: pubblicare e impacchettare non ne hanno + # bisogno, quindi .NET va in globalizzazione invariante invece di fermarsi («Couldn't find a valid ICU package»). + DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true" steps: - uses: actions/checkout@v4 diff --git a/CLAUDE.md b/CLAUDE.md index 0658d50..bbb52b8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,7 +24,7 @@ All'inizio di ogni sessione leggi docs/stato.md. 9. I lettori si scrivono solo su campioni reali ripuliti. Il formato delle risposte non si inventa. 10. Mai password, cookie, gettoni, tasti, variabili o corpi di richieste e risposte nei log. Il client CDP registra solo nomi di comandi; il client del sito solo operazione o forma del percorso e stato. 11. La libreria non cancella e non sostituisce file da sola. -12. Dipendenze a elenco chiuso (§3): prima di aggiungerne una, chiedi. +12. Niente componenti esterni: niente ffmpeg, programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro specifiche pubbliche. Ammessi solo .NET/BCL con ASP.NET Core, Microsoft.Data.Sqlite, il browser (Chromium o WebView2 con Microsoft.Web.WebView2, regola 4) e MSTest; nella sola CI gitleaks e Trivy (docs/processo.md); nell'immagine Docker solo Chromium, i pacchetti Debian che gli servono e Xvfb (mai headless). Escono con la loro tappa della 0.3.0 (specifica §2 regola 13, §15): SkiaSharp con C1, ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. Prima di aggiungere qualunque cosa, chiedi. ## Convenzioni - Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano (glossario: appendice D). @@ -41,7 +41,7 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande - Repository: Gitea di casa, https://gitea.encke-hake.ts.net/Alby96/Febe (ramo main). Non è GitHub: niente strumenti GitHub. - Processo (rami `/`, commit piccoli, una richiesta di unione per ramo, verifica verde per unire in main, commit di unione, rilasci, correzioni urgenti): docs/processo.md. - CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`: - - `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb, ffmpeg e NSIS veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-` (con il segreto `REGISTRY_TOKEN`; senza, un avviso). + - `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium e Xvfb veri in Debian (più ffmpeg fino alla tappa C3, NSIS e Node fino alla tappa C6 della 0.3.0: regola 12), nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-` (con il segreto `REGISTRY_TOKEN`; senza, un avviso). - `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release. - `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore. - Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera. diff --git a/Directory.Packages.props b/Directory.Packages.props index bd954cc..dfe6144 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -1,9 +1,7 @@ - + - - diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index 844a3ac..49f4db5 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -88,9 +88,9 @@ Queste regole prevalgono su qualunque altra indicazione del documento e su qualu 8. **Al primo segnale ci si ferma** (§7.6). Nessun nuovo tentativo automatico dopo una richiesta di verifica o una disconnessione: Febe non rifà mai l'accesso da solo e non rinnova la sessione da sé. Una risposta senza i campi attesi ferma la sessione e avvisa; decide Alberto se rifare l'accesso. 9. **Tu non contatti mai Instagram e non apri i campioni grezzi.** Prove automatiche, script e verifiche tue usano solo il sito di prova locale (§14.2). Le prove dal vivo le lancia Alberto, con l'account di prova che ti indicherà. I campioni grezzi della sonda contengono dati personali di altre persone: lavori solo sulle copie ripulite (§14.5). 10. **Il formato delle risposte di Instagram non si inventa.** I lettori si scrivono soltanto su campioni reali raccolti nella tappa M0. Se un campione manca, chiedilo. -11. **Segreti fuori dai registri e fuori da git.** Mai password, cookie, gettoni (`fb_dtsg`, `lsd`, `csrftoken`, `x-ig-www-claim`), tasti premuti, corpi di richieste e di risposte, variabili delle interrogazioni né indirizzi con i loro parametri nei log, nei messaggi di errore e nel rapporto di diagnostica. La sessione salvata non va mai in git, nelle copie del database né nell'interfaccia. I campioni grezzi stanno fuori dal repository. -12. **La libreria non cancella e non sostituisce da sola.** Se un contenuto sparisce da Instagram, il file resta. Un file della libreria si elimina o si sostituisce solo per una scelta esplicita di Alberto. -13. **Dipendenze a elenco chiuso** (§3). Per aggiungerne una chiedi prima, spiegando perché non basta ciò che c'è. +11. **Segreti fuori dai registri e fuori da git.** Mai password, cookie, gettoni (`fb_dtsg`, `lsd`, `csrftoken`, `x-ig-www-claim`), tasti premuti, corpi di richieste e di risposte, variabili delle interrogazioni né indirizzi con i loro parametri nei log, nei messaggi di errore e nel rapporto di diagnostica. La sessione salvata non va mai in git, nelle copie del database né nell'interfaccia: la pagina Collegamento ne mostra solo la data della copia, i conteggi e i nomi dei valori che mancano, mai un valore (§6.0, §13.2). I campioni grezzi stanno fuori dal repository. +12. **La libreria non cancella e non sostituisce da sola.** Se un contenuto sparisce da Instagram, il file resta. Un file della libreria si elimina o si sostituisce solo per una scelta esplicita di Alberto. Anche la conversione del formato della libreria (§4.10) aggiunge il file convertito accanto all'originale, che resta; e nelle cartelle di esportazione Febe non cancella né sovrascrive mai nulla, salvo i propri file temporanei `.part`. +13. **Niente componenti esterni** (§3, decisioni di Alberto del 18 novembre 2026). Niente ffmpeg o ffprobe, nessun altro programma, nessuna libreria di terzi, nessun file di dati di terzi (caratteri, icone) e nessun codice copiato da altri progetti: tutto il codice si scrive in casa sulla libreria di base di .NET, i formati dalle loro specifiche pubbliche. Ammessi solo la libreria di base di .NET con ASP.NET Core, `Microsoft.Data.Sqlite`, il browser (regola 2: Chromium in Docker, WebView2 su Windows con `Microsoft.Web.WebView2`) e MSTest per le prove; nella sola CI gitleaks e Trivy, approvati da Alberto (`docs/processo.md`); nell'immagine Docker e nel contenitore delle prove solo Chromium, i pacchetti Debian che gli servono e Xvfb, perché Chromium ha sempre una finestra e non è mai headless (§11). Gli altri componenti ancora in uso escono con la loro tappa del traguardo 0.3.0 (§15), e finché la tappa non è unita il codice di prima li usa: SkiaSharp con C1, ffprobe con C2, ffmpeg con C3; NSIS (al suo posto un installatore scritto in casa), Node (la CI con passi di shell, git e curl verso l'API di Gitea), il carattere Archivo (i caratteri di sistema, `system-ui`) e le icone Lucide (icone SVG disegnate in casa) con C6. Prima di aggiungere qualunque cosa chiedi, spiegando perché non basta ciò che c'è. 14. **Resoconti onesti.** Se una cosa non funziona, o non l'hai potuta verificare, scrivilo così. Un «fatto» senza il risultato del controllo non vale. --- @@ -112,9 +112,31 @@ Sono scelte fatte al posto di Alberto per poter scrivere una specifica coerente. | **Profilo «Prudente» come predefinito** | §7.5 | Impostazione | | **Le storie si leggono con una richiesta per account e non risultano viste** | Decisione di Alberto del 16 novembre 2026 (#36, domanda 11 di §16): segnarle come viste sarebbe una scrittura, vietata dalla regola 5. Fino al 15 novembre valeva il contrario: solo dal visualizzatore, con Alberto fra gli spettatori | Domande 5 e 11 di §16 | | **Due percorsi generali: Libreria e Dati** | La richiesta originale era troncata su questo punto | Domanda 3 di §16 | -| **Carattere Archivo, icone Lucide**, copiati nel programma | Licenze libere (OFL e ISC), nessun caricamento da rete | — | +| **Caratteri di sistema** (`system-ui`) **e icone SVG disegnate in casa** | Decisione di Alberto del 18 novembre 2026 (regola 13): nessun file di dati di terzi, nessun caricamento da rete. Fino alla tappa C6 della 0.3.0 restano il carattere Archivo (OFL) e le icone Lucide (ISC), copiati nel programma (appendici B e C) | — | -**Dipendenze ammesse.** In esecuzione: `Microsoft.Data.Sqlite`, `SkiaSharp` con `SkiaSharp.NativeAssets.Linux.NoDependencies` (miniature e impronta visiva), `Microsoft.Web.WebView2` (solo Windows). Per le prove: MSTest. Nell'immagine Docker: i pacchetti di §11. Nell'interfaccia: nessun pacchetto npm; carattere e icone sono file copiati nel repository con le loro licenze. Tutto il resto viene dalla libreria di base di .NET (`System.Text.Json`, `HttpClient`, `ClientWebSocket`, `System.Security.Cryptography`). Ciò che manca e serve poco si scrive a mano: per esempio la lettura della data di scatto dai metadati di una foto. +**Dipendenze ammesse** (decisioni di Alberto del 18 novembre 2026, regola 13). Niente componenti esterni: niente ffmpeg o ffprobe, nessun altro programma, nessuna libreria di terzi, nessun file di dati di terzi, nessun codice copiato da altri progetti. In esecuzione si usano solo la libreria di base di .NET con ASP.NET Core (framework condiviso: `System.Text.Json`, `HttpClient`, `ClientWebSocket`, `System.Security.Cryptography`, `System.IO.Compression`…), `Microsoft.Data.Sqlite` e il browser: Chromium della distribuzione in Docker, WebView2 su Windows con il suo pacchetto `Microsoft.Web.WebView2`. Per le prove: MSTest. Nella sola CI: gitleaks e Trivy. Nell'immagine Docker e nel contenitore delle prove: Chromium, i pacchetti Debian che gli servono e Xvfb (§11), più ciò che la piattaforma .NET chiede al sistema (ICU, certificati). Nell'interfaccia: nessun pacchetto npm e nessun file di terzi: dalla tappa C6 i caratteri di sistema (`system-ui`, `-apple-system`, `"Segoe UI"`, `Roboto`, `sans-serif`) e icone SVG disegnate in casa. + +Tutto il resto si scrive in casa, dalle specifiche pubbliche dei formati e mai copiando codice di altri, con `Span` e senza allocazioni nei cicli che lavorano sui pixel (librerie di 200.000 elementi, processori di un server Unraid): + +- decodificatori di immagini: JPEG (ITU-T T.81 con codifica di Huffman a 8 bit: di base, sequenziale esteso e progressivo; scala di grigi, YCbCr, e CMYK o YCCK con il segmento APP14 di Adobe; restano fuori la codifica aritmetica, la precisione a 12 bit, il modo senza perdita e il gerarchico, e un file così è uno che non si decodifica), PNG, WEBP con e senza perdita (contenitore RFC 9649; il flusso con perdita VP8 è quello di RFC 6386), GIF (GIF89a, primo fotogramma), BMP. Delle immagini animate (GIF con più di un fotogramma, WEBP con `ANIM`/`ANMF`, PNG animato con `acTL`) si decodifica solo il primo fotogramma, per miniatura e impronta visiva: non si convertono mai (§4.10). Un'immagine troncata o rovinata (un PNG o un JPEG che finisce prima del suo marcatore di fine, un blocco che non torna) non si decodifica a metà: si rifiuta, con la tessera neutra e «File danneggiato o incompleto» (§8.4; risposta di Alberto del 25 novembre 2026); +- codificatori di immagini: JPEG, PNG, WEBP senza perdita; +- metadati delle immagini: lettura e scrittura di EXIF (orientamento compreso), profilo ICC e XMP, per copiarli da un formato all'altro (§4.10); +- lettori dei contenitori video ISO BMFF (MP4, MOV) e Matroska (MKV, WebM): durata, dimensioni, rotazione, tracce, codec e metadati del contenitore, al posto di ffprobe; +- lettori dei contenitori ASF (WMV, WMA), FLV e MPEG-PS (flusso di programma di ISO/IEC 13818-1, `.mpg`, `.vob`): durata, dimensioni, codec e data dove il contenitore la porta (risposta di Alberto del 18 novembre 2026, tappa C5). Solo lettura dei metadati: i loro video non si rimuxano e non si decodificano, salvo una traccia H.264 o H.265 dentro MPEG-PS, che i decodificatori qui sotto leggono come le altre; +- rimuxaggio in MP4, senza ricodifica; +- decodificatore H.264 (ITU-T H.264), per i fotogrammi, le miniature dei video importati e i video fermi (§4.10). **Tutto lo standard** (risposta di Alberto del 18 novembre 2026, «Tutto»): profili Baseline (anche non vincolato), Constrained Baseline, Main, Extended (FMO, ASO, fette ridondanti, partizione dei dati, fette SP e SI), High, High 10, High 4:2:2 e High 4:4:4 (Predictive e Intra, con i piani di colore separati e il modo senza perdita), CAVLC 4:4:4 Intra, monocromatico (4:0:0), con la profondità di bit che ogni profilo prevede (fino a 14 bit); video interlacciati (campi, PAFF, MBAFF); CAVLC e CABAC, trasformata 8×8 e matrici di quantizzazione; SVC (allegato G) e MVC (allegato H), di cui per fotogrammi e miniature si usano lo strato con la risoluzione più alta e la vista di base. Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, per JPG, PNG e WEBP. Solo un flusso rovinato dice «Fotogramma non disponibile per questo video»; +- decodificatore H.265/HEVC (ITU-T H.265; risposta di Alberto del 18 novembre 2026, dentro la 0.3.0, tappa C4), per gli stessi usi: tutti i profili della serie di conformità ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`, §16 domanda 18, risposta di Alberto del 25 novembre 2026), cioè Main, Main 10, Main Still Picture e le **estensioni di formato (RExt)** dei flussi della serie, che **restano**: 4:0:0, 4:2:2 e 4:4:4 fino a 12 bit, con i loro strumenti (predizione fra componenti, RDPCM, adattamento di Rice, `chroma_qp_offset_list`). Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, come per H.264. Non hanno flussi in quella serie e restano fuori la precisione estesa dei profili a 16 bit, l'allineamento del CABAC, lo scalabile (SHVC), il multivista (MV-HEVC), il 3D e i contenuti dello schermo (SCC): un video così dice «Fotogramma non disponibile per questo video»; +- VP9, AV1 e gli altri codec video non si decodificano (non richiesti): miniatura con la tessera neutra e «Fotogramma non disponibile per questo video»; +- miniature e impronta visiva (§8.4) sopra questi decodificatori; +- ridimensionamento (filtro cubico di Mitchell–Netravali, quello usato oggi con SkiaSharp) e un piccolo disegnatore 2D: riempimento e contorno con antialias di rettangoli anche arrotondati, cerchi, ovali, linee e tracciati, sfumature lineari, rotazioni, composizione di un'immagine su un'altra. Servono all'icona (`BrandIcon`, Febe.Desktop.Core), alle immagini della modalità dimostrativa (`DemoImages`, `DemoPart2`), all'anteprima dell'importazione (`ImportPreview`), alle immagini del sito di prova (`MediaFactory`) e ai generatori delle prove (`LibraryTestSupport`, `ImportTestFiles`: le varianti ridimensionate, ricompresse e ritagliate di §14.1). Non deve dare gli stessi pixel di SkiaSharp: basta che le prove dei doppioni passino con le soglie di §8.4 invariate; +- l'installatore di Windows (§12), al posto di NSIS: un eseguibile .NET scritto in casa che porta Febe compresso con `System.IO.Compression`, lo installa per l'utente, crea i collegamenti e la voce di disinstallazione, e si costruisce con `dotnet publish` (tappa C6); +- i passi della CI (`docs/processo.md`), al posto delle azioni che vogliono Node: script di shell con git (scaricare il commit) e curl verso l'API di Gitea (artefatti, stati, rilasci) (tappa C6); +- le icone dell'interfaccia: SVG disegnati in casa, tratto 1,75, con gli stessi nomi d'uso dell'appendice C (tappa C6). + +**Il passaggio avviene a tappe nella 0.3.0** (§15): C1 codec delle immagini (esce SkiaSharp con `SkiaSharp.NativeAssets.Linux.NoDependencies`), C2 contenitori e metadati senza ffprobe, C3 tutto H.264 (esce ffmpeg, dall'immagine Docker, dalla CI e dalle prove; fatto sul ramo `funzione/decoder-h264`, non ancora unito), C4 HEVC, C5 lettori ASF, FLV e MPEG-PS, C6 CI senza Node, installatore senza NSIS, caratteri di sistema e icone nostre. **Finché una tappa non è unita, il codice di prima li usa ancora**: SkiaSharp per miniature, impronta visiva, icona, immagini della modalità dimostrativa e del sito di prova, anteprima dell'importazione e generatori delle prove; ffmpeg e ffprobe dal PATH per i video importati; NSIS e Node nella CI; Archivo e Lucide nell'interfaccia. Dati di prova per questi lavori (risposte di Alberto del 18 novembre 2026, §16 domande 15 e 16): + +- Le serie di conformità ITU-T: H.264.1 per C3 (12 flussi già scaricati e messi nel repository sul ramo `funzione/decoder-h264`, con il permesso di Alberto; si scaricano anche quelli dei profili che mancano, ora che il decodificatore copre tutto lo standard) e H.265.1 per C4, in `tests/Febe.Tests/Media/H264/Conformita` e `tests/Febe.Tests/Media/H265/Conformita`. Nel repository **solo i flussi e l'MD5 dell'uscita di riferimento**, mai le uscite decodificate, con un `LEGGIMI.md` che dice la fonte (indirizzo dell'ITU-T, data dello scaricamento, condizioni d'uso) e l'elenco (nome, profilo, MD5 del flusso e dell'uscita). +- Le immagini di riferimento dei codec, generate una sola volta con SkiaSharp prima che esca (permesso di Alberto, già fatto), tenute come file di prova della tappa C1. **Lingua del codice.** Identificatori e commenti in inglese; interfaccia, documentazione e messaggi per l'utente in italiano. Il glossario dell'appendice D lega i due vocabolari. @@ -159,7 +181,7 @@ Sono scelte fatte al posto di Alberto per poter scrivere una specifica coerente. ### 4.3 Che cosa si scarica -Due parole vanno tenute distinte. Un **elemento** è una pubblicazione: un post (anche con più foto e video), una storia, un contenuto di una raccolta in evidenza. Un **file** è ogni singola foto o video. Nell'interfaccia una tessera è un elemento e i contatori contano elementi; un post con quattro foto è un elemento con quattro file. +Due parole vanno tenute distinte. Un **elemento** è una pubblicazione: un post (anche con più foto e video), una storia, un contenuto di una raccolta in evidenza. Un **file** è ogni singola foto o video. Nell'interfaccia una tessera è un elemento e i contatori contano elementi; un post con quattro foto è un elemento con quattro file. Solo con «Tutte le foto» (§4.6) una tessera è un file e la riga del giorno conta i file. | Tipo (`{tipo}` e cartella) | Che cos'è | Interruttori dell'account | Dove si vede | `{codice}` nel nome | |---|---|---|---|---| @@ -181,6 +203,7 @@ Ogni account ha le sue (mockup 05): - **Tieni aggiornato**: sì o no. Con «no» si fa un solo scaricamento, poi l'account resta in pausa. - **Frequenza dei controlli**: Bassa, Normale, Alta (§7.3) oppure Su misura, che mostra due campi: ogni quante ore controllare i post, e l'intervallo massimo fra due controlli delle storie. - **Cosa scaricare**: i sei interruttori di §4.3. +- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): «Come le impostazioni generali» (predefinito) oppure un ordine suo dei tipi, che si cambia trascinando le righe. Pesa sulle visite del motore a quell'account e sulla coda dei suoi file (§7.2, §6.5). I tipi spenti in «Cosa scaricare» restano nell'elenco, attenuati. - **Limiti**: quanto indietro nel tempo (tutto, ultimi N post, da una data); massimo di post di storico al giorno; dimensione oltre la quale un video si salta (vuoto significa nessun limite); video delle storie sì o no. - **Cartella**: per impostazione predefinita una cartella con il nome dell'account dentro la Libreria. Se ne può scegliere un'altra, anche fuori dalla Libreria. I percorsi dei file nel database sono relativi alla cartella dell'account. @@ -188,16 +211,18 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz ### 4.5 Tenere aggiornato -«Appena pubblicato» va inteso così: **entro la sessione successiva**, non in tempo reale. Con il profilo Prudente significa di norma fra 20 e 90 minuti per gli account che Alberto segue, e l'intervallo scelto per quelli che non segue. Di notte Febe non lavora. L'interfaccia deve dirlo con numeri veri (riquadro di §4.4 e pagina Attività), e avvisare quando gli account e le frequenze chiesti superano ciò che i tetti consentono: in quel caso i controlli si diradano, non si forzano. +«Appena pubblicato» va inteso così: **entro la sessione successiva**, non in tempo reale. Con il profilo Prudente significa di norma fra 20 e 90 minuti per gli account che Alberto segue, e l'intervallo scelto per quelli che non segue. Di notte Febe non lavora. L'interfaccia deve dirlo con numeri veri (riquadro di §4.4 e Dashboard, §7.9), e avvisare quando gli account e le frequenze chiesti superano ciò che i tetti consentono: in quel caso i controlli si diradano, non si forzano. ### 4.6 Libreria - Mosaico di tutti gli elementi in ordine di pubblicazione, raggruppati per giorno (mockup 01). Filtri per tipo, account, periodo, provenienza (scaricati o importati). Ricerca per nome dell'account e testo della didascalia. - Deve restare fluida con 200.000 elementi: caricamento a finestre, miniature generate una volta e conservate. -- Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. -- Eliminare chiede conferma e, per impostazione predefinita, ricorda la scelta: l'elemento resta nel database senza file, nello stato «eliminato», così non viene riscaricato. La conferma offre anche «Eliminalo e lascia che torni». -- Scheda dell'account con gli elementi divisi in Post, Storie, In evidenza, Taggati (mockup 12), le impostazioni e la cronologia dei controlli. -- Selezione multipla per esportare o eliminare. +- **«Raggruppa i post» o «Tutte le foto»** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): un interruttore a due voci nella riga di strumenti della Libreria e della vista dei contenuti della scheda account. «Raggruppa i post», il predefinito, è il mosaico di oggi: una tessera per elemento, con il numero dei file in alto a destra. «Tutte le foto» mette una tessera per file, video compresi, nello stesso ordine (data dell'elemento, poi posizione nella serie): utile quando un post ha più foto. In quel modo la tessera di un file di una serie dice la sua posizione («2/4»), il conteggio della riga del giorno conta i file, il visualizzatore si apre su quel file e le frecce vanno di file in file. La selezione è di file: «Copia in…» e «Fotogrammi…» lavorano sui file scelti; l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e la conferma lo dice («3 file scelti appartengono a 2 post: elimino i 2 post, 9 file»). La scelta si ricorda per pagina, una per la Libreria e una per le viste degli account, nel browser di chi guarda come il tema (memoria locale del browser, letta e scritta dentro un `try`); se manca o non si legge vale «Raggruppa i post». Filtri, ricerca e caricamento a finestre funzionano uguali nei due modi, anche con 200.000 elementi e i loro file. +- **File danneggiato o incompleto** (risposta di Alberto del 25 novembre 2026). Un'immagine troncata o rovinata, scaricata o importata (§3, §8.4), si rifiuta e lo dice: tessera neutra nel mosaico e «File danneggiato o incompleto» nel visualizzatore al posto dell'immagine, con le azioni sul file (mostra nella cartella o scarica, elimina) che restano. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. +- Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. Con l'esportazione (§4.10, traguardo 0.3.0): «Copia in…», «Fotogramma» per i video, «È un video fermo?» a richiesta, e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· fotogramma»). +- Eliminare chiede conferma e, per impostazione predefinita, ricorda la scelta: l'elemento resta nel database senza file, nello stato «eliminato», così non viene riscaricato. La conferma offre anche «Eliminalo e lascia che torni». Le copie esterne di un elemento eliminato restano dove sono (§4.10). +- Scheda dell'account con gli elementi divisi in Post, Storie, In evidenza, Taggati (mockup 12), con lo stesso interruttore «Raggruppa i post» / «Tutte le foto», le impostazioni e la cronologia dei controlli. +- Selezione multipla per esportare (elenco CSV di §4.8; «Copia in…» e «Fotogrammi…» di §4.10) o eliminare. Dal traguardo 0.3.0 un filtro «Copie» (Tutti, Non ancora copiati, Copiati, Tolti o superati) in Libreria e nella scheda dell'account. ### 4.7 Percorsi e nomi dei file @@ -226,12 +251,70 @@ marta.demo\profilo\2026-09-30_21-04-33_a3f9c2e1_1.jpg - **Limiti e comportamento**: §7 e mockup 07. - **Importazione** di foto e video già esistenti, con controllo dei doppioni prima di copiare: §9 e mockup 09. - **Avvisi**: striscia rossa in ogni pagina quando Febe è fermo e serve Alberto (mockup 11); notifica di Windows nella versione desktop; messaggio Telegram facoltativo (§13.3). -- **Esportazione** dell'elenco degli elementi in CSV con `;` come separatore e codifica UTF-8 con BOM, perché si apra bene in Excel italiano. +- **Esportazione** dell'elenco degli elementi in CSV con `;` come separatore e codifica UTF-8 con BOM, perché si apra bene in Excel italiano. Le copie dei file in cartelle esterne, la conversione del formato (delle copie e della libreria), i fotogrammi dei video e i video fermi sono in §4.10. ### 4.9 Fuori dalla versione 1 Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, più account Instagram nella stessa istanza, pubblicazione di contenuti, aggiornamento automatico del programma, unione di tracce audio e video separate. Non progettare nulla in funzione di queste cose. +### 4.10 Esportazione + +Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Finché le tappe non sono unite, l'unica esportazione è l'elenco CSV di §4.8. + +**Principio.** Un'esportazione copia in una cartella esterna (una **destinazione**) file che sono già in libreria: così come sono, convertiti in un altro formato o come fotogramma di un video. È solo lavoro sul disco: niente Instagram, niente CDN, niente Governatore, niente `action_log`. Un file che manca in libreria non si riscarica: la copia dice «File non presente in libreria». + +**Destinazioni.** + +- Una **cartella di esportazione generale** (Impostazioni → Esportazione) e, per ogni account, una **cartella propria facoltativa** che la sostituisce, con l'interruttore **«Esporta questo account»** (scheda account → Impostazioni, blocco «Copie esterne», sotto «Cartella»). Ogni account ha al più una destinazione effettiva: «già copiato» è un sì o un no. +- Nella cartella generale Febe mette sempre per primo il segmento con il nome dell'account ripulito, perché gli account non si scontrino; sotto vale lo schema dei nomi della destinazione, «Come la libreria» (predefinito) oppure uno proprio, controllato come quelli di §4.7. I suffissi dei fotogrammi (`_fotogramma`, `_t0m12s340`, `_f001`) si aggiungono prima dell'accorciamento a 240 caratteri. +- Ogni destinazione dice: tipi di contenuto (post foto, post video, storie, evidenza, taggati, profilo), formati delle copie, schema dei nomi, «Automatica». +- Cartelle rifiutate: dentro **o contenenti** Dati, Libreria, una cartella di account (anche fuori dalla Libreria) o `/importa`; la radice di un disco o di una condivisione. Lettere di unità e percorsi UNC che puntano allo stesso posto si riconoscono con un file di prova, non confrontando i testi: un `.febe-prova-*.part` scritto e tolto come quello del punto qui sotto, **solo nella cartella candidata**, che deve già esistere, e mai in Dati, Libreria, cartelle degli account o `/importa`. Lì Febe lo cerca soltanto, in lettura: risalendo le loro cartelle madri (una di loro è dentro la candidata) e, per ogni cartella madre della candidata, allo stesso percorso relativo sotto ciascuna (la candidata è dentro una di loro). Se il file di prova non si scrive, la cartella si rifiuta. Si ricontrolla quando cambia la cartella di un account. +- **La radice di una destinazione non si crea mai**: un disco o una condivisione assente non deve diventare una cartella locale. Le sottocartelle dello schema sì. Prima di ogni gruppo di copie Febe scrive e toglie un file `.febe-prova-*.part`; se non riesce, la destinazione va in pausa, lo stato si vede in Impostazioni e nella Dashboard e il giro orario riprova. Mai la striscia rossa, che resta del motore. I controlli sul disco esterno sono asincroni e brevi: una condivisione staccata non blocca l'interfaccia. +- Spazio: per le destinazioni non valgono i 10 GB / 5 % della libreria; basta spazio libero per il prossimo file più un margine. Su FAT32 conta il limite di 4 GB per file. +- **Mai sovrascrivere, mai cancellare** (regola 12): si scrive con un `.part`, si verifica lo SHA-256, si rinomina su un nome libero. Togliere una destinazione toglie solo la configurazione («I file già copiati restano dove sono»); eliminare un elemento dalla libreria non tocca le sue copie. I `.part` rimasti si tolgono solo nelle cartelle di lavori non finiti, mai con una scansione della destinazione. + +**Conversione del formato.** Due impostazioni distinte, **entrambe spente** per impostazione predefinita: + +- **per le copie**: il formato in cui arrivano i file nella destinazione. Valori predefiniti in Impostazioni → Esportazione, che ogni destinazione e ogni singola «Copia in…» possono cambiare; +- **per la libreria**: Febe **aggiunge** all'elemento il file convertito, e l'originale **resta** accanto (regola 12). Il convertito è legato al suo originale: SHA-256, impronta visiva, miniatura, controllo dei doppioni e `_febe.jsonl` restano quelli dell'originale, e il convertito non si riscarica né conta come doppione. Come si registra lo fissano le tappe E1 ed E3. + +| | Scelte | Come | +|---|---|---| +| Foto | **Originale** (predefinito), JPG, PNG, WEBP senza perdita | Decodificatori e codificatori di Febe (§3). Stesso formato di partenza: copia byte per byte, mai una ricodifica. HEIC, AVIF, raw, immagini animate (GIF con più di un fotogramma, WEBP con `ANIM`/`ANMF`, PNG con `acTL`) e ciò che non si decodifica: si copia l'originale, con una nota nel resoconto | +| Video | **Originale** (predefinito), MP4 | Solo rimuxaggio, mai ricodifica. Un video che non si può portare in MP4 senza ricodifica si copia com'è, con una nota | + +- **Con perdita solo se scelto**: l'unica conversione con perdita è JPG, a qualità 92, e la finestra lo dice («con perdita»). PNG, WEBP senza perdita e il rimuxaggio non perdono nulla; un'immagine animata non si converte mai, perché perderebbe i fotogrammi dopo il primo. La trasparenza in JPG diventa bianco. +- **Metadati: tutti quelli possibili.** Il convertito è la stessa immagine con un'altra estensione: EXIF con l'orientamento (che resta un dato, i pixel non si ruotano), profilo ICC, XMP, nei posti che il formato di arrivo prevede (APP1 e APP2 in JPG, `eXIf`, `iCCP` e `iTXt` in PNG, `EXIF`, `ICCP` e `XMP ` in WEBP); per i video i metadati del contenitore (date, rotazione, lingua delle tracce). La data del file segue `libreria.data-file-pubblicazione`, fotogrammi compresi. Ciò che il formato di arrivo non può tenere lo dice il resoconto. + +**Fotogrammi e video fermi.** + +- **Fotogrammi a richiesta**, dal visualizzatore (questo istante, uno ogni k secondi, N in tutto, con anteprima) o con «Fotogrammi…» dalla selezione (le foto si saltano, e la finestra lo dice): JPG, PNG o WEBP senza perdita, a piena risoluzione, con i decodificatori H.264 e H.265 (HEVC) di Febe (§3; H.265 dalla tappa C4). Un video in un altro codec (VP9, AV1 e gli altri, non richiesti) dice «Fotogramma non disponibile per questo video». Uscita: «Scarica» (un file, o uno zip per più file) oppure una destinazione. +- **Solo il fotogramma**: l'audio si perde, e la finestra lo dice: «Il fotogramma non ha l'audio». +- **Video fermo** (mostra sempre la stessa immagine): l'analisi si fa **solo a richiesta**, dal visualizzatore («È un video fermo?») o dalla selezione, mai in sottofondo. Esiti: «Fermo», «In movimento», «Non analizzabile», salvati per SHA-256 (`video_analysis`, con il numero dell'algoritmo per poter rianalizzare). Per un video fermo il visualizzatore mostra «Un'immagine sola per tutto il video: basta un fotogramma» con «Salva il fotogramma»; nelle destinazioni si copia comunque **il video intero**, che tiene l'audio. +- Copie, conversioni e analisi lunghe partono fuori dalle sessioni del motore; esportazione, importazione e ricostruzione non girano insieme. + +**Manuale e automatica.** + +- **Manuale sempre**: «Copia in…» dalla selezione, dal filtro corrente, dal visualizzatore e dalla scheda dell'account. +- **Automatica spenta** per ogni destinazione. Quando Alberto l'accende, Febe chiede che cosa fare di ciò che è già in libreria; la risposta proposta è **«Solo i nuovi»**. Un elemento nuovo entra in coda dopo la sua riga di `_febe.jsonl`; un giro di recupero all'avvio e ogni ora. + +**«Già copiato».** + +- Una riga per copia (`export_copy`). Una copia è identificata da SHA-256 dell'originale, destinazione, **account effettivo** (quello del segmento con il nome dell'account nella cartella generale, o l'account della cartella propria), variante (intero, convertito, fotogramma), formato e istante del fotogramma; la riga tiene anche percorso relativo, byte e SHA-256 della copia, data, stato. Si cerca per SHA-256, non per l'identificativo di Instagram, che gli importati possono non avere: un elemento eliminato con «Eliminalo e lascia che torni» ritrova le sue copie quando torna. +- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta. +- **Adozione per percorso**: se nel percorso di arrivo c'è già un file, Febe lo adotta come copia invece di scriverne un secondo solo se è proprio quella copia. Per le copie byte per byte vuole lo stesso SHA-256 dell'originale; per i convertiti e i fotogrammi Febe rifà la conversione con le impostazioni di quella copia (i suoi codificatori sono fissi, §3) e vuole lo stesso SHA-256 del file trovato. La sola dimensione non basta mai. Se non coincide, il nome è occupato: Febe scrive su un nome libero e il file trovato resta com'è. Copre un database perso, un backup vecchio, due istanze sulla stessa cartella; «Riconosci le copie già presenti» lo fa per tutta la destinazione. +- Per elemento, calcolato al momento (nessuna tabella derivata): «Copiato», «Copiato in parte», «Non ancora copiato»; un video copiato solo come fotogramma lo dice («fotogramma», non «intero»). +- Dove si vede: un piccolo segno sulla tessera (solo se esiste almeno una destinazione; differenza voluta rispetto al mockup 01), le righe del pannello File del visualizzatore («Copiato in Disco USB il 3 novembre · intero», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo»), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie». + +**Casi particolari.** + +- **Lo stesso post in due account** (il post dell'uno e il taggato dell'altro, §8.3): un'impostazione sceglie fra **«Una copia per account»**, ognuna nella sua destinazione, che è il **predefinito** (risposta di Alberto del 18 novembre 2026), e **«Una copia sola»**, nel primo account che la copia; l'altro la mostra «Copiato» con la destinazione dove sta. Lo si riconosce dallo SHA-256. +- **Una storia entrata in una raccolta in evidenza** conta anche come evidenza: una destinazione con il solo tipo «evidenza» la copia. Per lo stesso account effettivo un file si copia una volta sola in una destinazione: la storia e la sua evidenza sono una copia. Con «una copia per account» (qui sopra) lo stesso SHA-256 sta invece due volte nella cartella generale, una sotto il segmento di ciascun account. + +**Docker e Windows.** In Docker le destinazioni sono sottocartelle di `/esporta`, scelte da un elenco come le sorgenti di importazione (`..` rifiutato). `/esporta` è attivo **solo se dichiarato** con `--esporta` o `FEBE_ESPORTA` e solo se è davvero un punto di montaggio (letto da `/proc/self/mountinfo`): altrimenti non si scrive nulla. Nel Dockerfile non c'è una riga `VOLUME` per `/esporta`: un volume anonimo la farebbe sembrare montata e riempirebbe in silenzio il disco delle immagini di Unraid (§11). Si cambia il proprietario solo della radice, mai in modo ricorsivo. Su Windows la cartella si sceglie con il selettore nativo, anche su un percorso di rete o UNC (§12). + +**Fuori dal traguardo 0.3.0.** Ricodifica dei video (VP9, AV1, HEVC → MP4); conversione al momento dello scaricamento; unione di immagine e traccia audio dei post con musica (§4.9); un diario delle copie nelle destinazioni; la colonna «Copiato in» nel CSV. + --- ## 5. Architettura @@ -314,7 +397,7 @@ public interface IRandomSource { double NextDouble(); } Decisione di Alberto del 16 novembre 2026 (issue #36). Il lavoro è a tappe (S0–S7 nell'issue); finché una tappa non è unita, il comportamento di Febe è quello delle sezioni che seguono. -**Come nasce la sessione.** Alberto accede a mano nel browser di Febe (§4.1). Quando preme «Ho finito», con la raccolta `richieste` (tappa S4, più sotto), Febe copia nella **sessione salvata**: +**Come nasce la sessione.** Alberto accede a mano nel browser di Febe (§4.1). Quando preme «Ho finito», con la raccolta `richieste` (tappa S4, più sotto), Febe copia nella **sessione salvata**, e la copia si fa anche quando Alberto chiude la finestra del browser su Windows, quando in Docker lascia la pagina del browser o ne chiude la scheda, e quando il suo permesso di guida finisce, sempre prima che la pagina torni al motore (decisioni del 18 e del 25 novembre 2026, tappa S4b di #36, «Quando si copia» più sotto): - i cookie del sito, valori compresi, con `Network.getCookies` (§6.1), chiesti per la radice del sito e per ogni percorso di `richieste..json` tagliato prima del primo valore (`/api/dati/profilo/{nome}` → `/api/dati/profilo/`), così un cookie limitato a un percorso arriva con il suo percorso. Di ogni cookie si tengono nome, valore, dominio, percorso, solo-host, `Secure`, `HttpOnly` e scadenza. Un cookie partizionato, o con un valore che il browser non rimanderebbe (caratteri di controllo, non ASCII, `;`), si scarta e si conta; - l'user agent del browser (`navigator.userAgent`), tale e quale; @@ -322,7 +405,11 @@ Decisione di Alberto del 16 novembre 2026 (issue #36). Il lavoro è a tappe (S0 User agent e valori della pagina si leggono con **una sola** `Runtime.evaluate` in sola lettura, scritta solo dai nomi della sezione `page` (identificatori controllati al caricamento del catalogo, `^[A-Za-z_$][A-Za-z0-9_$]*$`, messi nell'espressione come testi JSON: una copia modificata del file non può metterci codice) e passata da `ReadOnlyScriptGuard`. Ogni modulo si legge nel suo `try`: un modulo assente o che la pagina rifiuta, un valore che non è testo o numero, più lungo di 4096 caratteri o con caratteri di controllo o non ASCII **manca**, e non si inventa (regola 9). -La copia si fa solo da una pagina del sito che non sia un percorso di accesso o di verifica delle regole di arresto (§7.6), dentro i comandi del collegamento, dopo il controllo del cookie di sessione e prima del riposo, e solo finché dura il permesso di guida di Alberto («Accedi a Instagram», «Usa il browser»): Febe tiene il permesso e il turno della pagina per tutta la copia, e se il permesso finisce comunque prima del salvataggio la copia si butta. Dura al più 10 secondi; oltre, è un errore del browser. Una copia riuscita **sostituisce** la sessione salvata anche se manca qualche valore: tenere una copia più vecchia potrebbe tenere i cookie di un altro accesso. Il messaggio di «Ho finito» conta solo i valori e i `doc_id` che un'operazione configurata manda, e dice com'è: le richieste che li usano non partono e, alla prima, Febe si ferma come disconnessione e chiede un nuovo accesso (mai un ritorno alle pagine) finché un nuovo «Ho finito» non li trova. Dopo «Ho finito» il permesso di guida è finito: per rifare la copia Alberto riapre il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e preme di nuovo «Ho finito», ed è ciò che il messaggio di una copia rifiutata gli dice. Una copia rifiutata (pagina fuori dal sito, pagina di accesso o verifica, browser che non risponde, nessun user agent) la lascia com'era. Chiudere la finestra del browser su Windows o lasciar scadere il permesso di guida **non** copia: serve «Ho finito». Con il sito di prova e `--accesso-di-prova` la copia si fa anche dopo l'accesso automatico, come la farebbe Alberto. +La copia si fa solo da una pagina del sito che non sia un percorso di accesso o di verifica delle regole di arresto (§7.6), dentro i comandi del collegamento, dopo il controllo del cookie di sessione e prima del riposo. Si fa solo dentro il permesso di guida di Alberto («Accedi a Instagram», «Usa il browser»): Febe tiene il permesso e il turno della pagina per tutta la copia, a «Ho finito» come alla chiusura della finestra e alla fine del permesso, e in Docker lasciando la pagina del browser («Quando si copia»), e se il permesso finisce comunque prima del salvataggio la copia si butta. In ogni caso la copia dura al più 10 secondi; oltre, è un errore del browser e la copia si butta. + +**Quando si copia** (decisione di Alberto del 18 novembre 2026, tappa S4b di #36). In tre momenti, sempre **prima che la pagina torni al motore**: a «Ho finito»; quando Alberto chiude la finestra «Browser di Febe» su Windows (anche quando resta ridotta a icona troppo a lungo); quando il permesso di guida finisce da solo. In Docker, al posto della finestra, conta **lasciare la pagina del browser** (risposta di Alberto del 25 novembre 2026): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota della pagina Collegamento a un'altra pagina di Febe, chiudere la scheda o la finestra del browser in cui la guarda, o perderne il collegamento. Febe lo riconosce dal server: si chiude l'ultima vista remota aperta durante il permesso (la pagina che si lascia lo dice subito; una scheda chiusa o un collegamento perso chiudono la sua connessione) e per 5 secondi non se ne apre un'altra, così ricaricare la pagina non è lasciarla. Da lì vale ciò che vale per la finestra di Windows: la copia, se la pagina è sul sito e non è di accesso o di verifica, poi il permesso finisce e la pagina torna al motore. Finché questo non è costruito, in Docker si copia solo a «Ho finito» e alla fine del permesso. Alla chiusura della finestra, lasciando la pagina in Docker e alla fine del permesso la copia ha le stesse garanzie di «Ho finito»: i comandi del collegamento, la presa del permesso di guida e il turno della pagina, che Febe rilascia solo quando la copia è salvata o buttata (la finestra tiene una presa del permesso finché la copia non è finita; la fine del permesso copia prima di rilasciarlo); il motore intanto è fermo e aspetta (regola 4: la pagina non è mai di due). Si copia solo con il cookie di sessione nel browser e solo da una pagina del sito che non sia di accesso o di verifica (né il riposo). Alla chiusura della finestra e lasciando la pagina in Docker Febe aspetta al più 30 secondi che finisca un altro comando del collegamento in corso, perché il motore non resti trattenuto; poi vale il limite di 10 secondi della copia. Un errore imprevisto (database, disco) si scrive nel registro con il solo tipo d'errore e il permesso si rilascia lo stesso. Lì non c'è un messaggio: l'esito è una riga del registro con soli conteggi e lo stato nel riquadro della pagina Collegamento. La fine del permesso non copia di nuovo se la finestra (o la pagina lasciata) ha appena copiato, e un «Ho finito» tardivo dopo una copia fatta lasciando il browser non rilegge nulla e dice che la sessione era già stata copiata. + +**Copia incompleta** (impostazione `sessione.copia-incompleta`, tappa S4b di #36, letta a ogni copia). Una copia a cui manca qualche valore o `doc_id` che un'operazione configurata manda segue l'opzione «Copia incompleta» della pagina Collegamento: **«Sostituisci comunque»** (predefinita), perché tenere una copia più vecchia potrebbe tenere i cookie di un altro accesso; oppure **«Tieni la copia completa di prima»**, che lascia la sessione salvata com'era se quella era completa, e lo dice («Ho tenuto la copia del 17 novembre: in quella nuova mancavano …»). Una copia completa sostituisce sempre. Il messaggio di «Ho finito» conta solo i valori e i `doc_id` che un'operazione configurata manda, e dice com'è secondo ciò che è successo. Se la copia nuova ha sostituito quella di prima («Sostituisci comunque», o «Tieni la copia completa di prima» quando quella di prima era già incompleta): le richieste che li usano non partono e, alla prima, Febe si ferma come disconnessione e chiede un nuovo accesso (mai un ritorno alle pagine) finché un nuovo «Ho finito» non li trova. Se Febe ha tenuto la copia completa di prima: la sessione salvata resta quella di quella data, le richieste continuano a usarla e nulla si ferma per quei valori; la copia nuova non si tiene. Dopo «Ho finito» il permesso di guida è finito: per rifare la copia Alberto riapre il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e preme di nuovo «Ho finito», ed è ciò che il messaggio di una copia rifiutata gli dice. Una copia rifiutata (pagina fuori dal sito, pagina di accesso o verifica, browser che non risponde, nessun user agent) la lascia com'era. Con il sito di prova e `--accesso-di-prova` la copia si fa anche dopo l'accesso automatico, come la farebbe Alberto. | Valore della sessione | Nella richiesta | Dove lo tiene la pagina di Instagram | |---|---|---| @@ -337,11 +424,12 @@ La copia si fa solo da una pagina del sito che non sia un percorso di accesso o | `comet_req` | `__comet_req` (prima costante 7) | `SiteData.comet_env` | | `ccg` | `__ccg` | `WebConnectionClassServerGuess.connectionClass` | | `entry_nonce` | `x-fb-entry-nonce` | `BootloaderConfig.nonce` | +| `spin_r`, `spin_b`, `spin_t` | `__spin_r`, `__spin_b`, `__spin_t` | `SiteData.__spin_r`, `SiteData.__spin_b`, `SiteData.__spin_t`: fotografati dalla pagina come gli altri valori (decisione del 18 novembre 2026), dalla forma del codice pubblico della pagina nel HAR; i nomi esatti e chi li mette nella richiesta sono H23 (§6.6) | | `doc_id` | `doc_id` | modulo `_instagramRelayOperation` | I posti vengono dal codice pubblico della pagina nel HAR, solo forme e nomi (regola 9; decisione del 17 novembre 2026). Il catalogo rifiuta, quando si carica, un'operazione configurata che manda un valore `session:` senza posto nella sezione `page` (user agent e claim non ne hanno bisogno). -La sessione salvata sta in `Dati/sessione/sessione.json`, cifrata (§13.2), fuori dal database e dalle sue copie. Dopo la copia il browser si chiude o torna al riposo; si riapre solo per un nuovo accesso o per una verifica, e intanto il motore è fermo (regola 4). Un nuovo accesso ricopia tutto e sostituisce la sessione salvata: i valori della pagina restano quelli copiati fino alla copia dopo. Nei cookie del browser Febe non scrive mai. +La sessione salvata sta in `Dati/sessione/sessione.json`, cifrata (§13.2), fuori dal database e dalle sue copie. Non ha un limite fisso di età (decisione del 18 novembre 2026): vale finché il sito la accetta, e una risposta da sessione scaduta ferma come disconnessione (§7.6). Dopo la copia il browser si chiude o torna al riposo; si riapre solo per un nuovo accesso o per una verifica, e intanto il motore è fermo (regola 4). Un nuovo accesso ricopia tutto e sostituisce la sessione salvata: i valori della pagina restano quelli copiati fino alla copia dopo. Nei cookie del browser Febe non scrive mai. **Il client del sito.** Una sola classe di Febe parla con `www.instagram.com` (regola 1): @@ -361,11 +449,15 @@ Le risposte vanno ai lettori come quelle catturate (§6.2, §6.4), con gli stess **La sessione salvata e l'opzione «raccolta» (tappa S4).** Febe per Windows e Febe in Docker hanno un'opzione **«raccolta»**: `pagine`, il predefinito, oppure `richieste`. In Docker si sceglie con `--raccolta` o con la variabile `FEBE_RACCOLTA` (vince la riga di comando), su Windows con `--raccolta` (Febe.exe non ha altre fonti di opzioni). Solo con `richieste` **e** un catalogo del sito con almeno un'operazione configurata la composizione costruisce la sessione salvata, il client del sito per il motore e la copia a «Ho finito»; altrimenti non costruisce nulla, non legge i valori dei cookie né i moduli della pagina, e tutto resta com'era: con `pagine` sempre, e con Instagram anche con `richieste`, perché le sue dieci operazioni restano non configurate (decisione del 17 novembre 2026). Il registro dice quale delle due strade ha preso. Con il sito di prova e `pagine` nemmeno le prove d'insieme cambiano strada. -Perché la porta resta chiusa con Instagram: +Perché la porta resta chiusa con Instagram (aggiornato il 18 novembre 2026): -- chiedere `require()` di un modulo dentro la pagina viva di Instagram potrebbe eseguire la fabbrica di un modulo non ancora avviato o far segnalare un errore dalla pagina (H21, da verificare con Alberto prima di accenderla); -- i moduli dei `doc_id` potrebbero non essere caricati sulla pagina dove Alberto preme «Ho finito» (H22); -- restano senza fonte stabilita (`pending`) valori che le richieste di Instagram contengono: `__spin_r`, `__spin_b`, `__spin_t` (la pagina ha chiavi con quei nomi, ma non si vede chi le mette nella richiesta), `__req` (contatore delle richieste), `__s` (sessione della pagina), `__dyn`, `__csr`, `__hblp`, `__hsdp`, `__sjsp` (moduli caricati), `__crn` (percorso della pagina), `__d`, `x-web-session-id`, le intestazioni del browser (`referer`, `priority`, `sec-ch-ua…`, `x-ig-max-touch-points`) e i nomi che la sonda ha tolto. Un'operazione che ne usa uno non si può configurare (regola 9, H15). +- H21 (`require()` dei moduli nella pagina viva di Instagram è innocuo) e H22 (i moduli dei `doc_id` e dei valori sono caricati sulla pagina di «Ho finito») **restano da verificare**: le verifica Alberto nella prova dal vivo (tappa S7 di #36; risposta del 18 novembre 2026). Finché il loro esito non è scritto in `docs/sonda/esito.md` (§6.6) sono ancora un motivo per tenere chiusa la porta. Una nuova sonda non si fa ora; +- `__spin_r`, `__spin_b`, `__spin_t` hanno una fonte: si fotografano dalla pagina come gli altri valori (tabella qui sopra, `session:spin_*` nelle nove operazioni GraphQL che li mandano), non sono più `pending`; finché H23 (§6.6) non ha un esito in `docs/sonda/esito.md` i loro nomi in `SiteData` sono un'ipotesi, e un altro motivo per tenere chiusa la porta; +- restano senza fonte stabilita (`pending`) valori che la pagina calcola mentre gira: `__req` (contatore delle richieste), `__s` (sessione della pagina), `__dyn`, `__csr`, `__hblp`, `__hsdp`, `__sjsp` (moduli caricati), `__crn` (percorso della pagina), `__d`, `x-web-session-id`, le intestazioni del browser (`referer`, `priority`, `sec-ch-ua…`, `x-ig-max-touch-points`) e i nomi che la sonda ha tolto. Un'operazione che ne usa uno non si può configurare (regola 9, H15), e la sua ricetta **resta al browser** (§6.3): quei valori non si inventano. + +**«Collegato», con «richieste»** (tappa S4b di #36). Quando la composizione costruisce la sessione salvata, cioè con la raccolta `richieste` **e** un catalogo con almeno un'operazione configurata, Febe si dice «Collegato» solo se c'è il cookie di sessione del browser **e** la sessione salvata si legge; altrimenti lo stato è **«Serve «Ho finito»»**: il motore aspetta con quel titolo, e la pagina Collegamento apre la pagina iniziale (non l'accesso) e spiega che serve «Ho finito». Negli altri casi (`pagine`, e Instagram anche con `richieste` finché nessuna sua operazione è configurata) «Collegato» viene dal solo cookie di sessione del browser. Quando la sessione salvata esiste, la pagina Collegamento ne mostra lo **stato** nel riquadro «Sessione salvata per le richieste»: data dell'ultima copia, valori della pagina e `doc_id` presenti su quelli letti, numero di cookie, nomi di quelli mancanti e quanti servono alle operazioni configurate, e l'opzione «Copia incompleta»; solo conteggi e nomi, **mai i valori** (regola 11). «Scollega» cancella la sessione salvata e tiene `chiave.bin` (§13.2). + +**Niente browser e client insieme nello stesso momento** (regola 4, decisione del 18 novembre 2026). In una sessione del motore con `richieste` alcune ricette possono andare per richieste e altre con il browser (§6.3: il Giro dei seguiti resta sulle pagine), ma una alla volta: ogni ricetta usa o il browser o il client, mai tutti e due, e dopo un segnale non cambia strada. Resta com'è oggi. Il sito di prova ha già tutto: un cookie `csrftoken`, un cookie limitato a `/api/` e un registro di moduli con nomi suoi (§14.2), e le prove copiano a «Ho finito» la sessione del browser di prova e la usano con il client del sito. @@ -390,7 +482,7 @@ Il sito di prova ha già tutto: un cookie `csrftoken`, un cookie limitato a `/ap | Scaricare i file | `Network.loadNetworkResource` (richiede l'identificativo del frame), `IO.read`, `IO.close` | | Vista remota e anteprima | `Page.startScreencast`, `Page.screencastFrameAck`, `Page.stopScreencast`, `Page.captureScreenshot` | | Controllare il collegamento | `Network.getCookies`, per sapere se il cookie di sessione esiste; il valore non si registra mai | -| Copiare la sessione (§6.0, decisioni del 16 e del 17 novembre 2026) | Solo con la raccolta `richieste` e un catalogo con operazioni configurate (mai con Instagram nella tappa S4), una volta a «Ho finito» (e dopo l'accesso automatico del sito di prova): `Page.getFrameTree` per sapere su che pagina si è; `Network.getCookies` con i valori per la radice del sito e per i percorsi del catalogo, direttamente nella sessione salvata; **una** `Runtime.evaluate` in sola lettura con `returnByValue`, scritta solo dagli identificatori della sezione `page` di `richieste..json`, per l'user agent, i valori della tabella di §6.0 e i `doc_id`, con un `try` per modulo | +| Copiare la sessione (§6.0, decisioni del 16, 17, 18 e 25 novembre 2026) | Solo con la raccolta `richieste` e un catalogo con operazioni configurate (mai con Instagram finché nessuna sua operazione è configurata), una volta per uso del browser, in uno di tre momenti: a «Ho finito», alla chiusura della finestra «Browser di Febe» su Windows (anche ridotta a icona troppo a lungo), o in Docker lasciando la pagina del browser o chiudendone la scheda (decisione del 25 novembre 2026), e alla fine del permesso di guida, sempre prima che la pagina torni al motore e con il permesso di guida e il turno della pagina tenuti fino alla fine della copia; solo se la pagina è sul sito (e dopo l'accesso automatico del sito di prova): `Page.getFrameTree` per sapere su che pagina si è; `Network.getCookies` con i valori per la radice del sito e per i percorsi del catalogo, direttamente nella sessione salvata; **una** `Runtime.evaluate` in sola lettura con `returnByValue`, scritta solo dagli identificatori della sezione `page` di `richieste..json`, per l'user agent, i valori della tabella di §6.0 e i `doc_id`, con un `try` per modulo | | Chiedere i dati alla pagina (storia: decisione del 12 novembre 2026, sostituita dal client del sito) | `Runtime.evaluate` con `awaitPromise`, che esegue nella pagina un `fetch` verso un indirizzo di `richieste..json` e ne restituisce il corpo | **Provato in locale**: gli eventi della rotella inviati con `Input.dispatchMouseEvent` sono eventi veri e fanno scorrere la pagina; `Page.startScreencast` consegna i fotogrammi; `Network.loadNetworkResource` con `IO.read` ha scaricato integro un file di 40 MB. @@ -459,7 +551,7 @@ La pagina mostra versioni ridotte; gli indirizzi delle versioni migliori sono ne 3. Senza browser, la via principale dal 16 novembre 2026 (§6.0, tappa S5 di #36): `HttpClient` verso i soli domini del CDN presenti nell'indirizzo ricevuto, mai verso `instagram.com`, senza seguire rinvii fuori dal CDN. Senza cookie, con l'user agent della sessione salvata. Se il CDN la rifiuta, il file resta in attesa e l'interfaccia lo dice. 4. Il file si scrive con un nome temporaneo, se ne calcola lo SHA-256 e lo si rinomina. Uno scaricamento interrotto non lascia mai un file con il nome definitivo. 5. Se l'indirizzo è scaduto, il file torna «da scaricare». Il recupero passa dalla ricetta Post singolo, che rilegge il post e ne ottiene uno nuovo, dentro il suo tetto. Per le storie non c'è recupero dopo la scadenza. -6. Coda dedicata, al massimo due scaricamenti insieme, piccole pause casuali, tetto giornaliero sui dati. Le storie hanno la precedenza, perché scadono. +6. Coda dedicata, al massimo due scaricamenti insieme, piccole pause casuali, tetto giornaliero sui dati. L'ordine della coda segue **«Cosa scaricare prima»** dell'account del file (§7.2; tappa D1 del traguardo 0.3.0): prima i file del tipo che viene primo, poi gli altri tipi nell'ordine, e dentro un tipo prima quelli che scadono prima, poi i più vecchi in attesa. Con l'ordine predefinito le storie, che scadono, vengono prima di tutto, come oggi; le foto del profilo vanno con i post. Finché D1 non è unita, le storie hanno la precedenza e il resto segue la scadenza e la data di scoperta. ### 6.6 Ipotesi da provare in M0 @@ -487,8 +579,9 @@ Finché una voce non ha un esito scritto in `docs/sonda/esito.md`, non costruirc | H18 | I cursori sono gli stessi per pagine e richieste: un punto salvato dalle pagine si riprende con una richiesta, e viceversa | | H19 | Un 404 con JSON vuol dire risorsa assente, un 5xx errore temporaneo: la ricetta non insiste e si riprova al giro dopo (da confermare, Alberto) | | H20 | Una raccolta in evidenza si chiede con l'identificativo che il profilo dà nell'elenco delle raccolte, così com'è (sul sito di prova sì; su Instagram potrebbe servire il prefisso `highlight:`) | -| H21 | Su Instagram `require()` dei moduli della sezione `page` (§6.0), chiesto dalla copia a «Ho finito», non ha effetti: non esegue la fabbrica di un modulo non ancora avviato che faccia qualcosa, e un modulo assente non fa partire dalla pagina una segnalazione d'errore verso il sito. Finché non è verificata (con Alberto), con Instagram la copia non si accende (§6.0, «raccolta») | -| H22 | Sulla pagina dove Alberto preme «Ho finito» (di solito la pagina iniziale) i moduli dei `doc_id` delle operazioni del catalogo (`_instagramRelayOperation`) e i moduli dei valori sono già caricati; se no, quali pagine li caricano. Un `doc_id` assente manca nella sessione salvata e la richiesta che lo vuole non parte | +| H21 | Su Instagram `require()` dei moduli della sezione `page` (§6.0), chiesto dalla copia a «Ho finito», non ha effetti: non esegue la fabbrica di un modulo non ancora avviato che faccia qualcosa, e un modulo assente non fa partire dalla pagina una segnalazione d'errore verso il sito. **Da verificare da Alberto** nella prova dal vivo (tappa S7 di #36; risposta del 18 novembre 2026) (§6.0, «raccolta») | +| H22 | Sulla pagina dove Alberto preme «Ho finito» (di solito la pagina iniziale) i moduli dei `doc_id` delle operazioni del catalogo (`_instagramRelayOperation`) e i moduli dei valori sono già caricati; se no, quali pagine li caricano. Un `doc_id` assente manca nella sessione salvata e la richiesta che lo vuole non parte. **Da verificare da Alberto** nella prova dal vivo (tappa S7 di #36) | +| H23 | Su Instagram `__spin_r`, `__spin_b` e `__spin_t` stanno nel documento della pagina, dentro `SiteData`, con le chiavi `SiteData.__spin_r`, `SiteData.__spin_b`, `SiteData.__spin_t` (nomi presi solo dalla forma del codice pubblico nel HAR, nessun campione ripulito li documenta); è il codice della pagina che li aggiunge alle richieste `graphql/query`, con gli stessi valori di `SiteData`, e restano uguali finché la pagina non si ricarica. **Da verificare da Alberto** nella prova dal vivo (`docs/prove-dal-vivo.md`, parte E1; tappa S7 di #36). Se i nomi sono diversi, il catalogo si corregge prima di configurare qualunque operazione (§6.0) | | S1 | In WebView2 funzionano attraverso CDP il corpo delle risposte, i gesti e i fotogrammi della pagina | | S2 | Su Windows la pagina continua a caricare e a rispondere allo scorrimento quando la finestra del browser non è in vista | | S3 | L'accesso fatto a mano sopravvive al riavvio del programma, in Docker e su Windows | @@ -514,7 +607,8 @@ Nessuno può garantire che basti. Per questo il motore ha tre livelli indipenden - **Sessioni.** Dentro la fascia l'attività è fatta di sessioni brevi separate da pause. Durata della sessione e lunghezza della pausa si estraggono ogni volta da una distribuzione log-normale tagliata sugli estremi del profilo. Mai una distribuzione uniforme, mai intervalli fissi. - **Pavimento.** La pausa minima vale sempre, anche con molto lavoro arretrato. L'arretrato si smaltisce nei giorni, non stringendo le pause. - **Avvio.** Dopo l'avvio del programma la prima sessione parte dopo un'attesa casuale fra 2 e 10 minuti. Tetti e registro delle azioni sono su disco: un riavvio non azzera nulla. Un programma che riparte più volte non deve produrre più traffico di uno che resta acceso. -- **Composizione.** Una sessione comincia di norma con il Giro dei seguiti, prosegue con le storie segnalate, poi con i controlli di profilo scaduti, infine con qualche pagina di storico. Non tutte le sessioni fanno tutto: circa una su tre si limita al giro e alle storie. L'ordine degli account è estratto a caso con pesi, mai lo stesso. +- **Composizione.** Una sessione comincia di norma con il Giro dei seguiti, prosegue con le storie segnalate, poi con i controlli di profilo scaduti, infine con qualche pagina di storico. Non tutte le sessioni fanno tutto: circa una su tre si limita al giro e alle storie. L'ordine degli account è estratto a caso con pesi, mai lo stesso. Dalla tappa D1 l'ordine delle visite dopo il giro lo pesa anche «Cosa scaricare prima» (qui sotto). +- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine dei tipi, generale (Impostazioni → Limiti e comportamento, mockup 07) e per account (§4.4: «Come le impostazioni generali», il predefinito, oppure un ordine suo), che si cambia trascinando le righe o, da tastiera, con i pulsanti «Su» e «Giù». Ordine predefinito: storie, evidenza, post, reel, taggati (Alberto ha detto storie, post, reel, taggati; le raccolte in evidenza subito dopo le storie sono una proposta, §16 domanda 19). Un tipo è quello delle ricette di §6.3: storie per Storie di un account, evidenza per Raccolta in evidenza, post per Controllo del profilo e Storico (foto del profilo comprese), reel per Reel, taggati per Taggati. Pesa in due posti, dopo il Giro dei seguiti, che resta sempre primo: sulle **visite del motore nella sessione**, perché fra il lavoro già dovuto e permesso la visita successiva si estrae con il peso dell'account moltiplicato per il peso del tipo (tabella qui sotto), così il primo tipo viene di norma prima ma non sempre; e sulla **coda dei file** (§6.5), dove i file del primo tipo passano prima. Restano come sono il Governatore e i tetti (§7.4), le pause, la fascia, le frequenze (§7.3), la composizione casuale delle sessioni (circa una su tre si limita al giro e alle storie), l'umore e l'avvio graduale: l'ordine pesa le scelte dentro ciò che è già permesso, non aggiunge visite, non le anticipa e non le rende fisse; un tipo in cima senza nulla di dovuto non si visita. Un reel è un post: in coda conta come reel se Febe sa che lo è (trovato nella scheda Reel o segnato così nella risposta), altrimenti come post. Le storie scadono in 24 ore: spostarle in basso le espone a scadere prima di essere scaricate, e l'impostazione lo dice accanto all'elenco. - **Umore della sessione.** Ogni sessione ha un fattore di velocità estratto una volta, che moltiplica tutte le attese: alcune sessioni sono svelte, altre lente. - **Riposo.** A fine sessione il browser torna alla pagina vuota (§6.1). - **Avvio graduale.** Se attivo (lo è per impostazione predefinita), nei primi giorni dopo il collegamento e dopo ogni verifica risolta i tetti partono dalla metà e risalgono in modo lineare fino al valore pieno, nel numero di giorni previsto dal profilo. @@ -527,6 +621,7 @@ Parametri delle estrazioni: | Umore della sessione | Log-normale, mediana 1, σ 0,2, tagliata fra 0,7 e 1,5 | | Scostamento del prossimo controllo | Intervallo × log-normale con mediana 1, σ 0,25, tagliata fra 0,6 e 1,8 | | Peso di un account nella scelta | (Alta 3, Normale 2, Bassa 1) × (1 + ritardo ÷ intervallo), con il rapporto limitato a 3 | +| Peso di un tipo nella scelta (tappa D1) | 16, 8, 4, 2, 1 secondo la posizione del tipo in «Cosa scaricare prima» dell'account (proposta, da tarare con la simulazione di §14.3) | | Distanza minima fra due azioni contate | 4 secondi con il ritmo «naturale» | ### 7.3 Frequenze @@ -594,7 +689,7 @@ Per il client del sito (§6.0) sono segnali anche: un rinvio (3xx) verso le pagi - Le durate dei fermi sono fisse: nella versione 1 non si modificano dall'interfaccia. - Dopo Verifica o Disconnessione riparte solo quando Alberto ha sistemato a mano nel browser e ha premuto «Riprendi». La ripresa comincia con l'avvio graduale. - Durante un fermo gli scaricamenti già in coda dal CDN si completano; verso il sito non parte nulla. -- Ogni arresto finisce nella tabella `incident` con data, livello, segnale e indirizzo, e nella cronologia della pagina Attività. +- Ogni arresto finisce nella tabella `incident` con data, livello, segnale e indirizzo, e nella cronologia della Dashboard (§7.9). - Tre rallentamenti in sette giorni: Febe propone di passare al profilo più prudente o di ridurre gli account. ### 7.7 Il ritmo dei gesti @@ -618,9 +713,18 @@ Regole: il puntatore non salta mai da un punto all'altro; non si clicca nulla ch ### 7.9 Che cosa deve vedere Alberto -La pagina Attività (mockup 06 e 11) è il cruscotto del motore: che cosa sta facendo adesso, la **striscia della giornata** con sessioni, riposo, rallentamenti e arresti, i quattro tetti principali con i numeri (profili aperti, storie viste, pagine di storico, dati scaricati) e, da «Tutti i tetti», anche gli altri; la coda con orari indicativi, le ultime azioni con l'esito. Gli orari futuri si scrivono sempre come «verso le», perché sono estratti a caso. +La **Dashboard** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026; prima si chiamava Attività, mockup 06 e 11) è il cruscotto del motore e la **pagina iniziale** di Febe: quando il motore lavora Alberto resta qui a guardare come va lo scaricamento. È la prima voce della barra laterale (§10.2), all'indirizzo `/dashboard`; `/` e il vecchio `/attivita` portano lì, la finestra di Febe per Windows si apre lì e il riquadro di stato in fondo alla barra laterale vi rimanda. È compatta, per stare in una finestra di 1440 × 900 senza scorrere nella parte alta: -**Rapporto di diagnostica.** Dopo una prova dal vivo andata storta, Alberto deve poter mandare un solo file che spieghi perché, senza che nessuno apra i dati di altre persone. «Esporta il rapporto di diagnostica» (pulsante «Diagnostica» nella riga del titolo di Attività) scarica `febe-diagnostica-aaaa-mm-gg.json`: per ogni sessione del motore delle ultime due settimane, e per ogni giorno fuori dalle sessioni, le pagine aperte (il nome della pagina nella mappa del sito e la sua forma, mai l'indirizzo), le risposte ricevute per tipo con numero e misure, che cosa ne hanno fatto i lettori (riconosciute, vuote, ignorate, forma sconosciuta con la sola struttura delle chiavi, in cui resta solo una chiave fatta di parole di un elenco chiuso, preso dai campioni ripuliti e dai vocabolari dei lettori, mai di sole parole che sono anche nomi come «max_mark», e ogni altra diventa `#`; diventano `#` anche le voci di una mappa, cioè le chiavi sorelle con valori della stessa forma, salvo quelle che i lettori conoscono come `user` e `owner`), i bersagli cliccati, le ricette con l'esito (e, per un errore imprevisto, il solo tipo dell'eccezione), i segnali di §7.6 per livello e codice, i rifiuti del Governatore, i file messi in coda e scaricati (per un file fallito o da riprovare, la causa da un elenco chiuso, come `http-404`), e la causa di ogni fine (fine prevista, lavoro finito, tetti esauriti, ricetta che ferma, interruttore aperto, pausa, Alberto al browser, chiusura di Febe, errore). Mai cookie, password, gettoni, corpi delle risposte, nomi utente, didascalie, codici dei post, identificativi, indirizzi interi o testi liberi (messaggi, note, eccezioni): solo valori di elenchi chiusi, conteggi, misure, orari e forme degli indirizzi in cui ogni parte che non è una parola fissa del sito è `{numero}` o `{testo}`; per il CDN solo «cdn» e l'estensione del file. Le tracce finite stanno in `Dati/diagnostica/sessioni-aaaa-mm-gg.jsonl`, una riga per sessione, e si tengono 14 giorni (Febe cancella da sé solo i file più vecchi di quella cartella); le sessioni in corso entrano nel rapporto come «in corso». Una sessione scrive una riga «in corso» quando parte e poi al più ogni 5 minuti alla fine di una ricetta, così una chiusura brusca di Febe non la cancella; leggendo, di una sessione resta la riga finita, altrimenti l'ultima. I segnali entrano anche quando arrivano all'interruttore senza passare dal rilevatore (il cookie di sessione perso), e i file in attesa perché manca la connessione hanno la causa `connessione`. La testa del file dice che cosa sicuramente manca: righe del registro rovinate (`righeRovinate`), errori del registratore, scritture non riuscite comprese (`erroriRegistratore`), file di un giorno che non si sono potuti leggere (`fileIlleggibili`) e sessioni rimaste senza fine per una chiusura brusca (`sessioniSenzaFine`). Anche a zero il rapporto non promette di essere intero: gli ultimi minuti di una chiusura brusca, le ore fuori dalle sessioni del giorno e quello che supera i tetti (contato in `overflow`) possono mancare. Le forme delle pagine della mappa del sito passano per la stessa riduzione degli indirizzi, perché la mappa può venire dalla cartella dei dati. Con un problema di configurazione il motore non parte: l'indirizzo del rapporto risponde lo stesso, con gli elenchi vuoti. Una prova dimostra che nessun valore dei dati arriva nel file. +- **l'anteprima del browser, sempre visibile**: la pagina che il browser di Febe sta guardando, che scorre mentre la ricetta la scorre, aggiornata da sola a ogni fotogramma nuovo (al più uno al secondo, con i comandi di §6.1 «Vista remota e anteprima»), mai nascosta dietro un clic; fuori sessione dice perché è ferma (riposo, browser spento, Alberto al browser, arresto) come oggi. Accanto, che cosa sta facendo adesso; +- la **striscia della giornata** con sessioni, riposo, rallentamenti e arresti, in una riga più bassa; +- i quattro tetti principali con i numeri (profili aperti, storie viste, pagine di storico, dati scaricati) in una riga sola e, da «Tutti i tetti», anche gli altri; +- la coda con orari indicativi, ridotta alle prime righe con «Mostra tutta»; +- la **cronologia dell'attività**, le ultime azioni con l'esito; le righe che hanno salvato qualcosa (post, storie, contenuti in evidenza, taggati, reel, foto del profilo) mostrano le **miniature** di ciò che è arrivato, piccole (le miniature di §8.4, caricate solo quando la riga è in vista, al più otto per riga con «+12» per il resto). Un clic su una miniatura apre un'**anteprima ingrandita** leggera, sopra la pagina e senza lasciarla: la foto o il video (che parte senza audio), account, tipo, data, frecce fra i file di quella riga, Esc che chiude; per il resto «Apri nella Libreria» (il visualizzatore di §4.6 su quell'elemento) e «Apri l'account» (la sua scheda). Un file danneggiato o incompleto mostra la tessera neutra (§4.6); +- il pulsante «Diagnostica» nella riga del titolo (qui sotto) e, dalla tappa E2, la scheda «Esportazione» (§4.10). + +Si aggiorna da sola con gli eventi del server, e con una cronologia lunga resta leggera: si caricano le ultime righe e le altre a richiesta. Gli orari futuri si scrivono sempre come «verso le», perché sono estratti a caso. Finché la tappa D1 non è unita la pagina resta «Attività» com'è oggi. + +**Rapporto di diagnostica.** Dopo una prova dal vivo andata storta, Alberto deve poter mandare un solo file che spieghi perché, senza che nessuno apra i dati di altre persone. «Esporta il rapporto di diagnostica» (pulsante «Diagnostica» nella riga del titolo della Dashboard) scarica `febe-diagnostica-aaaa-mm-gg.json`: per ogni sessione del motore delle ultime due settimane, e per ogni giorno fuori dalle sessioni, le pagine aperte (il nome della pagina nella mappa del sito e la sua forma, mai l'indirizzo), le risposte ricevute per tipo con numero e misure, che cosa ne hanno fatto i lettori (riconosciute, vuote, ignorate, forma sconosciuta con la sola struttura delle chiavi, in cui resta solo una chiave fatta di parole di un elenco chiuso, preso dai campioni ripuliti e dai vocabolari dei lettori, mai di sole parole che sono anche nomi come «max_mark», e ogni altra diventa `#`; diventano `#` anche le voci di una mappa, cioè le chiavi sorelle con valori della stessa forma, salvo quelle che i lettori conoscono come `user` e `owner`), i bersagli cliccati, le ricette con l'esito (e, per un errore imprevisto, il solo tipo dell'eccezione), i segnali di §7.6 per livello e codice, i rifiuti del Governatore, i file messi in coda e scaricati (per un file fallito o da riprovare, la causa da un elenco chiuso, come `http-404`), e la causa di ogni fine (fine prevista, lavoro finito, tetti esauriti, ricetta che ferma, interruttore aperto, pausa, Alberto al browser, chiusura di Febe, errore). Mai cookie, password, gettoni, corpi delle risposte, nomi utente, didascalie, codici dei post, identificativi, indirizzi interi o testi liberi (messaggi, note, eccezioni): solo valori di elenchi chiusi, conteggi, misure, orari e forme degli indirizzi in cui ogni parte che non è una parola fissa del sito è `{numero}` o `{testo}`; per il CDN solo «cdn» e l'estensione del file. Le tracce finite stanno in `Dati/diagnostica/sessioni-aaaa-mm-gg.jsonl`, una riga per sessione, e si tengono 14 giorni (Febe cancella da sé solo i file più vecchi di quella cartella); le sessioni in corso entrano nel rapporto come «in corso». Una sessione scrive una riga «in corso» quando parte e poi al più ogni 5 minuti alla fine di una ricetta, così una chiusura brusca di Febe non la cancella; leggendo, di una sessione resta la riga finita, altrimenti l'ultima. I segnali entrano anche quando arrivano all'interruttore senza passare dal rilevatore (il cookie di sessione perso), e i file in attesa perché manca la connessione hanno la causa `connessione`. La testa del file dice che cosa sicuramente manca: righe del registro rovinate (`righeRovinate`), errori del registratore, scritture non riuscite comprese (`erroriRegistratore`), file di un giorno che non si sono potuti leggere (`fileIlleggibili`) e sessioni rimaste senza fine per una chiusura brusca (`sessioniSenzaFine`). Anche a zero il rapporto non promette di essere intero: gli ultimi minuti di una chiusura brusca, le ore fuori dalle sessioni del giorno e quello che supera i tetti (contato in `overflow`) possono mancare. Le forme delle pagine della mappa del sito passano per la stessa riduzione degli indirizzi, perché la mappa può venire dalla cartella dei dati. Con un problema di configurazione il motore non parte: l'indirizzo del rapporto risponde lo stesso, con gli elenchi vuoti. Una prova dimostra che nessun valore dei dati arriva nel file. --- @@ -664,8 +768,8 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc | Tabella | Contenuto | |---|---| | `setting` | Chiave e valore | -| `account` | Identificativo Instagram, nome utente, nome visibile, privato, seguito, è il mio, stato, tieni aggiornato, frequenza, tipi da scaricare, limiti, cartella, punto di ripresa dello storico, ultimi e prossimi controlli | -| `entry` | Un elemento: account, tipo (§4.3), identificativo e codice Instagram, data di pubblicazione in UTC, didascalia, autore (per i taggati), stato, provenienza, date di scoperta e di scaricamento | +| `account` | Identificativo Instagram, nome utente, nome visibile, privato, seguito, è il mio, stato, tieni aggiornato, frequenza, tipi da scaricare, limiti, cartella, punto di ripresa dello storico, ultimi e prossimi controlli; dalla tappa D1 l'ordine di «Cosa scaricare prima» (vuoto: come le impostazioni generali, chiave `scaricamento.ordine` in `setting`) | +| `entry` | Un elemento: account, tipo (§4.3), identificativo e codice Instagram, data di pubblicazione in UTC, didascalia, autore (per i taggati), stato, provenienza, date di scoperta e di scaricamento; dalla tappa D1 se un post è un reel, quando Febe lo sa (§7.2) | | `media` | Un file di un elemento: posizione, foto o video, dimensioni, durata, stato, percorso relativo, byte, SHA-256, impronta visiva, tentativi, ultimo errore | | `highlight`, `highlight_entry` | Raccolte in evidenza di un account e loro contenuti, in ordine. Un elemento può stare in più raccolte | | `duplicate_pair` | Coppie di file «doppione probabile» in attesa della decisione di Alberto, da importazione o da scaricamento | @@ -676,6 +780,7 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc | `event` | Cronologia leggibile per l'interfaccia | | `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura | | `import_run`, `import_file` | Importazioni e loro file, con esito e decisione | +| `export_destination`, `export_copy`, `export_run`, `export_item`, `video_analysis` | **Previste**, migrazione `0002` (tappa E1 del traguardo 0.3.0, §4.10): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito; rimuovere un account la disattiva, non la cancella), copie fatte per file, destinazione e account effettivo con il loro stato (§4.10), lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere), esito dell'analisi dei video fermi per SHA-256. Impostazioni in `setting` con chiavi `esportazione.*`; nessuna colonna nuova in `account` | Vincoli che contano: @@ -686,9 +791,10 @@ Vincoli che contano: ### 8.4 Miniature e impronte -- Miniatura di 480 pixel sul lato lungo per ogni immagine; per i video si usa la copertina che arriva dalla pagina e, per quelli importati, un fotogramma estratto con ffmpeg se presente, altrimenti una tessera neutra. +- Miniatura di 480 pixel sul lato lungo per ogni immagine; per i video si usa la copertina che arriva dalla pagina e, per quelli importati, un fotogramma estratto con i decodificatori H.264 e H.265 di Febe (§3), altrimenti (VP9, AV1 e gli altri codec) una tessera neutra. Fino alla tappa C3 del traguardo 0.3.0 il fotogramma lo estrae ffmpeg, se presente; fra C3 e C4 un video HEVC ha la tessera neutra. - SHA-256 del file per i doppioni esatti. - Impronta visiva a 64 bit per le immagini, per riconoscere la stessa foto salvata a risoluzione o compressione diversa. Le impronte stanno in memoria: il confronto di una foto con 200.000 è questione di millisecondi. +- **Immagini troncate o rovinate** (PNG, JPEG e gli altri formati di §3; risposta di Alberto del 25 novembre 2026): si rifiutano e lo si dice, «File danneggiato o incompleto». Niente miniatura (la tessera neutra) e **nessuna impronta visiva**: un file così non risulta mai doppione probabile per impronta, né dallo scaricamento né dall'importazione (§9.3). Lo SHA-256 sì, perché dice solo se due file sono identici. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. ### 8.5 Copie e ricostruzione @@ -713,7 +819,7 @@ Quattro passi, mostrati in alto nella pagina (mockup 09): ### 9.2 Analisi -Per ogni file: tipo dal contenuto e non solo dall'estensione; byte; SHA-256; dimensioni; impronta visiva per le immagini; data, cercata nell'ordine nel nome del file, nei metadati del file (data di scatto delle foto, data di creazione dei video), nella data di modifica; identificativo o codice Instagram, se il nome lo contiene; account probabile, dal nome della cartella; tipo probabile (storia, evidenza, taggato) dalle sottocartelle. La lettura dei metadati si scrive a mano per i pochi campi che servono, oppure si usa ffprobe dove è presente. +Per ogni file: tipo dal contenuto e non solo dall'estensione; byte; SHA-256; dimensioni; impronta visiva per le immagini che si decodificano per intero (non per quelle troncate o rovinate, §8.4); data, cercata nell'ordine nel nome del file, nei metadati del file (data di scatto delle foto, data di creazione dei video), nella data di modifica; identificativo o codice Instagram, se il nome lo contiene; account probabile, dal nome della cartella; tipo probabile (storia, evidenza, taggato) dalle sottocartelle. La lettura dei metadati si scrive a mano per i pochi campi che servono: per i video con i lettori dei contenitori di Febe (§3: ISO BMFF, Matroska e, dalla tappa C5, ASF/WMV, FLV e MPEG-PS); fino alla tappa C2 del traguardo 0.3.0 si usa ancora ffprobe dove è presente, e fra C2 e C5 un file ASF, FLV o MPEG-PS ha il tipo dal contenuto ma durata, dimensioni e codec vuoti. ### 9.3 Confronto con la libreria @@ -724,7 +830,7 @@ Per ogni file: tipo dal contenuto e non solo dall'estensione; byte; SHA-256; dim | **Nuovo** | Nessuna corrispondenza | Verrà copiato | | **Non riconosciuto** | Né foto né video | Ignorato ed elencato | -I doppioni si cercano anche dentro la sorgente stessa. Le soglie dell'impronta si tarano con le prove di §14.1 su varianti costruite apposta: ridimensionata e ricompressa deve risultare doppione, ritagliata no. Per i video vale solo lo SHA-256. «Tenere il più grande», quando il più grande è quello importato, sostituisce un file della libreria: è una scelta esplicita di Alberto, come chiede la regola 12. +I doppioni si cercano anche dentro la sorgente stessa. Un'immagine troncata o rovinata (§8.4) ha il tipo dal contenuto e lo SHA-256, ma nessuna impronta: può essere «Già in libreria» o «Nuovo», mai «Doppione probabile» per impronta; si importa come le altre e revisione e resoconto la segnano «File danneggiato o incompleto». Le soglie dell'impronta si tarano con le prove di §14.1 su varianti costruite apposta: ridimensionata e ricompressa deve risultare doppione, ritagliata no. Per i video vale solo lo SHA-256. «Tenere il più grande», quando il più grande è quello importato, sostituisce un file della libreria: è una scelta esplicita di Alberto, come chiede la regola 12. ### 9.4 Associazione e copia @@ -757,7 +863,7 @@ Semplice e moderna, con una ragione dietro ogni scelta: - **Le foto portano il colore, l'interfaccia resta in grigio neutro.** Come nei programmi di fotoritocco, i grigi non hanno dominante, così i colori delle immagini non vengono falsati. Niente sfumature decorative, niente richiami alla grafica di Instagram. - **Un solo accento**, un blu cianotipo, per l'azione principale, la selezione e le sessioni del motore. Verde, ambra e rosso servono solo a dire uno stato, sempre accompagnati da testo o numero. -- **Un solo carattere**, Archivo, in due larghezze: normale per l'interfaccia, più stretta con cifre tabellari per i dati (date, numeri, nomi di file). +- **Un solo carattere**, quello di sistema (`system-ui`, regola 13: dalla tappa C6 della 0.3.0; fino ad allora Archivo), con cifre tabellari per i dati (date, numeri, nomi di file). La larghezza più stretta dei dati c'era con Archivo; con i caratteri di sistema si ottiene solo dove il carattere la offre, e i mockup si confrontano tenendone conto (§10.7). - **Raggi che crescono con l'importanza**: 3 per le tessere, 7 per i controlli, 10 per i pannelli, 14 per le finestre di dialogo. Ombre solo su menu e dialoghi; il resto si separa con linee sottili. - **Elenchi e tabelle, non mosaici di riquadri uguali.** Un pannello si usa quando raggruppa davvero qualcosa. - **La striscia della giornata** è l'elemento che distingue Febe: una barra di 24 ore con le sessioni come tratti irregolari. Il resto le sta intorno in silenzio. @@ -766,7 +872,7 @@ Token di colore, misure e CSS di partenza sono nell'appendice B e nel mockup 13. ### 10.2 Ossatura -Barra laterale fissa di 228 pixel: marchio, quattro voci (Libreria, Account, Attività, Importa), separatore, Impostazioni. In fondo il riquadro di stato, sempre visibile: stato del motore, una riga su che cosa sta facendo o quando riprende, misuratore dei profili aperti oggi, account collegato. A destra la pagina: titolo, eventuale riga di strumenti, contenuto che scorre. Le azioni che salvano stanno in una barra fissa in basso. +Barra laterale fissa di 228 pixel: marchio, quattro voci (Dashboard, Libreria, Account, Importa), separatore, Impostazioni. La Dashboard (§7.9) è la prima voce e la pagina iniziale (decisione di Alberto del 25 novembre 2026, tappa D1 del traguardo 0.3.0; prima: Libreria, Account, Attività, Importa, con la Libreria come pagina iniziale). In fondo il riquadro di stato, sempre visibile: stato del motore, una riga su che cosa sta facendo o quando riprende, misuratore dei profili aperti oggi, account collegato. A destra la pagina: titolo, eventuale riga di strumenti, contenuto che scorre. Le azioni che salvano stanno in una barra fissa in basso. ### 10.3 Schermate @@ -780,22 +886,32 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f | `03-account.png` | Account | Le cinque icone di «Raccoglie» sono nell'ordine: foto, video, storie, evidenza, taggati; spente se non attive. L'interruttore agisce subito. Un clic sulla riga apre la scheda | | `04-aggiungi-account.png` | Aggiungi account | I tre punti di partenza sono quelli di §4.2. **Superato da #37**: niente linguette, una sola casella con l'elenco dei suggerimenti sotto (profili seguiti, poi Instagram, con foto ed etichette), «Da aggiungere» al posto dell'elenco a spunte, che si apre con «Scegli fra tutti i profili che segui». I profili già presenti sono attenuati. Durante la lettura dell'elenco compare l'avanzamento di §4.2. Finché non c'è un mockup nuovo, il riferimento è la schermata `docs/schermate/04-aggiungi-account.png` | | `05-account-impostazioni.png` | Scheda account, impostazioni | Il riquadro a destra si ricalcola a ogni modifica. «Controlla ora» segue §7.8. Con «Su misura» compaiono i due campi di §4.4 | -| `06-attivita.png` | Attività | Si aggiorna da sola con gli eventi del server. L'anteprima del browser è un fotogramma ogni pochi secondi, non un video. «Tutti i tetti» apre l'elenco completo di §7.4 | +| `06-attivita.png` | Attività, dalla tappa D1 Dashboard | Si aggiorna da sola con gli eventi del server. L'anteprima del browser è fatta di fotogrammi, non è un video; con la Dashboard è sempre visibile e si aggiorna a ogni fotogramma nuovo (§7.9). «Tutti i tetti» apre l'elenco completo di §7.4. **Superato dalla Dashboard** (qui sotto, «Schermate senza mockup») | | `07-limiti-e-comportamento.png` | Impostazioni, limiti | Modificare un valore cambia il profilo in «Su misura». I cerchi con le iniziali sono i giorni attivi. Nel programma la tabella dei tetti ha anche le righe Home, Post singoli ed Elenco dei seguiti di §7.5, e «Ricerche di profili» (#37). La riga degli arresti è informativa: non si modifica | | `08-impostazioni-generali.png` | Impostazioni, generali | In Docker le due cartelle sono in sola lettura, con la nota che si cambiano dal contenitore. Il blocco «Avvio» esiste solo su Windows | | `09-importa-revisione.png` | Importa, passo 3 | I passi 1, 2 e 4 usano la stessa intestazione: scelta della cartella, barra di avanzamento con possibilità di interrompere, resoconto finale. Nel confronto dei doppioni nessuna scelta è già fatta in partenza: l'immagine mostra una decisione presa da Alberto. «Sposta» non compare se la sorgente è in sola lettura | | `10-collegamento-instagram.png` | Collegamento, versione Docker | Il riquadro grande è la vista remota del browser del server. Il rettangolo tratteggiato dell'immagine è un segnaposto: la pagina di Instagram non si ridisegna. Versione Windows qui sotto | -| `11-attivita-fermo-tema-scuro.png` | Attività durante un arresto, tema scuro | La striscia rossa compare in cima a tutte le pagine, non solo qui. «Riprendi» si attiva dopo che Alberto ha usato il browser | +| `11-attivita-fermo-tema-scuro.png` | Attività (dalla tappa D1 Dashboard) durante un arresto, tema scuro | La striscia rossa compare in cima a tutte le pagine, non solo qui. «Riprendi» si attiva dopo che Alberto ha usato il browser | | `12-account-storie-tema-scuro.png` | Scheda account, storie, tema scuro | Griglia regolare con proporzione 9:16. Post, In evidenza e Taggati usano il mosaico della Libreria; le raccolte in evidenza sono intestazioni di gruppo | | `13-foglio-di-stile.png` | Colori, caratteri, misure, componenti | È il riferimento per qualunque elemento non disegnato altrove. Non è una schermata del programma | | `14-finestra-stretta-e-telefono.png` | Finestra stretta su Windows, telefono nel browser | Sotto i 1000 px la barra laterale si riduce alle icone; sotto i 560 px una colonna e navigazione in basso | **Collegamento su Windows.** La pagina è la stessa del mockup 10, ma il browser è la finestra «Browser di Febe». Nel riquadro grande compare la frase «Il browser di Febe è aperto in un'altra finestra» con il pulsante «Portalo in primo piano». Il testo accanto dice: «La password va solo a Instagram. La scrivi direttamente nella sua pagina: Febe non la riceve e non la salva. Resta solo la sessione del browser, nella cartella dei dati.» -**«Apri il browser»**, da Attività e dalla striscia rossa: su Windows porta in primo piano la finestra del browser; in Docker apre la pagina «Browser», che è il mockup 10 senza la colonna dei passi, con la vista remota e il pulsante «Ho finito». Finché Alberto usa il browser il motore resta fermo. +**«Apri il browser»**, dalla Dashboard e dalla striscia rossa: su Windows porta in primo piano la finestra del browser; in Docker apre la pagina «Browser», che è il mockup 10 senza la colonna dei passi, con la vista remota e il pulsante «Ho finito». Finché Alberto usa il browser il motore resta fermo. In Docker lasciare quella pagina o la vista remota di Collegamento, o chiuderne la scheda, mentre Alberto guida copia la sessione e restituisce la pagina al motore, come chiudere la finestra su Windows (§6.0, «Quando si copia»). Schermate senza mockup, da comporre con gli elementi del foglio di stile: Scheda account → Cronologia (elenco dei controlli con esito); Impostazioni → Notifiche, Dati e copie di sicurezza, Informazioni; revisione dei doppioni dopo uno scaricamento (lo stesso confronto del mockup 09); primo avvio (la schermata vuota del mockup 13 con i due pulsanti); pagina di errore di configurazione (§8.2, §11). +Schermate dell'esportazione (§4.10, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 18 novembre 2026): Impostazioni → Esportazione (cartella generale, formati predefiniti delle copie, conversione della libreria, «Una copia per account» o «Una copia sola», nota su `/esporta` in Docker; dai mockup 08 e 07); finestra della destinazione (cartella, tipi, formati, schema con anteprima, «Automatica» con la domanda «Solo i nuovi»; dal mockup 08 e dai dialoghi del 13); blocco «Copie esterne» nella scheda account → Impostazioni, sotto «Cartella» (mockup 05); finestra «Copia in…» con il riepilogo («312 file · 41 già copiati, saltati · 3 HEIC copiati come sono · circa 4,2 GB», con «con perdita» quando serve) e finestra «Fotogrammi…» (dialoghi del 13 e mockup 09); in Libreria e nella scheda account il menu dell'icona CSV («Esporta l'elenco (CSV)», «Copia i file in…»), «Copia in…» e «Fotogrammi…» nella barra della selezione, il filtro «Copie» e il segno sulla tessera (mockup 01 e 12); nel visualizzatore «Copia in…», «Fotogramma», «È un video fermo?» e le righe delle copie nel pannello File (mockup 02); scheda «Esportazione» nella Dashboard con avanzamento, Interrompi, Riprendi e resoconto (mockup 06 e passo 2 del 09). Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`. + +Schermate della tappa D1 (issue #59, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 25 novembre 2026): + +- **Dashboard** (§7.9), dai mockup 06 e 11 per anteprima, striscia, tetti, coda e cronologia, e dal mockup 01 per le miniature della cronologia (tessere piccole, raggio 3, i segni del mosaico: durata dei video, anello tratteggiato delle storie). La riga del titolo dice «Dashboard» con «Diagnostica» e i comandi del motore; sotto, in alto l'anteprima del browser con accanto che cosa sta facendo adesso e i quattro tetti, poi la striscia della giornata più bassa, poi in due colonne la cronologia con le miniature (la più larga) e la coda. L'anteprima ingrandita della cronologia è un dialogo leggero (mockup 13: raggio 14, ombra, Esc chiude), non il visualizzatore del mockup 02. Sotto i 1000 px una colonna sola, con l'anteprima sopra (mockup 14); +- **«Raggruppa i post» / «Tutte le foto»** (§4.6), dal mockup 01: un controllo a due voci nella riga di strumenti, accanto al cursore della grandezza delle tessere, nella Libreria e nella vista dei contenuti della scheda account (mockup 12); nel modo «Tutte le foto» il segno in alto a destra della tessera di una serie dice la posizione («2/4»); +- **«Cosa scaricare prima»** (§7.2), un blocco di Impostazioni → Limiti e comportamento (mockup 07) con l'elenco dei tipi da trascinare (maniglia, «Su» e «Giù» per la tastiera, la nota sulle storie che scadono) e lo stesso blocco nella scheda account → Impostazioni, sotto «Cosa scaricare» (mockup 05), con «Come le impostazioni generali» o «Un ordine suo». + +Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`, come per l'esportazione. + ### 10.4 Testi - Frasi in italiano corrente, iniziale maiuscola solo alla prima parola. Niente etichette in tutto maiuscolo. @@ -826,7 +942,7 @@ Avvia con `--demo`, fai uno screenshot nelle condizioni della tabella e confront | 01, 02, 03, 08 | 1440 × 900 | chiaro, normale | | 04 | 1440 × 900 | chiaro, dialogo aperto con «gaia» scritto e l'elenco dei suggerimenti aperto | | 05 | 1440 × 1000 | chiaro, normale | -| 06 | 1440 × 900 | chiaro, sessione | +| 06 (dalla tappa D1 la Dashboard, confrontata come composizione) | 1440 × 900 | chiaro, sessione | | 07 | 1440 × 1470 | chiaro, normale | | 09 | 1440 × 900 | chiaro, passo 3 | | 10 | 1440 × 900 | chiaro, scollegato | @@ -848,7 +964,7 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I ## 11. Docker e Unraid -- **Immagine.** Base Debian stabile in versione ridotta. Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona. Febe si pubblica autosufficiente per `linux-x64`, quindi nell'immagine non serve il runtime .NET. Pacchetti: `chromium`, `chromium-l10n` (le lingue del browser sono a parte), `xvfb`, `ffmpeg`, la libreria ICU, caratteri di sistema compresi quelli per le emoji, certificati, `tzdata`, `locales` con la lingua italiana generata. +- **Immagine.** Base Debian stabile in versione ridotta. Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona. Febe si pubblica autosufficiente per `linux-x64`, quindi nell'immagine non serve il runtime .NET. Pacchetti (regola 13: solo Chromium, ciò che gli serve e Xvfb, più ciò che la piattaforma .NET chiede al sistema): `chromium`, `chromium-l10n` (le lingue del browser sono a parte), `xvfb`, i caratteri per il browser, cioè `fonts-noto-color-emoji`, che **resta** perché a Chromium serve per mostrare le pagine, e `fonts-dejavu-core` come carattere di base (`fonts-liberation` **esce**: risposta di Alberto del 25 novembre 2026), `tzdata` e `locales` con la lingua italiana generata (fuso e lingua veri del browser, §6.1), la libreria ICU e i certificati (per .NET); `ffmpeg` solo fino alla tappa C3 del traguardo 0.3.0, poi esce dall'immagine. Nient'altro. - **Processi.** `Febe.Server` è il processo principale: avvia Xvfb, poi Chromium, e li riavvia se cadono. Niente script di shell che facciano da supervisore. - **Utente.** Non root, con `PUID` e `PGID` configurabili (su Unraid 99 e 100). - **Avvio di Chromium.** Come un browser normale, con finestra, sul display virtuale, con: porta di debug fissa su `127.0.0.1` (§6.1), cartella del profilo, nessuna procedura di primo avvio, dimensione della finestra, archivio delle password di base, uso di `/tmp` al posto della memoria condivisa. La lingua viene da `LANG`. Mai `--headless`, `--enable-automation`, opzioni che cambiano lo user agent o che intervengono su ciò che il browser dichiara. @@ -861,6 +977,7 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I | `/dati` | Database, profilo del browser, miniature, copie. Su un disco locale del server | | `/libreria` | Foto e video | | `/importa` | Sorgenti da importare, in sola lettura | +| `/esporta` | Facoltativo, dal traguardo 0.3.0: le destinazioni delle copie esterne (§4.10), come sue sottocartelle. Attivo solo se dichiarato con `--esporta` o `FEBE_ESPORTA` e montato davvero; nel Dockerfile **nessuna** riga `VOLUME` per `/esporta` | | Variabile | Significato | Predefinito | |---|---|---| @@ -870,24 +987,26 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I | `LANG` | Lingua del contenitore e del browser | it_IT.UTF-8 | | `PUID`, `PGID` | Utente e gruppo dei file | 99, 100 | | `FEBE_RACCOLTA` | Opzione «raccolta» di §6.0: `pagine` o `richieste` (`--raccolta` sulla riga di comando vince) | `pagine` | +| `FEBE_ESPORTA` | Dal traguardo 0.3.0: attiva le copie esterne in `/esporta` (§4.10); `--esporta` sulla riga di comando vale lo stesso | spenta | | `FEBE_CHIAVE_SESSIONE` | Chiave AES-256 della sessione salvata (§13.2), 32 byte in base64; facoltativa, serve a tenerla fuori da `/dati` | `Dati/sessione/chiave.bin` | - Se `FEBE_PASSWORD` manca, o `/dati` non è scrivibile o è una condivisione di rete, il motore non parte e l'interfaccia mostra una sola pagina che spiega che cosa non va e come rimediare. Vale dal primo contenitore che costruisci, compreso quello di prova di M0: la vista remota non deve mai essere raggiungibile senza password. - **Accesso a Instagram.** Solo dalla pagina Collegamento, con la vista remota: i fotogrammi del browser arrivano all'interfaccia e i gesti di Alberto tornano al browser. Ciò che scrive, password compresa, attraversa la rete di casa e la memoria del server senza essere registrato: la pagina lo dice (mockup 10). Per questo l'interfaccia non va mai esposta su Internet senza una VPN o un proxy con HTTPS: scrivilo nella guida. -- **Consegna.** `docker/Dockerfile`, `docker/compose.yml` di esempio, modello per Unraid `docker/unraid/febe.xml` con icona, punto di controllo `/salute`. +- **Consegna.** `docker/Dockerfile`, `docker/compose.yml` di esempio, modello per Unraid `docker/unraid/febe.xml` con icona, punto di controllo `/salute`. Con il traguardo 0.3.0 `compose.yml`, `febe.xml` e `docs/docker.md` mostrano `/esporta` come montaggio facoltativo, commentato. --- ## 12. Windows - Applicazione WPF su .NET 10, una sola istanza alla volta, icona nell'area di notifica. -- La finestra principale è un WebView2 che mostra l'interfaccia servita in locale su `127.0.0.1`, porta scelta all'avvio. -- Il browser di Instagram è un secondo WebView2, con una sua cartella dati, in una finestra separata «Browser di Febe». Alberto la apre da Collegamento e da Attività; quando non serve resta fuori vista ma attiva (S2). Salvataggio delle password e compilazione automatica sono disattivati nelle impostazioni del controllo. -- Funzioni native offerte all'interfaccia: scelta di una cartella, «Mostra nella cartella», apertura di un indirizzo nel browser predefinito, notifiche di Windows, avvio con il sistema. +- La finestra principale è un WebView2 che mostra l'interfaccia servita in locale su `127.0.0.1`, porta scelta all'avvio, e si apre sulla Dashboard (§7.9, dalla tappa D1). +- Il browser di Instagram è un secondo WebView2, con una sua cartella dati, in una finestra separata «Browser di Febe». Alberto la apre da Collegamento e dalla Dashboard; quando non serve resta fuori vista ma attiva (S2). Salvataggio delle password e compilazione automatica sono disattivati nelle impostazioni del controllo. +- Funzioni native offerte all'interfaccia: scelta di una cartella (anche per le destinazioni di esportazione di §4.10, con percorsi di rete e UNC), «Mostra nella cartella», apertura di un indirizzo nel browser predefinito, notifiche di Windows, avvio con il sistema. +- **Niente ffmpeg** (regola 13): fotogrammi, conversioni, miniature dei video importati e video fermi li fa il codice di Febe (§3), e non c'è nulla da installare a parte né un «Percorso di ffmpeg» da impostare. Fino alla tappa C3 del traguardo 0.3.0 un ffmpeg nel PATH serve ancora alle miniature dei video importati; senza, una tessera neutra. - Chiudendo la finestra Febe resta nell'area di notifica e continua a lavorare; dal menu dell'icona: apri, metti in pausa, esci. - Cartelle predefinite: dati in `%LOCALAPPDATA%\Febe`, libreria in `Immagini\Febe`. - **Verificato**: il runtime WebView2 è già presente in Windows 11 e in quasi tutti i Windows 10. Se manca, Febe lo dice con il collegamento per installarlo. -- Pubblicazione autosufficiente in un unico eseguibile; programma di installazione secondo la domanda 6 di §16. +- Pubblicazione autosufficiente in un unico eseguibile; programma di installazione (domanda 6 di §16) scritto in casa dalla tappa C6 della 0.3.0 (§3, regola 13); fino ad allora lo costruisce NSIS nella sola CI. --- @@ -900,17 +1019,18 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I ### 13.2 Dati riservati -- La sessione di Instagram vive nel profilo del browser dentro la cartella dei dati e, dal 16 novembre 2026 (§6.0), nella sessione salvata `Dati/sessione/sessione.json`: cookie, user agent, gettoni e `doc_id`. Esiste solo con la raccolta `richieste` e un catalogo con operazioni configurate (§6.0); con Instagram, nella tappa S4, non si crea. Il file è cifrato e porta un'intestazione `FEBS` con versione e schema: +- La sessione di Instagram vive nel profilo del browser dentro la cartella dei dati e, dal 16 novembre 2026 (§6.0), nella sessione salvata `Dati/sessione/sessione.json`: cookie, user agent, gettoni e `doc_id`. Esiste solo con la raccolta `richieste` e un catalogo con operazioni configurate (§6.0); con Instagram non si crea finché nessuna sua operazione è configurata. Non ha un limite fisso di età. La pagina Collegamento ne mostra solo la data della copia, i conteggi (valori della pagina e `doc_id` presenti, cookie) e i nomi di quelli che mancano, mai un valore (regola 11; tappa S4b di #36). Con l'opzione «Tieni la copia completa di prima» (`sessione.copia-incompleta`, §6.0) una copia incompleta non sostituisce una completa; con «Sostituisci comunque», il predefinito, sì. Il file è cifrato e porta un'intestazione `FEBS` con versione e schema: - su Windows con DPAPI dell'utente corrente (`ProtectedData`, nella libreria del desktop di .NET, nessun pacchetto nuovo): solo quell'utente di Windows, su quel computer, lo apre; non c'è file della chiave; - in Docker con AES-256-GCM, un nonce nuovo a ogni scrittura e l'intestazione come dati associati, e una chiave a 256 bit presa dalla variabile `FEBE_CHIAVE_SESSIONE` (32 byte in base64, per esempio `openssl rand -base64 32`, o 64 cifre esadecimali) o, se manca, dal file `Dati/sessione/chiave.bin`, creato una volta con `RandomNumberGenerator` e mai rigenerato. Una `FEBE_CHIAVE_SESSIONE` sbagliata è sempre un problema di configurazione all'avvio (motore e browser non partono, la pagina d'errore lo spiega senza ripetere il valore); un `chiave.bin` che non è una chiave lo è solo con `richieste`. Con la variabile impostata un `chiave.bin` rimasto non si usa e il registro lo dice. Su Unix la cartella `Dati/sessione` è 0700 e i suoi file 0600 dalla creazione (`File.SetUnixFileMode`); un `chiave.bin` più aperto si restringe e il registro lo dice. Si scrive in modo atomico: un file `.part` nella stessa cartella, scritto fino al disco, poi rinominato sul vecchio. Sostituire, aggiornare e cancellare passano da un solo semaforo; un aggiornamento ricontrolla sessione e copia dopo averlo preso, così una risposta tardiva non riporta in vita una sessione cancellata né tocca quella di un accesso nuovo. Una scrittura che il disco rifiuta tiene i valori nuovi in memoria (il sito ha già cambiato i cookie), scrive nel registro una riga con il solo tipo d'errore e si riprova alla scrittura dopo. Un file che non si legge (altra chiave o altro utente, rovinato, altro formato) è nessuna sessione, detto nel registro e lasciato com'è finché una copia nuova non lo sostituisce: mai un arresto del programma. - Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia; Febe non lo esporta e non accetta sessioni incollate da fuori. **«Scollega»** cancella la sessione salvata prima del profilo del browser: prima in memoria, poi il file (e i `.part` rimasti), senza annullamento; con `pagine` cancella comunque un `sessione.json` lasciato da un avvio con `richieste`. `chiave.bin` resta. Un file che non si cancella è un fallimento parziale detto ad Alberto: Febe non lo usa più finché resta acceso, ma al prossimo avvio con `richieste` lo rileggerebbe, quindi il messaggio chiede di riprovare «Scollega» o di cancellare a mano la cartella `sessione` prima di riavviare. Chi ha accesso alla cartella dei dati e alla chiave (in Docker), o all'utente di Windows, ha accesso alla sessione. -- `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` si tolgono dall'ambiente di ogni processo che Febe avvia (Chromium o Edge, Xvfb, ffmpeg, ffprobe): un figlio eredita l'ambiente del padre, e Chromium esegue il codice del sito. La password e la chiave non si passano mai sulla riga di comando e non compaiono in nessun testo di Febe (registri, problemi, descrizione delle opzioni: solo «impostata», «assente» o «non valida»). + Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia, dove la pagina Collegamento ne mostra solo data della copia, conteggi e nomi mancanti; Febe non lo esporta e non accetta sessioni incollate da fuori. **«Scollega»** cancella la sessione salvata prima del profilo del browser: prima in memoria, poi il file (e i `.part` rimasti), senza annullamento; con `pagine` cancella comunque un `sessione.json` lasciato da un avvio con `richieste`. `chiave.bin` resta. Un file che non si cancella è un fallimento parziale detto ad Alberto: Febe non lo usa più finché resta acceso, ma al prossimo avvio con `richieste` lo rileggerebbe, quindi il messaggio chiede di riprovare «Scollega» o di cancellare a mano la cartella `sessione` prima di riavviare. Chi ha accesso alla cartella dei dati e alla chiave (in Docker), o all'utente di Windows, ha accesso alla sessione. +- `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` si tolgono dall'ambiente di ogni processo che Febe avvia (Chromium o Edge, Xvfb e, finché ci sono, ffmpeg e ffprobe): un figlio eredita l'ambiente del padre, e Chromium esegue il codice del sito. La password e la chiave non si passano mai sulla riga di comando e non compaiono in nessun testo di Febe (registri, problemi, descrizione delle opzioni: solo «impostata», «assente» o «non valida»). - Password e codici non entrano mai nei registri. Nella vista remota i tasti vanno al browser e non si conservano. - I registri contengono azioni ed esiti, non contenuti: nomi utente sì, didascalie e corpi delle risposte no. Il client CDP registra solo nomi di comandi (§6.1); il client del sito solo operazione o forma del percorso e stato (§6.0). Il rapporto di diagnostica (§7.9) è più severo dei registri: nemmeno i nomi utente, né indirizzi interi, solo forme, conteggi e codici di elenchi chiusi, perché è fatto per uscire dalla macchina di Alberto. Per le richieste verso Telegram e verso il CDN non si registrano gli indirizzi: contengono il gettone del bot e le firme dei file. - I campioni grezzi della sonda stanno fuori dal repository e si cancellano a fine M0 (§14.5). +- **Le copie esterne escono dal controllo di Febe** (§4.10). Chi ha la cartella di una destinazione, o il disco su cui sta, ha quei file, foto e video di altre persone compresi: Febe non li cifra, non li cancella e non ne sa più nulla oltre a ciò che ha registrato in `export_copy`. Nelle destinazioni Febe non scrive diari, identificativi o didascalie, solo i file con i nomi dello schema. La guida lo dice nella pagina dell'esportazione. ### 13.3 Avvisi @@ -928,6 +1048,11 @@ Eventi che meritano un avviso: verifica richiesta, disconnessione, fermo per ral - **Libreria**: nomi ripuliti, percorsi lunghi, scrittura con nome temporaneo, eliminazione che non torna, ricostruzione del database dai file. - **Doppioni**: immagini di prova generate e le loro varianti ridimensionate, ricompresse e ritagliate. - **Importazione**: interruzione e ripresa; «Sposta» non elimina mai un originale non verificato. +- **Codec e video** (traguardo 0.3.0, §3): decodificatori e codificatori sulle immagini di riferimento generate una volta con SkiaSharp (permesso di Alberto, §16 domanda 16), andata e ritorno senza perdita per PNG e WEBP senza perdita, metadati conservati. Pixel uguali esattamente per PNG, WEBP senza perdita, GIF e BMP; per JPEG e WEBP con perdita una tolleranza, perché la IDCT (ITU-T T.81 e T.83 ne fissano solo la precisione) e il ricampionamento della crominanza non danno gli stessi pixel in due decodificatori: proposta, PSNR di almeno 40 dB su ogni canale e al più lo 0,1 % dei pixel con un canale più lontano di 16 dal riferimento, da scrivere in `docs/decisioni.md` con C1. Decodificatore H.264 su tutti i flussi di conformità ITU-T H.264.1 di §3, di ogni profilo (interlacciati, Extended, High 10, 4:2:2, 4:4:4, monocromatici, SVC e MVC compresi), e decodificatore H.265 sui flussi di ITU-T H.265.1 dei profili di §3: uscita uguale bit per bit all'MD5 dell'uscita di riferimento, nessun flusso saltato. Lettori ISO BMFF, Matroska, ASF, FLV e MPEG-PS su file costruiti dalle prove stesse (durata, dimensioni, codec, data, file troncati e rovinati che non fanno cadere nulla); mai campioni veri. +- **Installatore e CI** (tappa C6, §3): l'installatore scritto in casa installa, aggiorna e disinstalla in una cartella di prova senza toccare i dati; l'interfaccia non carica file di caratteri né icone di terzi (nessun `@font-face`, nessun file di Archivo o Lucide in `wwwroot`). +- **Esportazione** (§4.10): nessuna sovrascrittura né cancellazione, radice della destinazione mai creata, stati «Tolto» e «Superato» mai ricopiati da soli, filtro «Copie» nei tempi della prova di scala. +- **Cosa scaricare prima** (tappa D1, §7.2): con orologio virtuale e seme fisso, il giro resta primo, l'ordine pesa senza diventare fisso, un tipo senza lavoro dovuto non si visita, tetti, pause, frequenze e composizione delle sessioni non cambiano; la coda dei file segue l'ordine dell'account. +- **Immagini danneggiate** (§8.4): PNG e JPEG troncati costruiti dalle prove danno «File danneggiato o incompleto», nessuna impronta, nessun doppione probabile, e il file resta. - **Ripulitura dei campioni**: nessun valore dei campioni grezzi sopravvive in quelli ripuliti (§14.5). ### 14.2 Sito di prova @@ -976,6 +1101,26 @@ Ogni tappa finisce con i controlli «Fatto quando» eseguiti e mostrati, `docs/s | **M8 Rifiniture** | Avvisi e Telegram, esportazione CSV, guida per l'uso, pagina sui problemi comuni | §4.8, §13.3, elenco qui sotto | Guida completa; un arresto simulato produce striscia, notifica e messaggio | | **M9 Facoltative** | Desktop collegato a un Febe remoto; seconda lingua | §5 | Da definire con Alberto | +**Traguardi dopo la versione 1.** Le attività stanno su Gitea, nei traguardi del repository. «0.2.0 — Raccolta che funziona su Instagram» (#36, #41) porta il client del sito e la sessione salvata (§6.0). **«0.3.0 — Esportazione»** (#58, decisione di Alberto del 18 novembre 2026) porta §4.10 e toglie i componenti esterni (regola 13, §3); porta anche la Dashboard, «Cosa scaricare prima» e «Raggruppa i post» / «Tutte le foto» (#59, decisione di Alberto del 25 novembre 2026, tappa D1). Ogni tappa è un ramo, una richiesta di unione e una verifica verde. + +| Tappa | Contenuto | Leggi | Fatto quando | +|---|---|---|---| +| **E0 Documenti** | Specifica, `CLAUDE.md`, decisioni e risposte di Alberto alle domande di #58 e alle domande 14–17 di §16. Niente codice | §2, §3, §4.10, §15, §16 | Documenti uniti in `main` | +| **C1 Codec delle immagini** | Decodificatori JPEG, PNG, WEBP (con e senza perdita), GIF, BMP; codificatori JPEG, PNG, WEBP senza perdita; EXIF, ICC e XMP; miniature e impronta visiva sopra di essi; ridimensionamento e disegnatore 2D per icona, immagini dimostrative e del sito di prova, anteprima dell'importazione e generatori delle prove (§3). Esce SkiaSharp | §3, §8.4, §9.3, §14.1 | Prove sulle immagini di riferimento (generate una volta con SkiaSharp, con il permesso di Alberto) verdi con le tolleranze di §14.1, soglie dei doppioni invariate, prova di scala con 200.000 elementi nei tempi; nessun uso di SkiaSharp in `src`, `tests` e `tools`; SkiaSharp tolto da `Directory.Packages.props` | +| **C2 Contenitori e metadati senza ffprobe** | Lettori ISO BMFF e Matroska (durata, dimensioni, rotazione, tracce, codec, metadati), rimuxaggio in MP4 | §3, §9.2 | Prove su video costruiti dalle prove; ffprobe non più chiamato | +| **C3 Decodificatore H.264** | **Tutto lo standard** (risposta di Alberto del 18 novembre 2026, §3): fotogrammi I, P, B, SP e SI di ogni profilo, dal Baseline non vincolato (FMO, ASO, fette ridondanti) e dall'Extended (partizione dei dati) a High 10, High 4:2:2 e High 4:4:4 (piani di colore separati, modo senza perdita), monocromatico, interlacciati (campi, PAFF, MBAFF), SVC e MVC; CAVLC e CABAC; miniature dei video importati. Esce ffmpeg dall'immagine Docker, dalla CI e dalle prove | §3, §8.4, §11, §12 | Tutti i flussi di ITU-T H.264.1 (i 12 già nel repository e quelli dei profili che mancano, scaricati con il permesso di Alberto, §16 domanda 15) in `tests/Febe.Tests/Media/H264/Conformita` con il `LEGGIMI.md` della fonte, uguali all'MD5 di riferimento, nessuno saltato; nessun processo esterno avviato da Febe oltre al browser e a Xvfb | +| **C4 Decodificatore H.265** | HEVC (ITU-T H.265) nei profili di §3: Main, Main 10, Main Still Picture e le estensioni di formato (RExt) della serie, che restano (risposta di Alberto del 25 novembre 2026, domanda 18 di §16), per fotogrammi, miniature e video fermi come H.264 | §3, §4.10, §8.4 | Tutti i flussi di ITU-T H.265.1 delle cartelle `HEVC_v1` e `RExt`, scaricati con il permesso di Alberto, in `tests/Febe.Tests/Media/H265/Conformita` con il `LEGGIMI.md` della fonte, uguali all'MD5 di riferimento, nessuno saltato | +| **C5 Lettori ASF, FLV e MPEG-PS** | Durata, dimensioni, codec e data dove c'è, per ASF (WMV), FLV e MPEG-PS (ISO/IEC 13818-1), nell'analisi dell'importazione (§9.2) | §3, §9.2 | Prove su file costruiti dalle prove, troncati e rovinati compresi; nessun file reale | +| **C6 Niente terzi nella CI e nell'interfaccia** | CI senza Node (passi di shell con git e curl verso l'API di Gitea), installatore di Windows scritto in casa al posto di NSIS, caratteri di sistema (`system-ui`) al posto di Archivo, icone SVG disegnate in casa al posto di Lucide. Restano solo gitleaks e Trivy nella CI, e Chromium con i suoi pacchetti Debian e Xvfb (regola 13) | §3, §10.1, §12, appendici B e C, `docs/processo.md` | Una verifica verde senza `node` nel contenitore delle prove né azioni che lo vogliano; installatore provato (§14.1); nessun file di Archivo o Lucide nel repository; schermate riconfrontate con i mockup (§10.7), con le differenze dei caratteri scritte; NSIS e Node tolti da `docs/processo.md` e dalla regola 13 | +| **E1 Schema** | Migrazione `0002` con le tabelle di §8.3, archivi e impostazioni `esportazione.*`. Nessun cambio di comportamento | §8.3, §4.10 | Database della versione 1 aggiornato con `foreign_key_check` pulito; database più nuovo rifiutato | +| **E2 Copie esterne** | Destinazioni (generale e per account), controlli delle cartelle, `/esporta` in Docker, «Copia in…» degli originali, adozione, stati «Tolto» e «Superato», «già copiato» su tessere, visualizzatore, scheda account e filtro «Copie», scheda «Esportazione» della Dashboard (di Attività, se D1 non è ancora unita) | §4.10, §10.3, §11, §12, §13.2 | Prove: cartelle rifiutate, radice mai creata, `/esporta` non montata quindi nulla scritto, nessuna sovrascrittura, adozione, filtro «Copie» con 200.000 elementi entro 250 ms. Schermate confrontate (§10.7) e guida dell'esportazione | +| **E3 Formati e fotogrammi** | Conversione delle copie e della libreria (il convertito si aggiunge, l'originale resta), metadati copiati, rimuxaggio, fotogrammi a richiesta, zip | §4.10, §3 | Prove: JPG → JPG è una copia, PNG con trasparenza → JPG, WEBP senza perdita con i pixel identici all'originale, metadati presenti nel convertito, MOV → MP4, fotogramma a un istante, ogni k secondi, N; libreria con originale intatto | +| **E4 Video fermi** | Analisi a richiesta, `video_analysis`, «Salva il fotogramma» | §4.10 | Prove su video costruiti dalle prove (immagine fissa con audio, dissolvenza dal nero, movimento, clip brevissima, tutto nero, rotazione); soglie in `docs/decisioni.md` | +| **E5 Esportazione automatica** | Destinazioni automatiche, domanda «Solo i nuovi», giro orario, «Riconosci le copie già presenti» | §4.10 | Prove: «Tolto» e «Superato» non si ricopiano, destinazione irraggiungibile in pausa e poi ripresa, nessuna copia durante una sessione del motore; guida completa | +| **D1 Dashboard e ordine** | Issue #59 (decisione di Alberto del 25 novembre 2026). «Cosa scaricare prima», generale e per account, con il peso dei tipi sulle visite dopo il Giro dei seguiti e l'ordine della coda dei file (§7.2, §6.5, §4.4, §8.3); la Dashboard al posto di Attività: prima voce della barra laterale, pagina iniziale (`/`, `/attivita` e la finestra di Windows portano a `/dashboard`), compatta, con l'anteprima del browser sempre visibile e le miniature nella cronologia con l'anteprima ingrandita (§7.9, §10.2); «Raggruppa i post» / «Tutte le foto» nella Libreria e nella scheda account (§4.6) | §4.4, §4.6, §6.5, §7.2, §7.9, §10.2, §10.3, §14.3 | Prove del motore con orologio virtuale e seme fisso: ordine predefinito storie, evidenza, post, reel, taggati; con un altro ordine la prima visita dopo il giro è più spesso del primo tipo, ma non sempre, e il giro resta primo; un tipo senza lavoro dovuto non si visita; coda dei file nell'ordine dell'account; simulazione di 30 giorni per i tre profili senza superamenti dei tetti, con pause, frequenze e composizione delle sessioni invariate. Interfaccia: `/` e `/attivita` aprono la Dashboard; «Tutte le foto» con 200.000 elementi nei tempi della prova di scala; la scelta del modo si ricorda per pagina e senza memoria del browser torna «Raggruppa i post». Schermate composte confrontate (§10.7) con le differenze in `docs/schermate/differenze.md`; guida aggiornata | + +Dipendenze: C1 → C2 → C3 → C4; C5 dopo C2; C6 indipendente dalle altre; D1 indipendente dalle altre (se E2 arriva prima, la sua scheda nasce nella vecchia Attività e passa alla Dashboard con D1); E1 → E2 → E3 → E4, con E3 dopo C1 per le foto e dopo C2 per il rimuxaggio, i fotogrammi dopo C3 (e dopo C4 per HEVC), E4 dopo C3; E5 dopo E2. La migrazione `0002` si concorda con le tappe di #36 che toccano lo schema; D1 ha una migrazione sua, numerata dopo quelle già unite. + `docs/stato.md` è il filo fra le sessioni: che cosa è fatto, che cosa è in corso, che cosa è stato rimandato e perché. `docs/decisioni.md` raccoglie ogni scelta tecnica presa strada facendo, con data e motivo. **Che cosa la guida deve dire per forza:** @@ -987,7 +1132,8 @@ Ogni tappa finisce con i controlli «Fatto quando» eseguiti e mostrati, `docs/s - che l'interfaccia Docker non va esposta su Internet, e che in Docker la password di Instagram passa dal server; - l'eventuale compromesso sulla sandbox di Chromium; - che cosa fare dopo una verifica o un rallentamento; -- dove sono le copie del database e come si ricostruisce. +- dove sono le copie del database e come si ricostruisce; +- dal traguardo 0.3.0, che le copie esterne escono dal controllo di Febe (§13.2) e che una conversione con perdita è scelta di Alberto (§4.10). --- @@ -1008,6 +1154,14 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del | 9 | Solo italiano, o anche inglese? | M4 | Solo italiano, testi già separati | | 10 | Su Unraid: porta, cartella della libreria, disco per i dati | M5 | Porta 8480, dati nella cartella delle applicazioni sul disco di cache | | 11 | **Risposta di Alberto del 16 novembre 2026: con una richiesta, non risultano viste** (§3). Domanda di allora: con la pagina che chiede i dati, le storie si chiedono con una richiesta (non risultano viste) o si continuano ad aprire nel visualizzatore (Alberto tra gli spettatori, come oggi)? | #36, sui campioni del nuovo HAR | Restare al visualizzatore, che è la scelta di §3; la richiesta solo se il visualizzatore non si può guidare in modo affidabile | +| 12 | **Risposte di Alberto del 18 novembre 2026** (§4.10, §3, §15). Le 16 domande dell'esportazione (#58): che cosa vuol dire «per ogni utente», convertire la libreria o solo le copie, quali formati, perdita, metadati, automatica o manuale, video fermi, audio, quando analizzare, ffmpeg, Docker, stesso post in due account, storie in evidenza, copie tolte o superate, mockup, traguardo | #58, tappa E0 | Risposte: cartella generale più cartella facoltativa per account con «Esporta questo account»; conversione per le copie **e** per la libreria, entrambe spente, nella libreria il convertito si aggiunge e l'originale resta; foto Originale/JPG/PNG/WEBP senza perdita, video Originale/MP4 solo rimuxaggio; perdita solo se scelta, JPG 92 con «con perdita»; tutti i metadati possibili; manuale sempre, automatica spenta e «Solo i nuovi»; video fermo copiato intero; solo fotogramma senza audio, detto; analisi solo a richiesta; **niente ffmpeg né componenti esterni**, codec e decodificatore H.264 in casa; `/esporta` solo se dichiarato, niente `VOLUME`; stesso post: una copia per account o una sola, a scelta; storia in evidenza conta anche come evidenza; «Tolto»/«Superato» mai ricopiati da soli; schermate dai mockup esistenti; traguardo 0.3.0 con tappe E0, C1–C3, E1–E5 (poi C3 allargata e C4–C6, domande 14 e 17) | +| 13 | **Risposte di Alberto del 18 novembre 2026** (§6.0, §13.2). Le domande della tappa S4 di #36: H21 e H22, copia alla chiusura della finestra e alla fine del permesso di guida, durata dei valori della pagina, copia incompleta | #36, dopo S4 | Risposte: `__spin_r`, `__spin_b`, `__spin_t` si copiano dalla pagina a «Ho finito», le operazioni con altri valori calcolati dalla pagina restano al browser; nessuna nuova sonda ora; H21 e H22 restano da verificare e le verifica Alberto nella prova dal vivo (S7); copia anche alla chiusura della finestra su Windows e alla fine del permesso di guida, se la pagina è sul sito; con «richieste» «Collegato» vuole una sessione salvata leggibile; «Scollega» tiene `chiave.bin`; nessun limite fisso di età; copia incompleta: opzione, sostituisci (predefinito) o tieni la completa e dillo; stato della sessione salvata nella pagina Collegamento, mai valori; niente browser e client insieme nello stesso momento (una ricetta alla volta, o l'uno o l'altro). Copia alla chiusura e alla fine del permesso, opzione «Copia incompleta», «Collegato» con la sessione salvata («Serve «Ho finito»») e stato nella pagina Collegamento sono arrivati con la tappa S4b | +| 14 | **Risposta di Alberto del 18 novembre 2026: «Tutto»** (§3, §15 tappa C3). Domanda di allora: video interlacciati (campi, PAFF, MBAFF), High 10, 4:2:2 e 4:4:4, SVC e MVC restano fuori dal decodificatore H.264? | C3, prima di cominciare | Risposta: il decodificatore copre tutto lo standard, ogni profilo compresi interlacciati (campi, PAFF, MBAFF), Extended (FMO, ASO, fette ridondanti, partizione dei dati, SP/SI), High 10, High 4:2:2, High 4:4:4 (piani di colore separati e senza perdita), monocromatico, SVC e MVC. Inoltre: decodificatore HEVC/H.265 in casa dentro la 0.3.0 (tappa C4); VP9 e AV1 non richiesti, tessera neutra; lettori in casa anche per ASF/WMV, FLV e MPEG-PS (tappa C5) | +| 15 | **Risposte di Alberto del 18 novembre 2026: sì** (§3, §14.1). Domanda di allora: si scarica il sottoinsieme delle serie di conformità ITU-T H.264.1 dei profili di §3, e dove stanno i flussi se superano 50 MB? | C3, prima di cominciare | Risposte: scaricamento permesso, fatto (12 flussi nel repository sul ramo `funzione/decoder-h264`); poi sì anche agli altri flussi di conformità ITU-T, i profili di H.264.1 che mancano e H.265.1: nel repository solo i flussi e l'MD5 dell'uscita di riferimento, con un `LEGGIMI.md` che dice la fonte | +| 16 | **Risposta di Alberto del 18 novembre 2026: sì** (§3, §14.1). Domanda di allora: le immagini di riferimento dei codec si generano una sola volta con SkiaSharp prima che esca? | C1, prima di cominciare | Risposta: SkiaSharp permesso un'ultima volta per generarle, fatto; per JPEG e WEBP con perdita le tolleranze di §14.1 | +| 17 | **Risposta di Alberto del 18 novembre 2026: si tolgono** (regola 13, §3, §15 tappa C6). Domanda di allora: componenti in uso oltre a quelli ammessi dalla regola 13 (Xvfb e gli altri pacchetti Debian di §11, il carattere Archivo e le icone Lucide come file, NSIS e Node nella CI): restano come eccezioni per nome o si tolgono? | E0 | Risposta: escono anche questi; installatore senza NSIS (scritto in casa), CI senza Node (passi di shell con git e curl verso l'API di Gitea), caratteri di sistema (`system-ui`) al posto di Archivo, icone SVG disegnate in casa al posto di Lucide. Restano solo Xvfb e i pacchetti Debian che servono a Chromium, e gitleaks e Trivy nella sola CI. Inoltre: lo stesso post in due account si copia con «Una copia per account» come predefinito (§4.10) | +| 18 | **Risposta di Alberto del 25 novembre 2026: le estensioni di formato (RExt) restano** (§3, §15 tappa C4). Domanda di allora: decodificatore H.265, oltre a Main, Main 10 e Main Still Picture, quali profili? Estensioni di formato (4:2:2, 4:4:4, 12 e 16 bit, senza perdita), scalabile (SHVC), multivista (MV-HEVC), 3D, contenuti dello schermo (SCC) | C4, prima di cominciare | Risposta: tutti i profili della serie di ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`): Main, Main 10, Main Still Picture e RExt fino a 12 bit. Ciò che non ha flussi in quella serie (precisione estesa a 16 bit, SHVC, MV-HEVC, 3D, SCC) dice «Fotogramma non disponibile per questo video». Inoltre, lo stesso giorno: in Docker lasciare la pagina del browser copia la sessione (§6.0); nell'immagine Docker `fonts-noto-color-emoji` resta e `fonts-liberation` esce (§11); le immagini troncate si rifiutano con «File danneggiato o incompleto», senza impronta, e restano in libreria (§8.4) | +| 19 | «Cosa scaricare prima»: le raccolte in evidenza vanno subito dopo le storie? Alberto ha detto storie, post, reel, taggati, senza nominarle | D1, prima di cominciare | Sì: storie, evidenza, post, reel, taggati, perché sono storie anche loro; si possono comunque spostare trascinandole | --- @@ -1041,7 +1195,7 @@ All'inizio di ogni sessione leggi docs/stato.md. 9. I lettori si scrivono solo su campioni reali ripuliti. Il formato delle risposte non si inventa. 10. Mai password, cookie, gettoni, tasti, variabili o corpi di richieste e risposte nei log. Il client CDP registra solo nomi di comandi; il client del sito solo operazione o forma del percorso e stato. 11. La libreria non cancella e non sostituisce file da sola. -12. Dipendenze a elenco chiuso (§3): prima di aggiungerne una, chiedi. +12. Niente componenti esterni: niente ffmpeg, programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro specifiche pubbliche. Ammessi solo .NET/BCL con ASP.NET Core, Microsoft.Data.Sqlite, il browser (Chromium o WebView2 con Microsoft.Web.WebView2, regola 4) e MSTest; nella sola CI gitleaks e Trivy (docs/processo.md); nell'immagine Docker solo Chromium, i pacchetti Debian che gli servono e Xvfb (mai headless). Escono con la loro tappa della 0.3.0 (specifica §2 regola 13, §15): SkiaSharp con C1, ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. Prima di aggiungere qualunque cosa, chiedi. ## Convenzioni - Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano (glossario: appendice D). @@ -1061,7 +1215,7 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande È il foglio che ha generato i mockup, con una sola differenza: qui il contenuto della pagina scorre (`.corpo` ha `overflow:auto`), mentre nelle immagini è tagliato al bordo. Usalo come base di `src/Febe.Web/wwwroot/css/febe.css` e completalo; i nomi delle classi puoi tenerli. Il tema scuro si attiva con `data-tema="scuro"` sull'elemento radice. -Il carattere Archivo variabile (licenza OFL) si prende dal pacchetto npm `@fontsource-variable/archivo`, cartella `files`: servono `archivo-latin-standard-normal.woff2` e `archivo-latin-ext-standard-normal.woff2`. Copiali in `wwwroot/caratteri/` con il file della licenza: il pacchetto non diventa una dipendenza. +Il carattere Archivo variabile (licenza OFL) si prende dal pacchetto npm `@fontsource-variable/archivo`, cartella `files`: servono `archivo-latin-standard-normal.woff2` e `archivo-latin-ext-standard-normal.woff2`. Copiali in `wwwroot/caratteri/` con il file della licenza: il pacchetto non diventa una dipendenza. **Con la tappa C6 della 0.3.0 Archivo esce** (regola 13, decisione di Alberto del 18 novembre 2026): le due regole `@font-face` e i file in `wwwroot/caratteri/` si tolgono, e `font-family` di `body` diventa la pila dei caratteri di sistema `system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`. ```css /* Febe — token e componenti di base */ @@ -1350,7 +1504,7 @@ Marchio: quadrato arrotondato nel colore d'accento con un anello e un punto, cio ``` -Icone: Lucide (licenza ISC), dal pacchetto npm `lucide-static`, cartella `icons`. Copia nel repository solo quelle usate e inseriscile come SVG in linea, con tratto 1,75. Elenco di partenza: +Icone: fino alla tappa C6 della 0.3.0 Lucide (licenza ISC), dal pacchetto npm `lucide-static`, cartella `icons`, solo quelle usate, come SVG in linea con tratto 1,75. **Con C6 Lucide esce** (regola 13, decisione di Alberto del 18 novembre 2026): ogni icona si ridisegna in casa, SVG in linea su una griglia di 24, tratto 1,75, con lo stesso nome d'uso, così l'interfaccia non cambia i suoi riferimenti. Elenco di partenza: | Uso | Icone | |---|---| @@ -1391,6 +1545,17 @@ Icone: Lucide (licenza ISC), dal pacchetto npm `lucide-static`, cartella `icons` | Sonda | `Probe` | Strumento passivo di M0 che registra ciò che la pagina riceve | | Impronta visiva | `PerceptualHash` | Numero che riconosce la stessa immagine in file diversi | | Vista remota | `RemoteView` | Il browser del server mostrato nell'interfaccia | +| Esportazione | `Export` | Copia di file della libreria in una cartella esterna (§4.10) | +| Destinazione | `ExportDestination` | La cartella esterna di un'esportazione, generale o di un account | +| Copia esterna | `ExportCopy` | Un file copiato in una destinazione, con il suo stato (Copiato, Tolto, Superato, Non riuscito) | +| Fotogramma | `Frame` | Un'immagine presa da un video | +| Video fermo | `StillVideo` | Video che mostra sempre la stessa immagine: basta un fotogramma | +| Rimuxaggio | `Remux` | Passaggio di un video in un altro contenitore senza ricodifica | +| Dashboard | `Dashboard` | La pagina iniziale e cruscotto del motore, prima voce della barra laterale; prima si chiamava Attività (§7.9) | +| Cosa scaricare prima | `DownloadOrder` | L'ordine dei tipi (storie, evidenza, post, reel, taggati) che pesa sulle visite dopo il Giro dei seguiti e sulla coda dei file, generale o di un account (§7.2) | +| Raggruppa i post | `MosaicMode.Grouped` | Il mosaico con una tessera per elemento, il predefinito (§4.6) | +| Tutte le foto | `MosaicMode.Files` | Il mosaico con una tessera per file, video compresi (§4.6) | +| File danneggiato o incompleto | `DamagedImage` | Un'immagine troncata o rovinata: tessera neutra, nessuna impronta, il file resta (§8.4) | --- diff --git a/docs/decisioni.md b/docs/decisioni.md index bd24b83..ede35f5 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -420,3 +420,67 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-17 | Il messaggio di «Ho finito» per una copia con valori mancanti conta solo i valori della pagina e i `doc_id` che un'operazione configurata manda (`SessionCapturePlan.NeededValues`, `NeededDocIds`; gli altri si leggono lo stesso e il registro li nomina a parte) e dice com'è: la copia ha sostituito quella di prima, le richieste che li usano non partono e alla prima Febe si ferma come disconnessione. Dopo un rifiuto il messaggio dice di riaprire il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premere di nuovo «Ho finito». La copia incompleta sostituisce comunque quella salvata | Il messaggio prometteva che quelle operazioni «restano al browser», ma il codice le ferma come disconnessione (§6.0, mai un ritorno alle pagine); e «Ho finito» chiude sempre il permesso di guida, quindi un secondo «Ho finito» da solo non copia nulla. Tenere una copia più vecchia ma completa potrebbe tenere i cookie di un altro accesso (regola 7) | | 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano | | 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» | +| 2026-11-18 | **Niente componenti esterni** (regola 12 di `CLAUDE.md`, regola 13 di §2, §3): niente ffmpeg, ffprobe, programmi o librerie di terzi, nessun codice copiato da altri progetti; tutto il codice in casa, i formati dalle loro specifiche pubbliche (ITU-T H.264, ITU-T T.81, PNG, RFC 9649, GIF89a, BMP, ISO BMFF, Matroska). Ammessi solo .NET/BCL con ASP.NET Core, Microsoft.Data.Sqlite, il browser (Chromium, WebView2 con `Microsoft.Web.WebView2`) e MSTest. Prima di aggiungere qualunque cosa si chiede | Decisione di Alberto (risposta alla domanda 10 di #58). Sostituisce l'«elenco chiuso» di §3 e la proposta di #58 (ffmpeg dal PATH o nell'installatore, circa 80–130 MB con licenza GPL; conversioni con SkiaSharp) | +| 2026-11-18 | SkiaSharp e ffmpeg/ffprobe escono e li sostituisce codice di Febe, a tappe nel traguardo 0.3.0: C1 decodificatori JPEG, PNG, WEBP (con e senza perdita), GIF, BMP, codificatori JPEG, PNG, WEBP senza perdita, EXIF/ICC/XMP, miniature e impronta visiva (esce SkiaSharp); C2 lettori ISO BMFF e Matroska e rimuxaggio in MP4 (esce ffprobe); C3 decodificatore H.264 con fotogrammi I, P e B (esce ffmpeg da immagine Docker, CI e prove). Finché una tappa non è unita il codice di prima li usa ancora. Cicli sui pixel con `Span`, senza LINQ né allocazioni | Conseguenza della riga precedente; l'ordine segue ciò che serve all'esportazione (§4.10): prima le foto, poi i contenitori, poi i fotogrammi. Le librerie arrivano a 200.000 elementi su processori di un server Unraid | +| 2026-11-18 | Le serie di conformità ITU-T H.264 si scaricano, con il permesso di Alberto, come dati di prova in `tests/Febe.Tests/Media/H264/Conformita`: solo i flussi e l'MD5 dell'uscita di riferimento, non le uscite decodificate | Sono il modo pubblico e ufficiale di dire che un decodificatore H.264 è giusto; dati, non codice di terzi (regola 13). Gli MD5 bastano a confrontare senza tenere nel repository centinaia di MB di fotogrammi | +| 2026-11-18 | SkiaSharp si usa un'ultima volta, prima che esca (tappa C1), per generare le immagini di riferimento delle prove dei codec; poi resta solo il risultato, come file di prova | Serve un riferimento indipendente dal codice nuovo per confrontarne i pixel; generarlo dopo non sarebbe più possibile senza la dipendenza | +| 2026-11-18 | **Esportazione** (#58, §4.10, traguardo «0.3.0 — Esportazione»): cartella generale più cartella facoltativa per account con «Esporta questo account», una destinazione effettiva per account; conversione del formato per le copie e per la libreria, entrambe spente, e nella libreria il file convertito si aggiunge all'elemento mentre l'originale resta (regola 12); foto Originale/JPG/PNG/WEBP senza perdita, video Originale/MP4 solo con rimuxaggio; perdita solo se scelta, JPG a qualità 92 con l'avviso «con perdita»; si copiano tutti i metadati possibili (EXIF con l'orientamento, ICC, XMP, data del file; per i video quelli del contenitore) | Risposte di Alberto alle domande 1–5 di #58. Il convertito deve essere la stessa immagine con un'altra estensione; nella libreria nulla si sostituisce da solo | +| 2026-11-18 | Esportazione, comportamento: manuale sempre, automatica spenta per destinazione e alla prima accensione la domanda con «Solo i nuovi»; un video fermo si copia intero; il solo fotogramma perde l'audio e la finestra lo dice; l'analisi dei video fermi si fa solo a richiesta, mai in sottofondo; `/esporta` in Docker attivo solo se dichiarato (`--esporta`, `FEBE_ESPORTA`) e montato, senza riga `VOLUME`; lo stesso post in due account con un'impostazione (una copia per account, predefinita, o una copia sola); una storia entrata in una raccolta in evidenza conta anche come evidenza; copia tolta o file della libreria cambiato diventano «Tolto» o «Superato», mai ricopiati da soli, «Copia di nuovo» a richiesta | Risposte di Alberto alle domande 6–14 di #58. Niente lavoro di CPU in sottofondo non chiesto; un volume anonimo farebbe sembrare `/esporta` montata e riempirebbe il disco delle immagini di Unraid | +| 2026-11-18 | Esportazione, pianificazione: le schermate nuove si compongono dai mockup esistenti e stanno fra le «Schermate senza mockup» di §10.3; nuovo traguardo «0.3.0 — Esportazione» con le tappe E0 documenti, C1 codec delle immagini, C2 video senza ffprobe, C3 decodificatore H.264, E1 schema `0002`, E2 copie esterne e «già copiato», E3 formati (copie e libreria) e fotogrammi, E4 video fermi a richiesta, E5 esportazione automatica (§15). La migrazione `0002` (`export_destination`, `export_copy`, `export_run`, `export_item`, `video_analysis`) supera «nessuna migrazione nuova» e si concorda con le tappe di #36 che toccano lo schema | Risposte di Alberto alle domande 15 e 16 di #58. Le parti di #58 su ffmpeg e SkiaSharp sono superate dalle righe precedenti | +| 2026-11-18 | Sessione salvata, dopo S4 (#36, §6.0, §6.1, §13.2): `__spin_r`, `__spin_b`, `__spin_t` si fotografano dalla pagina a «Ho finito», con il posto scritto nella sezione `page` dal codice pubblico della pagina; le operazioni che vogliono altri valori calcolati dalla pagina (`__req`, `__s`, `__dyn`, `__csr`…) restano al browser; nessuna nuova sonda ora; H21 e H22 verificate da Alberto | Risposte di Alberto alle domande 1–4 di S4. I valori calcolati mentre la pagina gira non hanno una fonte da fotografare, e non si inventano (regola 9) | +| 2026-11-18 | Sessione salvata, comportamento: si copia anche quando Alberto chiude la finestra del browser su Windows e quando il permesso di guida scade, se la pagina è sul sito (non accesso, verifica o riposo), tenendo il turno della pagina finché la copia finisce; con «richieste» «Collegato» vuole anche una sessione salvata leggibile; «Scollega» tiene `chiave.bin`; nessun limite fisso di età della sessione salvata; copia incompleta secondo un'opzione, «Sostituisci comunque» (predefinita) o «Tieni la copia completa di prima», detto ad Alberto; la pagina Collegamento mostra lo stato della sessione salvata (data della copia, valori presenti e mancanti per nome, mai i valori); niente browser e client insieme in una sessione del motore, come oggi | Risposte di Alberto alle domande 5–11 di S4. Sostituisce la riga del 17 novembre per cui chiudere la finestra o la fine del permesso non copiavano, e quella per cui una copia incompleta sostituiva sempre | +| 2026-11-18 | **Correzione**: H21 e H22 **non sono verificate**. Alberto ha risposto che le verifica lui (tappa S7 di #36, prova dal vivo), non che le ha già verificate; restano «da verificare da Alberto» in §6.6 e restano un motivo per tenere chiusa la porta con Instagram finché il loro esito non è scritto in `docs/sonda/esito.md`. Sostituisce «H21 e H22 verificate da Alberto» della riga sulle risposte 1–4 di S4 | La risposta registrata dice «H21 e H22 li verifica Alberto»; §6.6 vuole un esito scritto prima di costruirci sopra. Una prova (`SpecificationConsistencyTests`) rifiuta ogni ipotesi detta verificata senza esito | +| 2026-11-18 | Sessione salvata, precisazioni delle risposte 5–11 di S4. Copia alla chiusura della finestra, copia alla scadenza del permesso, opzione «Copia incompleta», stato della sessione salvata e «Collegato» con la sessione salvata sono **previsti per la tappa S6 di #36**: oggi copia solo «Ho finito» e una copia incompleta sostituisce sempre. Alla chiusura e alla scadenza il permesso è già finito: è un'eccezione scritta, Febe tiene **solo il turno della pagina** fino al salvataggio, al più 10 secondi, poi la copia si butta e il turno torna al motore, che intanto aspetta; il tenere il permesso per tutta la copia vale per «Ho finito». «Collegato» vuole la sessione salvata leggibile solo quando la composizione la costruisce (`richieste` e almeno un'operazione configurata); altrimenti, Instagram compreso, resta il solo cookie del browser. Il messaggio della copia incompleta dipende da ciò che è successo: con la copia completa di prima tenuta le richieste continuano a usarla e nulla si ferma. «Niente browser e client insieme» vuol dire mai nello stesso momento: in una sessione del motore le ricette vanno una alla volta, ognuna o con il browser o per richieste (§6.3) | I paragrafi di §6.0 scritti il 18 novembre si contraddicevano: una copia fatta alla scadenza del permesso si sarebbe buttata per la regola del permesso; Instagram con `richieste`, senza sessione salvata, non sarebbe mai stato «Collegato»; il messaggio prometteva un arresto anche quando la sessione completa restava; la frase sulla sessione del motore vietava ciò che il codice fa oggi (`RecipeRunner` sceglie la strada per ricetta) | +| 2026-11-18 | Esportazione, precisazioni di §4.10. Una copia è identificata da SHA-256 dell'originale, destinazione, **account effettivo**, variante, formato e istante del fotogramma: con «una copia per account» lo stesso SHA-256 sta due volte nella cartella generale, una per segmento di account, e «una volta sola per destinazione» vale per lo stesso account (storia ed evidenza). L'adozione per percorso non si fida della dimensione: per i convertiti e i fotogrammi Febe rifà la conversione e confronta lo SHA-256; se non coincide scrive su un nome libero. Le immagini animate (GIF con più fotogrammi, WEBP con `ANIM`/`ANMF`, PNG con `acTL`) non si convertono: si copia l'originale con una nota. Il file di prova delle cartelle rifiutate è un `.febe-prova-*.part` scritto solo nella cartella candidata e cercato in lettura nelle altre | Senza account la tabella non poteva tenere il caso predefinito; un file diverso della stessa dimensione sarebbe stato segnato «Copiato» per sempre; convertire un'animazione ne avrebbe perso i fotogrammi in silenzio; un file di prova senza nome né cartella avrebbe violato la regola 12 o la decisione del 13 ottobre di non scrivere in `/importa` | +| 2026-11-18 | Codec, precisazioni di §3, §14.1 e §15. JPEG: Huffman a 8 bit, di base, sequenziale esteso e progressivo, grigi, YCbCr, CMYK e YCCK (APP14 di Adobe); fuori codifica aritmetica, 12 bit, senza perdita e gerarchico. WEBP con perdita: VP8 di RFC 6386. Prove: pixel esatti per PNG, WEBP senza perdita, GIF e BMP; per JPEG e WEBP con perdita una tolleranza proposta (PSNR ≥ 40 dB per canale, al più lo 0,1 % dei pixel oltre 16), da fissare con C1. H.264: Constrained Baseline, Main e High, 8 bit, 4:2:0, a quadri interi, CAVLC e CABAC; fuori interlacciati (PAFF, MBAFF), High 10, 4:2:2, 4:4:4, SVC, MVC, Extended (proposta, §16 domanda 14); C3 è finita quando passa un elenco scritto dei flussi di H.264.1 in quei profili. C1 comprende anche ridimensionamento e un disegnatore 2D con antialias, perché SkiaSharp disegna l'icona, le immagini dimostrative e del sito di prova, l'anteprima dell'importazione e le immagini delle prove | IDCT e ricampionamento della crominanza non sono uguali bit per bit fra due decodificatori: un confronto esatto non sarebbe mai passato. «Tutta la serie di conformità» comprende profili che Febe non decodifica, e senza un disegnatore SkiaSharp non poteva uscire da `Directory.Packages.props` | +| 2026-11-18 | **Correzione**: lo scaricamento delle serie di conformità ITU-T H.264 e le immagini di riferimento generate con SkiaSharp (righe precedenti di oggi) sono **proposte da confermare con Alberto** (§16, domande 15 e 16), non decisioni: le risposte registrate non ne parlano. Proposta: solo il sottoinsieme dei profili di §3, al più 50 MB in git, con le condizioni d'uso dell'ITU-T accanto; finché Alberto non risponde non si scarica e non si genera nulla | Il permesso non si ritrovava fra le risposte; la serie intera pesa decine o centinaia di MB di binari | +| 2026-11-18 | La regola 13 (regola 12 di `CLAUDE.md`, guida Sviluppo) nomina per nome ciò che è in uso oltre ai quattro ammessi: gitleaks e Trivy nella sola CI, già approvati (`docs/processo.md`); da confermare o togliere con Alberto (§16, domanda 17) Xvfb e gli altri pacchetti Debian di §11, carattere Archivo e icone Lucide come file di dati, NSIS e Node nella CI; SkiaSharp fino a C1 e ffmpeg fino a C3. `Directory.Packages.props` dice la regola e la tappa in cui esce SkiaSharp | La regola diceva «ammessi solo» quattro cose mentre §3, §11, §15 e la CI ne usano altre: un elenco per nome evita che qualcuna resti sottintesa. Una prova controlla che le tre copie della regola le nominino e che ogni pacchetto non ammesso dica la sua tappa | +| 2026-11-18 | **Decodificatore H.264: tutto lo standard** (§3, §15 tappa C3, §16 domanda 14): ogni profilo, compresi interlacciati (campi, PAFF, MBAFF), Extended (FMO, ASO, fette ridondanti, partizione dei dati, fette SP e SI), High 10, High 4:2:2, High 4:4:4 (piani di colore separati e modo senza perdita), monocromatico, SVC e MVC. Per fotogrammi e miniature si usano lo strato con la risoluzione più alta (SVC) e la vista di base (MVC); più di 8 bit si porta a 8 solo all'uscita. La tappa C3 si allarga: tutti i flussi di ITU-T H.264.1, nessuno saltato | Risposta di Alberto del 18 novembre 2026 alla domanda 14: «Tutto». Supera la proposta di prima (solo Constrained Baseline, Main e High a quadri interi) | +| 2026-11-18 | **Decodificatore HEVC/H.265 in casa dentro la 0.3.0**, nuova tappa C4, dopo C3: almeno Main, Main 10 e Main Still Picture; gli altri profili sono la domanda 18 di §16 (proposta: tutti quelli di cui ITU-T H.265.1 ha flussi). VP9 e AV1 non si decodificano: tessera neutra e «Fotogramma non disponibile per questo video» | Risposta di Alberto del 18 novembre 2026: HEVC sì, ora; VP9 e AV1 non richiesti. | +| 2026-11-18 | **Lettori in casa anche per ASF/WMV, FLV e MPEG-PS** (ISO/IEC 13818-1, flusso di programma), nuova tappa C5 dopo C2: durata, dimensioni, codec e data dove il contenitore la porta, per l'analisi dell'importazione (§9.2). Solo metadati: niente rimuxaggio né decodifica, salvo una traccia H.264 o H.265 dentro MPEG-PS | Risposta di Alberto del 18 novembre 2026. Senza ffprobe questi file avrebbero avuto solo il tipo; dalle loro specifiche pubbliche i campi che servono sono pochi | +| 2026-11-18 | **Escono anche i componenti di terzi rimasti**, tappa C6: installatore di Windows scritto in casa al posto di NSIS; CI senza Node (passi di shell con git e curl verso l'API di Gitea al posto delle azioni); caratteri di sistema (`system-ui`, `-apple-system`, `"Segoe UI"`, `Roboto`, `sans-serif`) al posto di Archivo; icone SVG disegnate in casa, con gli stessi nomi d'uso, al posto di Lucide. Restano solo gitleaks e Trivy, nella sola CI, e nell'immagine Docker Chromium con i pacchetti Debian che gli servono e Xvfb (più ICU e certificati per .NET). Regola 13 della specifica e regola 12 di `CLAUDE.md` riscritte: non c'è più nulla «da confermare», ogni componente in uso dice la tappa in cui esce | Risposta di Alberto del 18 novembre 2026 alla domanda 17. Sostituisce la proposta di tenerli come eccezioni per nome. Xvfb resta perché Chromium ha sempre una finestra e non è mai headless (regola 2) | +| 2026-11-18 | **Altre serie di conformità ITU-T**: si scaricano anche i flussi di H.264.1 dei profili che mancano e quelli di H.265.1. Nel repository solo i flussi e l'MD5 dell'uscita di riferimento, mai le uscite decodificate, con un `LEGGIMI.md` che dice la fonte (in `tests/Febe.Tests/Media/H264/Conformita` e `tests/Febe.Tests/Media/H265/Conformita`). Le domande 15 e 16 di §16 sono risposte: lo scaricamento dei primi 12 flussi di H.264.1 (ramo `funzione/decoder-h264`) e l'ultimo uso di SkiaSharp per le immagini di riferimento dei codec erano stati permessi da Alberto e sono fatti; la riga «Correzione» di oggi che li diceva proposte è superata | Risposte di Alberto del 18 novembre 2026. Il tetto di 50 MB era solo una proposta: Alberto ha detto sì ai flussi nel repository senza porne uno | +| 2026-11-18 | **Lo stesso post in due account: «Una copia per account» è il predefinito** (§4.10); «Una copia sola» resta la scelta alternativa | Risposta di Alberto del 18 novembre 2026, che conferma la proposta | +| 2026-11-18 | Specifica allineata alla tappa S4b di #36 (ramo `funzione/sessione-s4b`): la copia alla chiusura della finestra e alla fine del permesso di guida, l'opzione «Copia incompleta» (`sessione.copia-incompleta`), «Serve «Ho finito»» e il riquadro della sessione salvata nella pagina Collegamento non sono più «previsti per la tappa S6»: la copia si fa prima che la pagina torni al motore, con la presa del permesso e il turno della pagina tenuti fino alla fine (§6.0, §6.1); la regola 11 e §13.2 permettono nella pagina Collegamento solo data della copia, conteggi e nomi mancanti; `spin_r`, `spin_b`, `spin_t` stanno nella tabella dei valori con il loro posto in `SiteData` e non sono più `pending`; H23 entra in §6.6. Supera la riga «Sessione salvata, precisazioni delle risposte 5–11 di S4» di oggi | Revisione di S4b: la specifica diceva ancora «oggi copia solo «Ho finito»» e «tiene solo il turno della pagina», contro il codice e le decisioni di S4b | +| 2026-11-25 | **In Docker lasciare la pagina del browser copia la sessione** (§6.0 «Quando si copia», §6.1): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota di Collegamento a un'altra pagina di Febe, chiudere la scheda o perdere il collegamento vale come chiudere la finestra «Browser di Febe» su Windows, con le stesse garanzie (comandi del collegamento, presa del permesso e turno della pagina fino al salvataggio, 30 secondi di attesa per un comando in corso, 10 secondi per la copia), solo da una pagina del sito che non sia di accesso o di verifica; poi il permesso finisce e la pagina torna al motore. Il server lo riconosce dalla chiusura dell'ultima vista remota aperta durante il permesso, se per 5 secondi non se ne apre un'altra (proposta: così una ricarica della pagina non è una partenza) | Risposta di Alberto del 25 novembre 2026. Prima in Docker si copiava solo a «Ho finito» e alla fine del permesso, e una scheda chiusa lasciava il permesso aperto fino alla sua scadenza | +| 2026-11-25 | **Immagine Docker: `fonts-noto-color-emoji` resta, `fonts-liberation` esce** (§11); `fonts-dejavu-core` resta come carattere di base del browser. Il Dockerfile e `docs/docker.md` vanno allineati nella prima tappa che tocca l'immagine | Risposta di Alberto del 25 novembre 2026: Chromium ha bisogno delle emoji per mostrare le pagine; Liberation non serve. DejaVu non è stato nominato: resta perché il browser ha bisogno di almeno un carattere per il testo | +| 2026-11-25 | **Immagini troncate o rovinate rifiutate e dette** (§3, §4.6, §8.4, §9): tessera neutra, «File danneggiato o incompleto» nel visualizzatore, nessuna impronta visiva (mai doppione probabile per impronta, né scaricando né importando), lo SHA-256 sì; il file resta in libreria (regola 12) e Febe non lo riscarica da sé | Risposta di Alberto del 25 novembre 2026. Decodificare a metà avrebbe dato miniature e impronte sbagliate, e quindi doppioni falsi | +| 2026-11-25 | **HEVC: le estensioni di formato (RExt) restano**; il decodificatore copre i profili della serie ITU-T H.265.1 scelta (cartelle `HEVC_v1` e `RExt`: Main, Main 10, Main Still Picture, RExt fino a 12 bit). Ciò che la serie non ha (precisione estesa a 16 bit, SHVC, MV-HEVC, 3D, SCC) dà «Fotogramma non disponibile per questo video». La domanda 18 di §16 è risposta | Risposta di Alberto del 25 novembre 2026. «Tutti i profili della serie» letto come i profili di cui i flussi scaricati per Febe hanno esempi: senza flussi di conformità un profilo non si può dire provato (§14.1) | +| 2026-11-25 | **«Cosa scaricare prima»** (issue #59, tappa D1 della 0.3.0; §7.2, §4.4, §6.5): ordine dei tipi generale (Impostazioni → Limiti e comportamento) e per account («Come le impostazioni generali» o un ordine suo), cambiato trascinando o con «Su»/«Giù». Predefinito storie, evidenza, post, reel, taggati. Pesa sulle visite dopo il Giro dei seguiti (peso dell'account × peso del tipo, 16, 8, 4, 2, 1 per posizione: proposta da tarare con la simulazione) e sull'ordine della coda dei file (prima il tipo che viene primo, poi la scadenza e l'attesa). Governatore, tetti, pause, fascia, frequenze e composizione casuale delle sessioni non cambiano; un tipo senza lavoro dovuto non si visita. Un reel conta come reel in coda solo se Febe lo sa, altrimenti come post; le foto del profilo vanno con i post. Ordine dell'account in una colonna di `account` e quello generale in `setting` (`scaricamento.ordine`), con una migrazione di D1 | Richiesta di Alberto del 25 novembre 2026 («di default scarica prima le storie, poi i post, poi reel, poi taggati»). Le raccolte in evidenza subito dopo le storie sono una proposta, perché Alberto non le ha nominate (§16 domanda 19). Pesi e non un ordine fisso, perché un ordine sempre uguale renderebbe le sessioni regolari, contro §7.1 | +| 2026-11-25 | **Attività diventa Dashboard** (§7.9, §10.2, §10.3; tappa D1): prima voce della barra laterale («Dashboard, Libreria, Account, Importa»), pagina iniziale di Febe (`/` e `/attivita` portano a `/dashboard`, la finestra di Windows e il riquadro di stato vi aprono), compatta, con l'anteprima del browser sempre visibile e aggiornata a ogni fotogramma (al più uno al secondo, comandi già ammessi da §6.1), la cronologia con le miniature di ciò che è arrivato e un'anteprima ingrandita leggera (dialogo, non il visualizzatore) con «Apri nella Libreria» e «Apri l'account». Striscia, tetti, coda e «Diagnostica» restano, ridotti. Schermata senza mockup composta da 06, 11 e 01 | Richiesta di Alberto del 25 novembre 2026: mentre Febe lavora resta su questa pagina a guardare lo scaricamento. Le miniature si caricano solo quando la riga è in vista e la cronologia a richiesta, per restare leggera con librerie grandi | +| 2026-11-25 | **«Raggruppa i post» / «Tutte le foto»** nella Libreria e nella scheda account (§4.6, §4.3): una tessera per elemento (predefinito) o per file, video compresi, con la posizione «2/4» sulle tessere di una serie e il visualizzatore che va di file in file. In «Tutte le foto» «Copia in…» e «Fotogrammi…» lavorano sui file scelti, CSV ed «Elimina» sugli elementi a cui appartengono, detto nella conferma. La scelta si ricorda nel browser di chi guarda (memoria locale, come il tema, letta e scritta in un `try`), una per la Libreria e una per le viste degli account; senza, «Raggruppa i post» | Richiesta di Alberto del 25 novembre 2026 («utile quando un post ha più foto»). Una preferenza di vista, non un dato: non serve né nel database né sugli altri dispositivi. Eliminare resta per elemento (§4.6), per non lasciare post a metà | +| 2026-11-25 | Nuova tappa **D1 Dashboard e ordine** nel traguardo 0.3.0 (§15), indipendente da C1–C6 ed E1–E5; `SpecificationConsistencyTests` controlla anche questi punti (copia in Docker lasciando la pagina, caratteri dell'immagine, immagini danneggiate, RExt, ordine, Dashboard, modo del mosaico, glossario) e la domanda 18 con la risposta del 25 novembre | Issue #59. Le prove dei documenti tengono insieme le risposte di Alberto e il testo della specifica | +| 2026-11-18 | Nuovi valori della sessione `spin_r`, `spin_b`, `spin_t` (`__spin_r`, `__spin_b`, `__spin_t`), copiati dalla pagina a «Ho finito» come gli altri: su Instagram dalle chiavi omonime di `SiteData` (`SiteData.__spin_r` …), nel sito di prova dal modulo suo `GiroProva` (`revisione` e `tempo` numeri, `ramo` testo), che il sito controlla nella richiesta GraphQL. Nelle nove operazioni GraphQL di Instagram (`media-info` non ha campi `__spin_*`) le tre fonti passano da `pending` a `session:spin_*`, ma tutte e dieci le operazioni restano non configurate | Risposta 1 di Alberto (#36, S4): un'istantanea della pagina; i valori che cambiano mentre la pagina gira (`__req`, `__s`, `__dyn`, `__csr` …) restano al browser. Che `SiteData` tenga quelle chiavi viene dalla forma del codice pubblico della pagina già usata in S4; chi le mette nella richiesta e se i nomi esatti di `SiteData` (con i due trattini bassi) sono quelli resta da vedere dal vivo (H23, ipotesi nuova da aggiungere a §6.6; intanto descritta in `docs/prove-dal-vivo.md`, parte E), e finché `__req`, `__s`, `__dyn`, `__csr` non hanno fonte nessuna operazione si configura comunque | +| 2026-11-18 | La sessione si copia anche alla chiusura della finestra «Browser di Febe» su Windows (anche ridotta a icona troppo a lungo) e quando il permesso di guida di «Accedi» / «Usa il browser» finisce da solo, sempre prima che la pagina torni al motore: la finestra tiene una presa del permesso di guida finché la copia non è finita (`WebView2HostOptions.CopyOnClose`, `FebePlatformContext.CopyOnWindowClosed`), la fine del permesso copia prima di rilasciarlo; in tutti e due i casi i comandi del collegamento, la presa del permesso e il turno della pagina come a «Ho finito», solo con il cookie di sessione nel browser, solo da una pagina del sito che non sia di accesso o di verifica. Nessun messaggio, una riga di registro con soli conteggi; la fine del permesso non copia di nuovo se la finestra ha appena copiato (un segno di guida entro un giro di controllo dalla copia è la presa della finestra) | Risposta 5 di Alberto. Sotto le stesse garanzie di «Ho finito» per la regola 7: la pagina non è mai letta quando è del motore. In Docker c'è solo la fine del permesso (la vista remota non ha una finestra da chiudere); la chiusura della finestra ha un limite di 30 s (`LetGoWait`) perché non trattenga il motore se un altro comando del collegamento è in corso | +| 2026-11-18 | Con la raccolta «richieste» e una sessione salvata nella composizione, «Collegato» vuole anche una sessione salvata leggibile: senza, lo stato è `SessionCopyMissing` (`copyMissing`, «Serve «Ho finito»»), `EngineRuntime.IsConnected` è falso e il motore aspetta con il titolo «Serve «Ho finito»»; la pagina Collegamento apre la pagina iniziale (non l'accesso) e spiega che cosa fare. Con «pagine» non cambia nulla | Risposta 6 di Alberto. Senza copia le ricette per richieste si fermerebbero alla prima come disconnessione: meglio aspettare e dirlo. La strada di «Pagina iniziale» resta quella del cookie | +| 2026-11-18 | Impostazione `sessione.copia-incompleta` (`SessionCopySettings`, tabella `setting`): `sostituisci` (predefinita) o `tieni-completa`. Con `tieni-completa` una copia a cui manca un valore o un `doc_id` che un'operazione configurata manda non sostituisce una copia salvata che li ha tutti, e «Ho finito» lo dice; altrimenti sostituisce come in S4. Letta a ogni copia (nessun riavvio), `GET`/`PUT /api/connection/settings`, scelta nel riquadro della pagina Collegamento | Risposta 9 di Alberto: un'opzione, con il comportamento di S4 come predefinito perché una copia più vecchia potrebbe avere i cookie di un altro accesso; il messaggio consiglia «Sostituisci comunque» dopo un nuovo accesso o un cambio di account | +| 2026-11-18 | La pagina Collegamento mostra la sessione salvata (riquadro «Sessione salvata per le richieste»): data della copia, valori della pagina e `doc_id` presenti su quelli letti, numero di cookie, nomi di quelli mancanti e quanti servono alle operazioni configurate; `GET /api/connection` li porta in `savedSession` (solo conteggi e nomi, mai valori; `null` con «pagine»). La data si scrive nel fuso del browser | Risposta 10 di Alberto. I nomi dei campi e delle operazioni non sono valori (regola 10); il rapporto (`ISessionCopier.Report`) li calcola dalla sessione in memoria, senza leggere il file | +| 2026-11-18 | Correzioni della revisione di S4b. (1) Un errore imprevisto durante la copia senza «Ho finito» (database, disco, Febe che si ferma) non trattiene più il permesso di guida: la copia lo scrive nel registro con il solo tipo d'errore e la fine del permesso arriva lo stesso; il controllo della fine della guida, se si interrompe per un errore, rilascia il permesso. (2) Un «Ho finito» tardivo, dopo che lo stesso uso del browser ha già copiato quando è tornato al motore, non legge nulla e dice che la sessione era già stata copiata (senza chiedere un nuovo accesso se la copia è completa); un nuovo «Accedi» / «Usa il browser» dimentica quella copia. (3) Il registro distingue «Finestra del browser chiusa» da «Finestra del browser ridotta a icona troppo a lungo» (`BrowserWindowLetGo`). (4) `EngineSnapshot.SessionCopyMissing`: con il motore in funzione `/api/engine` e gli eventi prendono «Serve «Ho finito»» dall'istantanea del motore, senza chiedere al browser; il collegamento si interroga solo con il motore spento | Il permesso tenuto per sempre lasciava il motore in «Stai usando il browser» senza un errore nel registro; il messaggio tardivo diceva «non è stata copiata, rifai l'accesso» di una sessione appena salvata; il registro diceva «chiusa» di una finestra solo ridotta a icona; ogni evento del flusso costava un indirizzo e un controllo del cookie via CDP | +| 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-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 | diff --git a/docs/docker.md b/docs/docker.md index c74528d..b5241a1 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -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. - Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET. -- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati), ICU, caratteri di sistema con le emoji - (`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. +- `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 (`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 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 @@ -71,7 +74,7 @@ gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»). | `FEBE_CHIAVE_SESSIONE` | Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (`openssl rand -base64 32`) o 64 cifre esadecimali. Senza, Febe crea una volta `/dati/sessione/chiave.bin`, leggibile solo dal proprietario. Impostala se vuoi la chiave fuori da `/dati` (così una copia di `/dati` da sola non apre la sessione); se la cambi, la sessione salvata non si legge più e basta rifare l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega | `/dati/sessione/chiave.bin` | La password dell'interfaccia e la chiave della sessione non si passano mai sulla riga di comando e non finiscono nei -registri; Febe le toglie dall'ambiente di Chromium, Xvfb e ffmpeg. +registri; Febe le toglie dall'ambiente di Chromium, Xvfb e ffmpeg (che c'è fino alla tappa C3 del traguardo 0.3.0). ## Porte diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md index c18ee78..7374887 100644 --- a/docs/guida/Primo-collegamento.md +++ b/docs/guida/Primo-collegamento.md @@ -37,13 +37,50 @@ fa anche una **copia della sessione** per le richieste dirette di Febe: i cookie browser e i pochi valori che la pagina tiene per le sue richieste, cifrati nella cartella dei dati (`sessione/sessione.json`). La copia si fa solo se il browser è su una pagina del sito (non sulla pagina di accesso o di una verifica) e mentre il browser è ancora tuo; il messaggio di «Ho finito» dice se è riuscita e se alla pagina -mancava qualche valore che serve alle richieste. Una copia così sostituisce comunque quella di prima, e le richieste -che usano il valore mancante non partono: alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. Se -la copia non è riuscita o è incompleta, riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina -iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale: dopo «Ho finito» il browser torna al motore, quindi -premerlo una seconda volta senza riaprirlo non copia nulla. Su Windows -chiudere la finestra del browser non copia: serve «Ho finito». Con `pagine`, il predefinito, e con Instagram per ora -anche con `richieste`, «Ho finito» non copia nulla e guarda solo se il cookie di sessione esiste. +mancava qualche valore che serve alle richieste. Le richieste che usano un valore mancante non partono: alla prima Febe +si ferma come disconnessione e chiede un nuovo accesso. Se la copia non è riuscita o è incompleta, riapri il browser +dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale: +dopo «Ho finito» il browser torna al motore, quindi premerlo una seconda volta senza riaprirlo non copia nulla. + +Febe copia la sessione anche quando lasci il browser **senza** «Ho finito», sempre prima di riprenderselo e solo da una +pagina del sito che non sia di accesso o di verifica: + +- **su Windows**, quando chiudi la finestra «Browser di Febe» (o la lasci ridotta a icona troppo a lungo); +- **in Docker**, quando lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza «Ho finito»: passi a + un'altra pagina di Febe, chiudi la scheda o la finestra del browser in cui la guardi, o se ne perde il collegamento. + Febe aspetta 5 secondi: se in quel tempo la vista remota non si riapre (una pagina ricaricata la riapre subito, e + ricaricare non è lasciare), copia la sessione e il motore può riprendere; +- quando dopo «Accedi a Instagram» o «Usa il browser» nessuna vista del browser resta aperta per 2 minuti (su Windows + la finestra fuori vista) e la guida finisce da sola. + +Solo il pulsante **«Annulla»** non copia mai: il browser torna sulla pagina vuota e, se non c'era già una copia, lo +stato diventa «Serve «Ho finito»». + +In questi casi non compare nessun messaggio: il registro dice com'è andata (solo conteggi, mai valori), e la pagina +Collegamento mostra la copia. Se poi premi «Ho finito» lo stesso: + +- se il browser è **già tornato al motore** (la guida è finita), Febe non rilegge la pagina e ti dice che la sessione + era già stata copiata: se la copia era completa non serve rifare l'accesso; +- se il browser è **ancora tuo** (su Windows, entro i 2 minuti dalla chiusura della finestra, mentre «Accedi a + Instagram» o «Usa il browser» tiene ancora il browser), «Ho finito» copia di nuovo come sempre e il suo messaggio dice + com'è andata quella copia. + +**«Collegato» con la raccolta «richieste».** Il cookie di sessione nel browser non basta: serve anche una copia +leggibile della sessione. Se manca (per esempio dopo «Annulla», o se il file non si legge più), lo stato è **«Serve «Ho +finito»»**, il motore aspetta e la pagina Collegamento apre la tua pagina iniziale nel browser: premi «Ho finito». + +**La sessione salvata nella pagina Collegamento.** Da collegato, il riquadro «Sessione salvata per le richieste» dice +quando è stata copiata, quanti valori della pagina e quanti `doc_id` ci sono su quelli che Febe legge, quanti cookie, e +il nome di quelli che mancano (mai i valori). Sotto c'è la scelta **«Se una copia nuova è incompleta»**: + +- **«Sostituisci comunque»** (il predefinito, consigliato): la copia nuova prende sempre il posto di quella salvata, + perché una copia più vecchia potrebbe avere i cookie di un altro accesso; +- **«Tieni la copia completa»**: se alla copia nuova manca qualcosa che le richieste usano e quella salvata ha tutto, + Febe tiene quella salvata e il messaggio di «Ho finito» lo dice. Se hai rifatto l'accesso o cambiato account, torna a + «Sostituisci comunque». + +La scelta vale dalla copia successiva, senza riavviare. Con `pagine`, il predefinito, e con Instagram per ora anche con +`richieste`, «Ho finito» non copia nulla, guarda solo se il cookie di sessione esiste e il riquadro non c'è. «Annulla» torna alle impostazioni senza collegarti. @@ -66,7 +103,7 @@ sua copia cifrata): **chi ha la cartella dei dati, o una sua copia, ha la sessio «Prudente»). - La prima sessione parte tra 2 e 10 minuti dopo l'avvio, e solo dentro la fascia oraria. - Lo stato del collegamento è sempre in fondo alla barra laterale: collegato, da collegare, verifica richiesta, sessione - chiusa. + chiusa e, con la raccolta «richieste», «Serve «Ho finito»». - Il tuo profilo compare tra gli account segnato «Tu», con «Post in cui è taggato» attivo: è così che si scaricano i post in cui sei taggato. Su Instagram i dati della pagina danno solo l'identificativo del tuo account: Febe ti riconosce quando compare anche il tuo profilo (per esempio la tua voce nella barra delle storie); fino ad allora la @@ -91,7 +128,9 @@ nulla: premilo di nuovo. Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la scheda chiusa o ricaricata): -- **in Docker** vale come «Annulla»: il browser torna sulla pagina vuota e il motore può lavorare di nuovo; +- **in Docker** è come chiudere la finestra del browser su Windows: se entro 5 secondi la vista remota non si riapre + (ricaricare la pagina la riapre), Febe copia la sessione come detto sopra e il motore può lavorare di nuovo (poi + rimette il browser a riposo sulla pagina vuota). Non è «Annulla»: quello lo fa solo il suo pulsante; - **su Windows** la finestra «Browser di Febe» resta com'è, sullo schermo e con la sua pagina, finché non la chiudi (o premi «Ho finito»); finché è sullo schermo il motore resta fermo. diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index 3507fee..6f032a5 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -32,7 +32,9 @@ dati. | La vista remota dice «Nessuna immagine dal browser» | La vista è aperta ma la pagina non arriva. Febe riavvia da solo l'invio delle immagini quando si fermano; premi «Riprova». Se resta così, guarda il registro (categoria «vista»: avvii, riavvii e silenzi) e riferisci il caso | | Il browser è bianco, o la barra dice «Il browser è a riposo su una pagina vuota» | È la pagina vuota su cui Febe lascia il browser quando non lo usa: premi «Pagina iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) | | «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» | -| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era | +| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era. Se invece il messaggio dice che la sessione «era già stata copiata quando il browser è tornato al motore», Febe l'ha copiata quando hai lasciato il browser (su Windows chiudendo la finestra, o alla fine della guida) e il browser era già tornato al motore: se il messaggio non dice che mancano valori, non serve fare nulla. In Docker lasciare la pagina senza «Ho finito» non copia: premi «Ho finito» prima di uscire | +| «Serve «Ho finito»» (barra laterale o pagina Collegamento) | Solo con la raccolta «richieste»: il browser ha la sessione, ma Febe non ha una copia leggibile per le richieste (dopo «Annulla», o con un file che non si legge più). Il motore aspetta: dalla pagina Collegamento apri la tua pagina iniziale nel browser e premi «Ho finito» | +| «Alla pagina mancavano … Febe tiene la copia completa salvata prima e non usa quella nuova» | Hai scelto «Tieni la copia completa» nella pagina Collegamento e alla pagina mancava un valore che le richieste usano. Se hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque» e premi di nuovo «Ho finito» | | «Sessione copiata…, ma non ancora scritta su disco» | Il disco ha rifiutato la scrittura (spazio, permessi di `/dati/sessione`): Febe usa la copia in memoria e riprova alla prossima scrittura. Controlla lo spazio e i permessi; il registro dice il tipo d'errore | | Dopo un riavvio Febe chiede di nuovo l'accesso | Non dovrebbe: la sessione è nel profilo del browser in `/dati/browser`. Controlla che `/dati` sia un volume persistente e non sia stato cancellato; riferisci il caso (è la voce S3 di [Ipotesi da verificare](Ipotesi-da-verificare)) | @@ -76,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 | | 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: «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)) | | 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 | diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index 5bd361e..5016ac9 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -17,16 +17,19 @@ copia altrove. ### La sessione salvata (raccolta «richieste») Con la raccolta «richieste» (`FEBE_RACCOLTA`, `--raccolta`) «Ho finito» copia la sessione del browser in -`sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe. Con Instagram, per ora, non -succede: la copia si accende solo quando ci sono richieste configurate. +`sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe; la copia si fa anche quando chiudi +la finestra del browser su Windows e quando la guida del browser finisce da sola (vedi +[Primo collegamento](Primo-collegamento)). Con Instagram, per ora, non succede: la copia si accende solo quando ci sono +richieste configurate. - Il file è **cifrato**. Su Windows con la protezione dei dati di Windows (DPAPI) per il tuo utente: lo apre solo il tuo utente su quel computer. In Docker con AES-256 e una chiave che sta in `FEBE_CHIAVE_SESSIONE`, se la imposti, o nel file `/dati/sessione/chiave.bin`, creato da Febe e leggibile solo dal proprietario. **Con la chiave dentro `/dati`, chi ha `/dati` ha anche la sessione**: se vuoi che una copia di `/dati` da sola non basti, metti la chiave in `FEBE_CHIAVE_SESSIONE` (`openssl rand -base64 32`) e tienila fuori dai backup di `/dati`. -- Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia. Febe non la esporta e - non accetta sessioni incollate da fuori. Nei registri ci sono solo conteggi e nomi, mai valori. +- Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia: la pagina Collegamento + ne mostra solo la data, i conteggi e i nomi dei valori che mancano. Febe non la esporta e non accetta sessioni + incollate da fuori. Nei registri ci sono solo conteggi e nomi, mai valori. - Se cambi la chiave, o il file si rovina, Febe la tratta come assente e lo scrive nel registro: basta rifare l'accesso. «Scollega» la cancella. - Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser, Xvfb, diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 9dd2176..7e2dabe 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -9,8 +9,15 @@ framework né fase di build. La specifica è `docs/SPECIFICA.md`; le scelte pres - **Nessuna prova, script o verifica contatta Instagram** (né Meta, né il loro CDN): si usa solo il sito di prova locale. Le prove dal vivo le lancia Alberto. Lo stesso vale per **Telegram**: le prove usano un gestore HTTP finto, mai `api.telegram.org`. -- **Dipendenze a elenco chiuso** (`Directory.Packages.props`): Microsoft.Data.Sqlite, SkiaSharp (con le librerie native - per Linux), Microsoft.Web.WebView2, MSTest. Tutto il resto viene dalla libreria di base di .NET. +- **Niente componenti esterni** (decisioni del 18 novembre 2026, specifica §2 regola 13 e §3): niente ffmpeg, + programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro + 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 + 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: 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. ## Com'è fatto il repository @@ -198,7 +205,8 @@ richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correz - `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in tutta la storia (gitleaks); - `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in - un contenitore Debian con Chromium, Xvfb, ffmpeg, NSIS e Node veri: nessuna prova si salta; + un contenitore Debian con Chromium e Xvfb veri, più ffmpeg (fino alla tappa C3 del traguardo 0.3.0), NSIS e + Node (fino alla tappa C6): nessuna prova si salta; - `installatore`: `Febe-Setup--ci..exe` e lo zip portabile, fra gli artefatti per 14 giorni; - `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-`. Alla fine si toglie diff --git a/docs/processo.md b/docs/processo.md index 5a42f53..a6bc90b 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -87,8 +87,8 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget | Lavoro | Quando | Che cosa garantisce | |---|---|---| | `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) | -| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie`) con Chromium della distribuzione, Xvfb, ffmpeg, NSIS, Node e la lingua italiana: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) | -| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup--ci..exe` e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni | +| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie` fino alla tappa C6 del traguardo 0.3.0, poi un'immagine Debian senza Node) con Chromium della distribuzione, Xvfb e la lingua italiana, più ffmpeg (fino alla tappa C3, regola 13), NSIS e Node (fino alla tappa C6): tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) | +| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup--ci..exe` (con NSIS fino alla tappa C6, poi con l'installatore scritto in casa) e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni | | `immagine` | dopo `installatore` (così `:main` e `:sha-` escono solo da un commit con tutta la verifica verde) | l'immagine si costruisce con buildx (dentro girano compilazione e prove), il contenitore parte **senza rete** come dice la guida e diventa «healthy», Chromium e la lingua italiana ci sono, si ferma entro 30 secondi; Trivy 0.75.0 non trova vulnerabilità CRITICAL con correzione disponibile. Solo dopo un push su `main`: pubblicazione `:main` e `:sha-` | La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un @@ -253,8 +253,11 @@ lavoro. `sicurezza-immagine` (`trivy.json`) e, se riguardano ciò che Febe usa, diventano una segnalazione. Un'eccezione si scrive solo in `.trivyignore`, alla radice: l'identificativo con una scadenza (`CVE-AAAA-NNNN exp:AAAA-MM-GG`, al massimo 90 giorni) e, sulla riga sopra, il motivo e chi l'ha deciso. -- Strumenti: gitleaks e Trivy sono gli unici strumenti esterni della CI, approvati da Alberto, e girano solo nella - CI. Si aggiornano cambiando versione e impronta SHA-256 in `.gitea/scripts/strumento.sh`, in una richiesta di +- Strumenti: gitleaks e Trivy sono gli unici strumenti esterni ammessi nella CI, approvati da Alberto, e girano solo + lì (regola 13 della specifica, decisioni del 18 novembre 2026). Nel contenitore delle prove restano solo Chromium, i + pacchetti Debian che gli servono e Xvfb. ffmpeg esce con la tappa C3; NSIS (al suo posto l'installatore scritto in + casa) e Node (al posto delle azioni che lo vogliono, passi di shell con git e curl verso l'API di Gitea) escono con + la tappa C6. Si aggiornano cambiando versione e impronta SHA-256 in `.gitea/scripts/strumento.sh`, in una richiesta di unione con una riga in `docs/decisioni.md`, preferendo versioni uscite da almeno due settimane. ## Rilasci @@ -282,7 +285,7 @@ lavoro. Qui non ci sono runner né demone Docker: i flussi sono stati controllati come testo (struttura, espressioni, `bash -n` di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere alla prima esecuzione: il contenitore -`node:24-trixie` con le azioni dentro; le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3` +`node:24-trixie` con le azioni dentro (fino alla tappa C6); le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3` con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia; la pubblicazione su `main` con il segreto. diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md index d61b471..c35b30c 100644 --- a/docs/prove-dal-vivo.md +++ b/docs/prove-dal-vivo.md @@ -519,3 +519,30 @@ Gli avvisi sono gli stessi nelle due vesti (stessa composizione); su Windows arr - Nel contenitore su Unraid: il risultato di «Invia una prova» (dice se il contenitore raggiunge Telegram). - Su Windows (D4): «sì/no» per la notifica di prova e per quella della verifica; se manca, la riga `[avvisi]` del registro di quell'ora. + +--- + +## E. Prima di configurare un'operazione di Instagram per richieste (issue #36) + +Le dieci operazioni di `richieste.instagram.json` restano non configurate finché queste ipotesi non sono confermate +dal vivo (oltre a H21 e H22 di §6.6 e alle fonti ancora `pending`). Non serve Febe: bastano gli strumenti per +sviluppatori del tuo browser di tutti i giorni, con la stessa preparazione di A ter 1 e A ter 2 (filtro «Tutti»). +**Non mandare valori**: solo «sì/no», «uguali/diversi» e i nomi. + +### E1. H23 — `__spin_r`, `__spin_b`, `__spin_t` + +Il catalogo (decisione del 18 novembre 2026) li copia dalla pagina come `SiteData.__spin_r`, `SiteData.__spin_b` e +`SiteData.__spin_t`. Il nome viene solo dalla forma del codice pubblico della pagina nel HAR: nessun campione ripulito +lo documenta, e nemmeno chi li mette nella richiesta. + +1. Apri la pagina iniziale di Instagram con il pannello Rete aperto, poi un profilo. +2. Nel pannello Rete usa «Cerca» (la lente, cerca in tutte le risposte) con `__spin_r`. Deve comparire nel documento + della pagina, dentro un blocco `SiteData`. Annota il nome esatto della chiave (con i due trattini bassi o senza), + e lo stesso per `__spin_b` e `__spin_t`. +3. Apri una richiesta `graphql/query` del profilo, scheda «Payload»: annota se ci sono i campi `__spin_r`, + `__spin_b`, `__spin_t` e se i loro valori sono **uguali** a quelli del blocco `SiteData` del documento (solo + «uguali/diversi»). +4. Ricarica la pagina e ripeti il passo 3: annota se i valori cambiano da una pagina all'altra. + +Che cosa riferire: i tre nomi esatti, «sì/no» per ciascun campo nella richiesta, «uguali/diversi» e «cambiano/non +cambiano». Se i nomi sono diversi, il catalogo va corretto prima di configurare qualunque operazione. diff --git a/docs/windows.md b/docs/windows.md index 086373c..aa298d1 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -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 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, -WebView2Loader). Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale. +`Febe.exe` è un file solo (circa 86 MB, misurato di nuovo senza SkiaSharp): contiene il runtime .NET, l'interfaccia +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 @@ -224,12 +225,13 @@ installer/costruisci.sh 0.2.0 # oppure una versione esplicita ``` Il risultato è in `out/`: `Febe-Setup-.exe` e `Febe--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 -controlla che la pubblicazione abbia prodotto un solo file e che nulla superi il limite. Lo script NSIS è +(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB; senza +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=…`). 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`. ## Prove automatiche su Windows diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs index 5bee24e..4e63058 100644 --- a/src/Febe.App/BrowserConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -4,6 +4,7 @@ using Febe.Browser.Hosting; using Febe.Browser.Session; using Febe.Core.Abstractions; using Febe.Core.Collection; +using Febe.Core.Collection.Requests; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; @@ -40,6 +41,16 @@ namespace Febe.App; /// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only /// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega». /// +/// +/// With a saved session (issue #36, S4b) the session is copied at «Ho finito», and also when Alberto lets go of the +/// browser without it: the window «Browser di Febe» closed on Windows (), the page +/// of the browser left in Docker (, : after +/// without a view open again, answer of 25 November 2026) and the lease of «Accedi» / +/// «Usa il browser» ending by itself. «Annulla» never copies. Always before the page goes back to the engine, with the +/// same guarantees as «Ho finito» (the driving gate held, the page's turn), and only from a page of the site that is +/// not a login or verification page. «Collegato» then also needs a readable saved session: without one the state is +/// («Serve «Ho finito»») and the engine waits. +/// /// public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable { @@ -55,6 +66,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa /// How often the cookie is looked at in the background (outside sessions it is the only way to notice). public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30); + /// How the log names leaving the page of the browser in Docker (answer of 25 November 2026). + private const string PageLeftText = "Pagina del browser lasciata"; + private readonly IFebeBrowser _browser; private readonly IFebeStorage _storage; private readonly BrowserUseTracker _tracker; @@ -74,6 +88,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa private bool? _connected; private bool? _disconnectedByUser; private DateTimeOffset _checkedAt = DateTimeOffset.MinValue; + private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue; + private SessionCopyOutcome? _letGoCopy; + private DateTimeOffset? _leftAt; /// The browser of Febe. /// The database (first connection, «Scollega»). @@ -119,6 +136,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } + /// + /// True when the composition keeps a saved session (raccolta «richieste») and there is no readable one: the cookie + /// alone is not «Collegato», the copy of «Ho finito» is missing (issue #36, S4b, answer 6). + /// + public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present; + + /// + /// Whether the engine may collect (): the session cookie is in the browser + /// and, with a saved session, a readable copy of it is there too. + /// + public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing; + + /// + /// How long a copy when Alberto closes the browser window waits, at most, for the commands of the connection and for + /// the copy itself (real time); then it gives up and the window gives the page back. Tests shorten it. + /// + public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30); + /// /// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the /// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection @@ -140,6 +175,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa /// public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2); + /// + /// How long after Alberto left the page of the browser in Docker (, or its remote view + /// closed by the page: ) no view may open again before Febe takes it as letting go of + /// the browser (answer of 25 November 2026, proposal of 5 seconds): a reload of the page opens its view again well + /// before. Read at every look; tests shorten it. + /// + public TimeSpan PageLeaveGrace { get; set; } = TimeSpan.FromSeconds(5); + /// /// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every /// wait; tests shorten it. @@ -161,6 +204,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected ? ConnectionState.VerificationRequired : await CheckAsync(force: false, mayReport: true, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected; + var saved = _copier?.Report(); + if (state == ConnectionState.Connected && saved is not null && saved.State != SavedSessionState.Present) + { + state = ConnectionState.SessionCopyMissing; + } Account? mine = null; if (state != ConnectionState.NotConnected) @@ -168,7 +216,55 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false); } - return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false)); + return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false), ToStatus(saved)); + } + + /// + /// The window «Browser di Febe» was closed by Alberto without «Ho finito», or left minimised too long (Windows, issue + /// #36, S4b, answer 5): the session is copied while the page is still his. The caller (the window) holds the driving + /// gate until this returns, so the page goes back to the engine only afterwards. Gives up after + /// . Never throws for the browser; logs counts only, and says which of the two happened. + /// + public async Task CopyOnWindowClosedAsync(BrowserWindowLetGo how, CancellationToken ct) + { + var what = how == BrowserWindowLetGo.MinimizedTooLong ? "Finestra del browser ridotta a icona troppo a lungo" : "Finestra del browser chiusa"; + if (_copier is null) + { + return; + } + + if (!_browser.IsAvailable) + { + // A letting go that copies nothing: a late «Ho finito» must not report a copy of an earlier one. + ForgetLetGoCopy(); + return; + } + + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + limit.CancelAfter(LetGoWait); + try + { + await _commands.WaitAsync(limit.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (limit.IsCancellationRequested) + { + ForgetLetGoCopy(); + _log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso."); + return; + } + catch (ObjectDisposedException) + { + return; // Febe is stopping + } + + try + { + await CopyOnLetGoAsync(what, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false); + } + finally + { + ReleaseCommands(); + } } public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) @@ -181,6 +277,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa { if (_lease is null) { + // A new use of the browser: what an earlier one copied when it let go is no longer this one's. + _letGoCopy = null; _lease = _browser.UserDriving.Begin(); var watch = new CancellationTokenSource(); _leaseWatch = watch; @@ -189,6 +287,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } _lastDrivingSign = _clock.Now; + + // Alberto is back (a reload of the page left a moment ago): not a letting go. + _leftAt = null; } _tracker.MarkUsed(_clock.Now); @@ -313,6 +414,52 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } + /// + /// Docker (answer of 25 November 2026): the page of the browser was left without «Ho finito» or «Annulla». Nothing + /// happens at once — a reload opens the page, «Usa il browser» and the view again within a moment. The watch of the + /// lease lets go of the browser once, for after this and after the last view closed, no + /// view is open and no «Accedi» / «Usa il browser» came: the copy of the session as when the window is closed on + /// Windows, then the lease ends and the page goes back to the engine (which puts it to rest). + /// + public Task LeavePageAsync(CancellationToken ct) + { + if (NoteLeft()) + { + _log.Info("collegamento", $"Pagina del browser lasciata senza «Ho finito» né «Annulla»: se entro {ItalianText.Duration(PageLeaveGrace)} non torni al browser, Febe copia la sessione e il motore può riprendere."); + } + + return Task.CompletedTask; + } + + /// + /// Docker: a remote view was closed by its page (the page left, the tab closed, the link lost; not another view taking + /// its place, nor Febe stopping). While the lease of «Accedi» / «Usa il browser» holds it counts as leaving the page + /// (): the last view closed, the moment starts again from now. + /// + public void RemoteViewClosed() + { + // The browser gone: its view closed with it, Alberto did not leave (the page opens it again once it is back). + if (_browser.IsAvailable) + { + NoteLeft(); + } + } + + /// Notes that Alberto may have left the browser; false without the lease of «Accedi» / «Usa il browser». + private bool NoteLeft() + { + lock (_gate) + { + if (_lease is null) + { + return false; + } + + _leftAt = _clock.Now; + return true; + } + } + public async Task FinishAsync(CancellationToken ct) { await _commands.WaitAsync(ct).ConfigureAwait(false); @@ -320,7 +467,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa { if (!_browser.IsAvailable) { - ReleaseLease(); + EndUseWithHoFinito(); return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro."); } @@ -330,10 +477,10 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false); // The copy for the site client (S4): while the page still holds the session and is still Alberto's. - var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : null; + var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : default; await RestIfAlbertosAsync().ConfigureAwait(false); await HideQuietlyAsync().ConfigureAwait(false); - ReleaseLease(); + EndUseWithHoFinito(); var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected; string message; @@ -354,9 +501,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione."; } - if (copy is not null) + if (copy.Outcome is { } outcome) { - message += " " + CopyMessage(copy); + message += " " + CopyMessage(outcome, copy.Earlier); } _log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser."); @@ -634,9 +781,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa while (true) { var grace = DrivingGrace; - var poll = TimeSpan.FromTicks(Math.Clamp(grace.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks)); + var leaveGrace = PageLeaveGrace; + var shortest = leaveGrace < grace ? leaveGrace : grace; + var poll = TimeSpan.FromTicks(Math.Clamp(shortest.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks)); await _clock.Delay(poll, ct).ConfigureAwait(false); DateTimeOffset lastSign; + DateTimeOffset? leftAt; lock (_gate) { if (!ReferenceEquals(_lease, lease)) @@ -651,11 +801,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } lastSign = _lastDrivingSign; + leftAt = _leftAt; } - if (_clock.Now - lastSign >= grace && ReleaseLease(lease)) + // Docker: the page of the browser left, or its last view closed by the page, and for a moment nothing came + // back (answer of 25 November 2026). Otherwise the long wait of a lease nobody uses. + var now = _clock.Now; + var left = leftAt is { } at && now - (at > lastSign ? at : lastSign) >= leaveGrace; + if (!left && now - lastSign < grace) { - _log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere."); + continue; + } + + // Before the page goes back to the engine: the copy of the session (S4b, answer 5; leaving the page in + // Docker, answer of 25 November 2026). + var what = left ? PageLeftText : "Fine della guida del browser"; + if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, what, ct).ConfigureAwait(false)) + { + continue; + } + + // The copy may have lasted long (the page's turn, the browser, the database): the remote view, the window + // or «Accedi» / «Usa il browser» may have come back meanwhile. Looked at again in the same step that ends + // the lease, so that nothing slips in between. + if (ReleaseIdleLease(lease, lastSign)) + { + _log.Info("collegamento", left + ? $"{PageLeftText}: nessuna vista del browser riaperta, il motore può riprendere." + : $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere."); return; } } @@ -664,6 +837,205 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa { // The lease ended with a command of Alberto. } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Whatever failed, the lease must not hold the engine still for ever (rule 10: the kind of error only). + _log.Warn("collegamento", $"Controllo della fine della guida del browser interrotto da un errore ({ex.GetType().Name}): il motore può riprendere."); + ReleaseLease(lease); + } + } + + /// + /// The copy when the lease of «Accedi» / «Usa il browser» is about to end by itself (S4b, answer 5), while it still + /// holds. Not when a copy was already made since the last sign that Alberto used the browser (the window closed a + /// moment before): the window's own hold lasts a moment after its copy, so a sign within one look + /// () of the copy is that hold, not Alberto. False when the lease must not end now: a sign of + /// driving came while the copy waited for its turn. + /// + private async Task CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, string what, CancellationToken ct) + { + if (_copier is null) + { + return true; + } + + lock (_gate) + { + if (_lastCopyAt != DateTimeOffset.MinValue && _lastCopyAt >= lastSign - poll) + { + return true; + } + } + + // Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide. + try + { + await _commands.WaitAsync(ct).ConfigureAwait(false); + } + catch (ObjectDisposedException) + { + return true; // Febe is stopping + } + + try + { + bool StillAlbertos() + { + lock (_gate) + { + return ReferenceEquals(_lease, lease); + } + } + + if (!StillAlbertos()) + { + return true; + } + + if (_browser.UserDriving.Leases > 1) + { + // The remote view or the window came back while this waited: the lease goes on. + lock (_gate) + { + _lastDrivingSign = _clock.Now; + } + + return false; + } + + await CopyOnLetGoAsync(what, StillAlbertos, ct).ConfigureAwait(false); + return true; + } + finally + { + ReleaseCommands(); + } + } + + /// + /// The copy when Alberto lets go of the browser without «Ho finito»: only while the page is still his, only when the + /// browser holds the session, with the driving gate held and the page's turn, like «Ho finito». The copier refuses a + /// page off the site or a login or verification page. One log line with the outcome (counts only). + /// + private async Task CopyOnLetGoAsync(string what, Func stillAlbertos, CancellationToken ct) + { + try + { + if (!_browser.UserIsDriving) + { + _log.Info("collegamento", $"{what}: sessione non copiata, il browser era già tornato al motore."); + return; + } + + // The last time this use of the browser let go decides what a late «Ho finito» says: a copy that does not + // happen now (no session, the page busy, refused, an error) forgets one made at an earlier letting go. + ForgetLetGoCopy(); + + if (await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) != true) + { + _log.Info("collegamento", $"{what}: nessuna sessione nel browser, niente da copiare."); + return; + } + + var hold = _browser.UserDriving.Begin(); + try + { + const string PageBusy = "sessione non copiata, la pagina era occupata dalla ricerca dei profili"; + PageTurn? taken; + try + { + taken = await TakePageAsync(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // The time of the letting go ran out while a step of the search held the page: not the browser's fault. + _log.Info("collegamento", $"{what}: {PageBusy}."); + return; + } + + using var turn = taken; + if (_engine is not null && turn is null) + { + _log.Info("collegamento", $"{what}: {PageBusy}."); + return; + } + + var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false); + lock (_gate) + { + _lastCopyAt = _clock.Now; + if (outcome.Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly or SessionCopyStatus.KeptComplete) + { + // A late «Ho finito» of this use says that the session was already copied (S4b). + _letGoCopy = outcome; + } + } + + _log.Info("collegamento", $"{what}: {LetGoSummary(outcome)}."); + } + finally + { + hold.Dispose(); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + _log.Info("collegamento", $"{what}: sessione non copiata, il browser non ha risposto in tempo."); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // The database, the disk, Febe stopping: never the lease held for ever because of it. The kind of error only + // (rule 10): the page and the saved session hold what the session holds. + _log.Warn("collegamento", $"{what}: copia della sessione non riuscita per un errore ({ex.GetType().Name})."); + } + } + + /// What a copy without «Ho finito» did, for the log (counts only). + internal static string LetGoSummary(SessionCopyOutcome copy) + { + ArgumentNullException.ThrowIfNull(copy); + var missing = copy.MissingValues + copy.MissingDocIds; + var clause = missing == 0 ? string.Empty : ", ma " + MissingNeeded(missing, past: false); + return copy.Status switch + { + SessionCopyStatus.Saved => "sessione copiata" + clause, + SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause, + SessionCopyStatus.KeptComplete => $"copia incompleta ({ItalianText.Count(missing, "valore mancante", "valori mancanti")}), resta quella completa salvata prima", + SessionCopyStatus.Discarded => "sessione letta ma non salvata, il browser era tornato al motore", + _ => $"sessione non copiata, {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}; la sessione salvata resta com'era", + }; + } + + /// The saved session for the interface, in counts and names; null without a saved session in this start. + private static SavedSessionStatus? ToStatus(SavedSessionReport? report) => report is null + ? null + : new SavedSessionStatus( + report.State switch + { + SavedSessionState.Present => SavedSessionStatus.Present, + SavedSessionState.Unreadable => SavedSessionStatus.Unreadable, + _ => SavedSessionStatus.None, + }, + report.CopiedAt, + report.Cookies, + report.ValuesPresent, + report.ValuesExpected, + report.MissingValues, + report.DocIdsPresent, + report.DocIdsExpected, + report.MissingDocIds, + report.NeededMissing); + + private void ReleaseCommands() + { + try + { + _commands.Release(); + } + catch (ObjectDisposedException) + { + // Febe stopped while the copy ran. + } } /// The first connection ever starts the gradual start (spec §7.2). True when it was the first. @@ -736,22 +1108,35 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa /// The copy at «Ho finito» (issue #36, S4, §6.0): only while Alberto's own lease («Accedi», «Usa il browser») still /// holds — after it ended the page is the engine's, and nothing is read from it (rule 7). A hold of the driving gate /// keeps the lease from ending by itself meanwhile, and the page turn keeps a step of the profile search off the - /// page; a lease that ended all the same before the copy is saved throws the copy away. + /// page; a lease that ended all the same before the copy is saved throws the copy away. A late «Ho finito», after + /// this use of the browser already copied when it let go (S4b), reads nothing and reports that earlier copy + /// (Earlier), as long as the saved session is still there. /// - private async Task CopySessionAsync(CancellationToken ct) + private async Task<(SessionCopyOutcome? Outcome, bool Earlier)> CopySessionAsync(CancellationToken ct) { IDisposable? lease; + SessionCopyOutcome? earlier; lock (_gate) { lease = _lease; + earlier = _letGoCopy; } if (lease is null || !_browser.UserIsDriving) { + if (earlier is not null && _copier!.SavedState == SavedSessionState.Present) + { + _log.Info("collegamento", "«Ho finito»: sessione non copiata di nuovo, era già stata copiata quando il browser è tornato al motore."); + return (earlier, true); + } + _log.Info("collegamento", "«Ho finito»: sessione non copiata, il browser era già tornato al motore."); - return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0); + return (new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0), false); } + // «Ho finito» copies again: from now on its own outcome is what a later «Ho finito» refers to, not an earlier copy + // made when the browser was let go (that copy may be of another login). + ForgetLetGoCopy(); var hold = _browser.UserDriving.Begin(); try { @@ -759,7 +1144,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa if (_engine is not null && turn is null) { _log.Info("collegamento", "«Ho finito»: sessione non copiata, la pagina era occupata dalla ricerca dei profili."); - return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0); + return (new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0), false); } bool StillAlbertos() @@ -770,7 +1155,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } - return await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false); + return (await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false), false); } finally { @@ -782,25 +1167,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa /// The clause of the «Ho finito» message about the copy, in Italian (counts only). It says what the code does: a /// value a configured operation needs and the page did not give stops that request as a disconnection (§6.0), never /// a way back to the browser; and after a refusal a new «Ho finito» needs the browser opened again, because - /// «Ho finito» always ends the lease. + /// «Ho finito» always ends the lease. With the copy is the one made a moment before, when + /// the browser went back to the engine without «Ho finito» (S4b): the message says so, and never asks for a new login + /// when that copy is complete. /// - internal static string CopyMessage(SessionCopyOutcome copy) + internal static string CopyMessage(SessionCopyOutcome copy, bool earlier = false) { ArgumentNullException.ThrowIfNull(copy); + const string Before = "La sessione per le richieste era già stata copiata quando il browser è tornato al motore"; const string Again = "Riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale."; var missing = copy.MissingValues + copy.MissingDocIds; + var needed = MissingNeeded(missing, past: true); var missingClause = missing == 0 ? string.Empty - : string.Create( - CultureInfo.InvariantCulture, - $" Alla pagina però mancavano {missing} valori che servono alle richieste: la copia ha comunque sostituito quella salvata prima, e le richieste che li usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}"); + : $" Alla pagina però {needed}: la copia ha comunque sostituito quella salvata prima, e le richieste che {(missing == 1 ? "lo" : "li")} usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}"; return copy.Status switch { + SessionCopyStatus.Saved when earlier => Before + "." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause), + SessionCopyStatus.SavedInMemoryOnly when earlier => + Before + ", ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause), + SessionCopyStatus.KeptComplete when earlier => + $"Quando il browser è tornato al motore alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}", SessionCopyStatus.Saved => "Sessione copiata per le richieste di Febe." + missingClause, SessionCopyStatus.SavedInMemoryOnly => "Sessione copiata per le richieste di Febe, ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + missingClause, SessionCopyStatus.Discarded => "La sessione per le richieste non è stata copiata: nel frattempo il browser era tornato al motore. Rifai l'accesso dalla pagina Collegamento e premi «Ho finito» sulla tua pagina iniziale.", + SessionCopyStatus.KeptComplete => + $"Alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima e non usa quella nuova. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}", _ when copy.Refusal is CaptureRefusal.NotOnSite or CaptureRefusal.CheckpointPage => $"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal.Value)}. La sessione salvata resta com'era. {Again}", _ => @@ -808,6 +1202,17 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa }; } + /// + /// «mancano 3 valori che servono alle richieste», «manca 1 valore che serve alle richieste» (: + /// «mancava», «mancavano»): the count with the Italian singular. + /// + internal static string MissingNeeded(int missing, bool past) + { + var one = missing == 1; + var verb = past ? (one ? "mancava" : "mancavano") : (one ? "manca" : "mancano"); + return $"{verb} {ItalianText.Count(missing, "valore", "valori")} che {(one ? "serve" : "servono")} alle richieste"; + } + /// «Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any. private async Task ForgetSavedSessionAsync() { @@ -938,6 +1343,27 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } + /// Forgets the copy made when this use of the browser was let go (S4b): it no longer answers a late «Ho finito». + private void ForgetLetGoCopy() + { + lock (_gate) + { + _letGoCopy = null; + } + } + + /// + /// «Ho finito» ends the lease. When it ends one, that use of the browser is over: a further «Ho finito» (a double + /// click, a second tab) must not report a copy made when that use was let go earlier. + /// + private void EndUseWithHoFinito() + { + if (ReleaseLease()) + { + ForgetLetGoCopy(); + } + } + /// Ends the lease (only , when given). True when a lease ended. private bool ReleaseLease(IDisposable? expected = null) { @@ -950,12 +1376,56 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa return false; } - lease = _lease; - watch = _leaseWatch; - _lease = null; - _leaseWatch = null; + (lease, watch) = TakeLeaseLocked(); } + return EndLease(lease, watch); + } + + /// + /// Ends by itself only if, in the same look, it is still the only lease of the browser and + /// no sign that Alberto uses the browser came after : another lease (the remote view, the + /// window, a hold of the connection) is a sign now. True when the lease ended. + /// + private bool ReleaseIdleLease(IDisposable expected, DateTimeOffset lastSign) + { + IDisposable? lease; + CancellationTokenSource? watch; + lock (_gate) + { + if (!ReferenceEquals(_lease, expected)) + { + return false; + } + + if (_browser.UserDriving.Leases > 1) + { + _lastDrivingSign = _clock.Now; + return false; + } + + if (_lastDrivingSign > lastSign) + { + return false; + } + + (lease, watch) = TakeLeaseLocked(); + } + + return EndLease(lease, watch); + } + + private (IDisposable? Lease, CancellationTokenSource? Watch) TakeLeaseLocked() + { + var taken = (_lease, _leaseWatch); + _lease = null; + _leaseWatch = null; + _leftAt = null; + return taken; + } + + private static bool EndLease(IDisposable? lease, CancellationTokenSource? watch) + { if (watch is not null) { watch.Cancel(); diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index 81034e2..a3d17a8 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -261,7 +261,16 @@ public sealed class FebeApp : IAsyncDisposable // Browser, connection, engine. The engine loop starts only once the browser is up. // «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed. - var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask); + // The copy when Alberto closes the browser window (S4b) is the connection's too, looked up when it happens. + var context = new FebePlatformContext( + o, + data, + Database, + Clock, + Log, + Tracker, + ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask, + (how, ct) => Connection?.CopyOnWindowClosedAsync(how, ct) ?? Task.CompletedTask); var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false); Browser = browser; PrepareSavedSession(context, browser); @@ -286,8 +295,9 @@ public sealed class FebeApp : IAsyncDisposable random, engineOptions, userIsDriving: () => browser.UserIsDriving, - isConnected: () => connection.IsConnected == true, - ct: ct).ConfigureAwait(false); + isConnected: () => connection.IsReadyToCollect, + ct: ct, + sessionCopyMissing: () => connection.IsConnected == true && connection.SessionCopyMissing).ConfigureAwait(false); // The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the // capture sees goes to the session in progress, if any. var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock)); @@ -500,9 +510,7 @@ public sealed class FebeApp : IAsyncDisposable InBackground(() => Connection.RunAsync(ct)); await engine.StartAsync(ct).ConfigureAwait(false); - Log.Info("motore", Connection.IsConnected == true - ? "Motore avviato: il browser è collegato." - : "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»)."); + Log.Info("motore", StartedMessage(Connection)); _running.TrySetResult(); } catch (OperationCanceledException) when (ct.IsCancellationRequested) @@ -576,10 +584,15 @@ public sealed class FebeApp : IAsyncDisposable var protector = _platform.CreateSessionProtector(context); var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message)); var rules = LoadSignalRules(context.Data); - _copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message)); + var settings = context.Storage.Settings; + _copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message)) + { + // What an incomplete copy does (S4b): read at every copy, so a change on the Collegamento page holds at once. + IncompleteCopy = async token => (await SessionCopySettings.LoadAsync(settings, token).ConfigureAwait(false)).IncompleteCopy, + }; _requestCatalog = catalog; SavedSession = saved; - Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito»."); + Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito», alla chiusura della finestra del browser e alla fine della guida."); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException) { @@ -665,6 +678,24 @@ public sealed class FebeApp : IAsyncDisposable } } + /// + /// The start-up line of the engine, with what it waits for: the same state as the engine's own gate + /// (), so that the log never says «collegato» while the monitor + /// says «Serve «Ho finito»». + /// + internal static string StartedMessage(BrowserConnectionService connection) + { + ArgumentNullException.ThrowIfNull(connection); + if (connection.IsReadyToCollect) + { + return "Motore avviato: il browser è collegato."; + } + + return connection.IsConnected == true && connection.SessionCopyMissing + ? "Motore avviato: il browser è collegato, ma aspetta la copia della sessione per le richieste (pagina Collegamento, «Ho finito»)." + : "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»)."; + } + /// The site's home page as the browser writes it (with its final slash), for «Pagina iniziale». private static string HomeUrl(string baseUrl) => Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl; diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs index 0b43683..0187a55 100644 --- a/src/Febe.App/IFebePlatform.cs +++ b/src/Febe.App/IFebePlatform.cs @@ -72,7 +72,23 @@ public interface IFebePlatform /// the login page otherwise, once the engine's session ended and with the page's turn /// (BrowserConnectionService.OpenStartPageAsync). Null: the button does nothing. /// -public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? OpenStartPage = null); +/// +/// What closing the browser window (or leaving it minimised too long) does before the page goes back to the engine +/// (issue #36, S4b): the connection copies the session into the saved session, when there is one +/// (BrowserConnectionService.CopyOnWindowClosedAsync). The window holds the driving gate until the task ends. +/// Null: nothing. +/// +public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? OpenStartPage = null, Func? CopyOnWindowClosed = null); + +/// How Alberto let go of the window «Browser di Febe» without «Ho finito» (Windows): the log says which. +public enum BrowserWindowLetGo +{ + /// He closed it. + Closed, + + /// He left it minimised longer than its limit: it went out of view as if closed. + MinimizedTooLong, +} /// Options of the shared composition, filled by each shell from its own configuration. public sealed record FebeAppOptions diff --git a/src/Febe.App/SessionCopier.cs b/src/Febe.App/SessionCopier.cs index 0a9bc85..3815204 100644 --- a/src/Febe.App/SessionCopier.cs +++ b/src/Febe.App/SessionCopier.cs @@ -19,6 +19,12 @@ public enum SessionCopyStatus /// Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7). Discarded, + + /// + /// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose + /// «Tieni la copia completa» (). The saved session stays as it was. + /// + KeptComplete, } /// What a copy did, for the message of «Ho finito» and the tests. Never a value. @@ -34,11 +40,42 @@ public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal } /// -/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», and after the -/// automatic login of the test site. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e -/// sostituisce»), also when some value of the page is missing: the requests that send it then do not leave and stop -/// the engine as a disconnection until a new copy has it (never a way back to the pages). A refused copy leaves the -/// saved session as it is. +/// The saved session as the Collegamento page shows it (issue #36, S4b, answer 10): its state, when it was copied, how +/// many values of the page and doc_id it holds and the names of those it lacks. Counts and names only, never a value. +/// +/// Whether a saved session is there and can be read. +/// When the browser's session was copied; null without a session or when not known. +/// How many cookies it holds. +/// Values of the page it holds, of . +/// Values of the page the copy reads. +/// Names of the values of the page it lacks. +/// doc_id it holds, of . +/// doc_id the copy reads. +/// Operations whose doc_id it lacks. +/// How many of the missing values and doc_id a configured operation sends. +public sealed record SavedSessionReport( + SavedSessionState State, + DateTimeOffset? CopiedAt, + int Cookies, + int ValuesPresent, + int ValuesExpected, + IReadOnlyList MissingValues, + int DocIdsPresent, + int DocIdsExpected, + IReadOnlyList MissingDocIds, + int NeededMissing) +{ + /// True when a readable session is there and nothing a configured operation sends is missing. + public bool Complete => State == SavedSessionState.Present && NeededMissing == 0; +} + +/// +/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», after the +/// automatic login of the test site, and (S4b) when Alberto closes the browser window on Windows or his driving lease +/// ends by itself. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e sostituisce»), also when +/// some value of the page is missing — unless Alberto chose «Tieni la copia completa» and the saved one is complete. +/// The requests that send a missing value do not leave and stop the engine as a disconnection until a new copy has it +/// (never a way back to the pages). A refused copy leaves the saved session as it is. /// public interface ISessionCopier { @@ -48,6 +85,12 @@ public interface ISessionCopier /// Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's). /// Cancels the copy; nothing is saved then. Task CopyAsync(Func mayKeep, CancellationToken ct); + + /// Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often). + SavedSessionState SavedState { get; } + + /// The saved session now, in counts and names (the Collegamento page, «Collegato»). + SavedSessionReport Report(); } /// @@ -76,6 +119,12 @@ public sealed class BrowserSessionCopier : ISessionCopier _log = log ?? throw new ArgumentNullException(nameof(log)); } + /// + /// What an incomplete copy does, asked at every copy (the setting of the Collegamento page, + /// ); by default it replaces the saved session, as before. + /// + public Func> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace); + /// /// How long the reading may last before it counts as a browser error: «Ho finito» holds the commands of the /// connection meanwhile, so a browser that hangs must not hold them for ever (real time). @@ -110,24 +159,34 @@ public sealed class BrowserSessionCopier : ISessionCopier var counts = string.Create( CultureInfo.InvariantCulture, $"{result.Cookies} cookie ({result.DroppedCookies} scartati), {result.ExpectedValues - result.MissingValues.Count} valori della pagina su {result.ExpectedValues}, {result.ExpectedDocIds - result.MissingDocIds.Count} doc_id su {result.ExpectedDocIds}"); + // Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0). + var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList(); + var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList(); + var needed = neededValues.Concat(neededDocIds).ToList(); + var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList(); + + // An incomplete copy replaces the saved one (§6.0: an older copy could keep another login's cookies), unless + // Alberto chose to keep a complete one (answer 9 of 18 November 2026) and the saved one is complete. The choice + // is read before the last look at whose page it is, so that nothing awaited comes between that look and the write. + var keepComplete = needed.Count > 0 && IsComplete(_store.Read()) && await KeepsCompleteAsync().ConfigureAwait(false); + if (!mayKeep()) { _log($"Sessione letta ma non salvata: nel frattempo il browser è tornato al motore ({counts})."); return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count); } - // Not cancelled from here: the copy was made, and a half-written replacement is never left. It replaces the - // saved session also when a value is missing (§6.0): keeping an older copy could keep another login's cookies. - var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false); + if (keepComplete) + { + _log($"Sessione letta ma non salvata: {Missing(needed)}, che {(needed.Count == 1 ? "serve" : "servono")} alle operazioni configurate; come scelto, resta la copia completa salvata prima ({counts})."); + return new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, result.Cookies, neededValues.Count, neededDocIds.Count); + } - // Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0). - var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList(); - var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList(); - var needed = neededValues.Concat(neededDocIds).ToList(); - var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList(); + // Not cancelled from here: the copy was made, and a half-written replacement is never left. + var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false); _log($"Sessione copiata: {counts}" - + (needed.Count == 0 ? string.Empty : "; mancano " + string.Join(", ", needed) + ", che servono alle operazioni configurate") - + (unused.Count == 0 ? string.Empty : "; mancano anche " + string.Join(", ", unused) + ", che nessuna operazione configurata usa") + + (needed.Count == 0 ? string.Empty : "; " + Missing(needed) + ", che " + (needed.Count == 1 ? "serve" : "servono") + " alle operazioni configurate") + + (unused.Count == 0 ? string.Empty : "; " + Missing(unused, also: true) + ", che nessuna operazione configurata usa") + (onDisk ? string.Empty : "; non ancora scritta su disco") + "."); return new SessionCopyOutcome( @@ -138,6 +197,56 @@ public sealed class BrowserSessionCopier : ISessionCopier neededDocIds.Count); } + public SavedSessionState SavedState => _store.State; + + public SavedSessionReport Report() + { + var state = _store.State; + var values = state == SavedSessionState.Present ? _store.Read() : null; + if (values is null) + { + var none = state == SavedSessionState.Present ? SavedSessionState.None : state; + return new SavedSessionReport(none, null, 0, 0, _plan.Values.Count, [], 0, _plan.DocIds.Count, [], 0); + } + + var missingValues = new List(); + var needed = 0; + foreach (var read in _plan.Values) + { + if (!values.Fields.ContainsKey(read.Field)) + { + missingValues.Add(read.Field); + needed += _plan.NeededValues.Contains(read.Field) ? 1 : 0; + } + } + + var missingDocIds = new List(); + foreach (var read in _plan.DocIds) + { + if (!values.DocIds.ContainsKey(read.Field)) + { + missingDocIds.Add(read.Field); + needed += _plan.NeededDocIds.Contains(read.Field) ? 1 : 0; + } + } + + return new SavedSessionReport( + SavedSessionState.Present, + values.CopiedAt, + values.Cookies.Count, + _plan.Values.Count - missingValues.Count, + _plan.Values.Count, + missingValues, + _plan.DocIds.Count - missingDocIds.Count, + _plan.DocIds.Count, + missingDocIds, + needed); + } + + /// «manca app_id», «mancano hsi, rev» (with : «manca anche …»), for the log: names only. + private static string Missing(IReadOnlyList names, bool also = false) => + (names.Count == 1 ? "manca " : "mancano ") + (also ? "anche " : string.Empty) + string.Join(", ", names); + /// Why a copy was refused, in Italian. public static string Reason(CaptureRefusal refusal) => refusal switch { @@ -146,4 +255,49 @@ public sealed class BrowserSessionCopier : ISessionCopier CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent", _ => "il browser non ha risposto", }; + + /// + /// Whether Alberto chose «Tieni la copia completa». A choice that cannot be read (the database busy or failing) is + /// the default, «Sostituisci comunque»: the copy goes on, and «Ho finito» never fails because of the setting. The log + /// gets the kind of error only (rule 10). + /// + private async Task KeepsCompleteAsync() + { + try + { + return await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _log($"Scelta per la copia incompleta non letta ({ex.GetType().Name}): vale la predefinita, la copia sostituisce quella salvata."); + return false; + } + } + + /// True when holds every value and doc_id a configured operation sends. + private bool IsComplete(SiteSessionValues? saved) + { + if (saved is null) + { + return false; + } + + foreach (var field in _plan.NeededValues) + { + if (!saved.Fields.ContainsKey(field)) + { + return false; + } + } + + foreach (var operation in _plan.NeededDocIds) + { + if (!saved.DocIds.ContainsKey(operation)) + { + return false; + } + } + + return true; + } } diff --git a/src/Febe.Core/Codecs/Images/BmpDecoder.cs b/src/Febe.Core/Codecs/Images/BmpDecoder.cs new file mode 100644 index 0000000..64243dd --- /dev/null +++ b/src/Febe.Core/Codecs/Images/BmpDecoder.cs @@ -0,0 +1,502 @@ +using System.Buffers.Binary; +using System.Numerics; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +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; + + /// Whether the bytes start like a BMP file. + public static bool IsBmp(ReadOnlySpan data) => + data.Length >= 18 && data[0] == (byte)'B' && data[1] == (byte)'M' && ImageFormatSniffer.IsBmpHeaderSize(BinaryPrimitives.ReadUInt32LittleEndian(data[14..])); + + /// Size of a BMP, without decoding the pixels. + public static ImageInfo Identify(ReadOnlyMemory 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), + }; + } + + /// Decodes a BMP to straight RGBA8, top row first. + /// The file is damaged, truncated or not a BMP. + /// A BMP variant Febe does not read (JPEG inside, OS/2 Huffman, 64 bits). + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory 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; + } + } + + /// Decodes a BMP and returns what returns as well. + public static RgbaImage Decode(ReadOnlyMemory 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; + + /// RGBA of each palette index (256 entries; those the file does not give are opaque black). + public uint[]? Palette; + + public int Stride => (int)((((long)Width * BitsPerPixel) + 31) / 32 * 4); + } + + private static BmpHeader ReadHeader(ReadOnlySpan 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 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 red = stackalloc byte[256]; + Span green = stackalloc byte[256]; + Span blue = stackalloc byte[256]; + Span 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; + } + } + } + + /// + /// 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 . Wider masks keep their top 8 bits. + /// + private static (int Shift, int Bits) MaskShift(uint mask, Span 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 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 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; + } + } + } + } +} diff --git a/src/Febe.Core/Codecs/Images/Crc32.cs b/src/Febe.Core/Codecs/Images/Crc32.cs new file mode 100644 index 0000000..a64fc01 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Crc32.cs @@ -0,0 +1,72 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +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(); + + /// The CRC of . + public static uint Compute(ReadOnlySpan data) => Append(0, data); + + /// The CRC of the bytes already summed into followed by . + public static uint Append(uint crc, ReadOnlySpan 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; + } +} diff --git a/src/Febe.Core/Codecs/Images/ExifOrientation.cs b/src/Febe.Core/Codecs/Images/ExifOrientation.cs new file mode 100644 index 0000000..762d145 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ExifOrientation.cs @@ -0,0 +1,79 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.Images; + +/// Reads the Orientation tag (0x0112) of the first IFD of an EXIF block (a TIFF structure). +internal static class ExifOrientation +{ + private const ushort OrientationTag = 0x0112; + + /// + /// The orientation 1-8 of (starting with «II*\0» or «MM\0*»), or 1 when the block has no + /// such tag, an invalid value or is damaged. + /// + public static int Read(ReadOnlySpan 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 b, bool little) => + little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b); + + private static uint U32(ReadOnlySpan b, bool little) => + little ? BinaryPrimitives.ReadUInt32LittleEndian(b) : BinaryPrimitives.ReadUInt32BigEndian(b); +} diff --git a/src/Febe.Core/Codecs/Images/GifDecoder.cs b/src/Febe.Core/Codecs/Images/GifDecoder.cs new file mode 100644 index 0000000..f383eec --- /dev/null +++ b/src/Febe.Core/Codecs/Images/GifDecoder.cs @@ -0,0 +1,531 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +public static class GifDecoder +{ + private const int MaxCodeBits = 12; + private const int MaxCodes = 1 << MaxCodeBits; + + /// Whether the bytes start with a GIF signature. + public static bool IsGif(ReadOnlySpan data) => + data.Length >= 6 && data[..3].SequenceEqual("GIF"u8) && (data[3..6].SequenceEqual("89a"u8) || data[3..6].SequenceEqual("87a"u8)); + + /// Canvas size, frame count and comments of a GIF, without decoding the pixels. + public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null) + { + limits ??= ImageLimits.Default; + var file = Walk(data.Span, limits, countFrames: true); + return file.ToInfo(); + } + + /// Decodes the first frame of a GIF to straight RGBA8. + /// The file is damaged, has no frame or is not a GIF. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory 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); + } + + /// Decodes the first frame of a GIF and returns what returns as well. + public static RgbaImage Decode(ReadOnlyMemory 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? 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 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 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 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 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((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 colours = stackalloc uint[256]; + Span 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); + } + } + + /// The row of the image that the -th decoded row of an interlaced frame fills. + 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); + } + + /// + /// Decodes the LZW data sub-blocks that start at into (GIF89a + /// appendix F: variable-length codes from + 1 bits up to 12, least significant bit + /// first) and returns how many indices were written. A damaged stream stops the decoding there. + /// + internal static int DecodeLzw(ReadOnlySpan data, int pos, int minCodeSize, Span output) + { + var prefix = ArrayPool.Shared.Rent(MaxCodes); + var lengths = ArrayPool.Shared.Rent(MaxCodes); + var suffix = ArrayPool.Shared.Rent(MaxCodes); + var first = ArrayPool.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.Shared.Return(prefix); + ArrayPool.Shared.Return(lengths); + ArrayPool.Shared.Return(suffix); + ArrayPool.Shared.Return(first); + } + } +} diff --git a/src/Febe.Core/Codecs/Images/ImageBuffers.cs b/src/Febe.Core/Codecs/Images/ImageBuffers.cs new file mode 100644 index 0000000..50ab380 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageBuffers.cs @@ -0,0 +1,44 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// Working arrays of the codecs: from up to , plain arrays +/// above it. +/// +/// +/// 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. +/// +internal static class ImageBuffers +{ + /// Largest array, in bytes, taken from the shared pool (a power of two, so a pooled array never exceeds it). + public const int PooledBytes = 16 * 1024 * 1024; + + /// An array of at least elements, contents undefined. + public static T[] Rent(int length) + { + if ((long)length * Unsafe.SizeOf() <= PooledBytes) + { + return ArrayPool.Shared.Rent(length); + } + + return GC.AllocateUninitializedArray(length); + } + + /// Gives back an array from ; those above the threshold are left to the collector. + public static void Return(T[] array) + { + if ((long)array.Length * Unsafe.SizeOf() <= PooledBytes) + { + ArrayPool.Shared.Return(array); + } + } + + /// Whether of came from the shared pool. + public static bool IsPooled(T[] array) => (long)array.Length * Unsafe.SizeOf() <= PooledBytes; +} diff --git a/src/Febe.Core/Codecs/Images/ImageConverter.cs b/src/Febe.Core/Codecs/Images/ImageConverter.cs new file mode 100644 index 0000000..a0c7f6a --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageConverter.cs @@ -0,0 +1,274 @@ +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// Options of . +public sealed record ImageConversionOptions +{ + /// The options used when a caller passes none. + public static ImageConversionOptions Default { get; } = new(); + + /// Quality of a JPEG target (1-100): 92 by Alberto's choice for exports (decision of 18 November 2026). + public int JpegQuality { get; init; } = 92; + + /// Chroma of a JPEG target: full (4:4:4) by default, so that the converted picture loses as little as possible. + public JpegSubsampling JpegSubsampling { get; init; } = JpegSubsampling.Ratio444; + + /// What transparent areas become in a JPEG target, which has no alpha. + public Drawing.Color JpegBackground { get; init; } = Drawing.Color.White; + + /// Limits of the decoding of the source. + public ImageLimits Limits { get; init; } = ImageLimits.Default; +} + +/// What made. +/// The converted file. +/// The format of the source. +/// The format written. +/// Width as stored (the orientation is not applied: the tag is copied). +/// Height as stored. +/// +/// 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). +/// +/// The metadata written. +/// What of the source's metadata the target could not take, in Italian, for the interface. +public sealed record ImageConversionResult( + byte[] Data, + ImageFormat Source, + ImageFormat Target, + int Width, + int Height, + bool Lossy, + ImageMetadata Metadata, + IReadOnlyList NotCarried); + +/// +/// 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 . Animations keep their first frame +/// only, and say so. +/// +public static class ImageConverter +{ + /// The formats a conversion can write. + public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP; + + /// Converts (any format reads) to . + /// The target is not JPEG, PNG or WebP. + /// The source is damaged, too large or in a format Febe does not read. + public static ImageConversionResult Convert(ReadOnlyMemory 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(); + 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(); + 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); + } + + /// The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null. + internal static string? IccColorSpace(ReadOnlySpan profile) + { + if (profile.Length < 20) + { + return null; + } + + Span 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); + } + + /// Bytes of payload in one JPEG marker segment (65535 less the two of the length). + 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 PngTexts(IReadOnlyList texts, List notCarried) + { + var result = new List(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; + } +} + +/// Composites an image over a plain colour. +public static class ImageBackground +{ + /// Every pixel of seen over , opaque, in place. + 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; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/ImageDecodeException.cs b/src/Febe.Core/Codecs/Images/ImageDecodeException.cs new file mode 100644 index 0000000..5552866 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageDecodeException.cs @@ -0,0 +1,58 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +public class ImageDecodeException : Exception +{ + public ImageDecodeException() + { + } + + public ImageDecodeException(string message) + : base(message) + { + } + + public ImageDecodeException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// The image is well formed but larger than allows: it is not decoded. +public sealed class ImageLimitException : ImageDecodeException +{ + public ImageLimitException() + { + } + + public ImageLimitException(string message) + : base(message) + { + } + + public ImageLimitException(string message, Exception innerException) + : base(message, innerException) + { + } +} + +/// The format was recognised but Febe has no decoder for it (yet), or not for this variant of it. +public sealed class ImageFormatNotSupportedException : ImageDecodeException +{ + public ImageFormatNotSupportedException() + { + } + + public ImageFormatNotSupportedException(string message) + : base(message) + { + } + + public ImageFormatNotSupportedException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/src/Febe.Core/Codecs/Images/ImageDecoder.cs b/src/Febe.Core/Codecs/Images/ImageDecoder.cs new file mode 100644 index 0000000..372eaf2 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageDecoder.cs @@ -0,0 +1,92 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +public static class ImageDecoder +{ + /// Whether Febe has a decoder for . + public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp or ImageFormat.WebP; + + /// Size, frames and metadata of an image, without decoding the pixels. + /// The format is not known or has no decoder yet. + /// The file is damaged. + public static ImageInfo Identify(ReadOnlyMemory 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), + }; + + /// Decodes an image to straight RGBA8 (the first frame of an animation). + /// The format is not known or has no decoder yet. + /// The file is damaged. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory 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), + }; + + /// Decodes an image to straight RGBA8 and returns what returns as well. + /// The format is not known or has no decoder yet. + /// The file is damaged. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory 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); + } + } + + /// + /// Decodes an image no smaller than 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 returns (the full size). The result may still need resizing. + /// + public static RgbaImage DecodeAtLeast(ReadOnlyMemory 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()}."); +} diff --git a/src/Febe.Core/Codecs/Images/ImageFormat.cs b/src/Febe.Core/Codecs/Images/ImageFormat.cs new file mode 100644 index 0000000..1a8f2d2 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageFormat.cs @@ -0,0 +1,85 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.Images; + +/// Image formats Febe recognises from their first bytes (not all of them can be decoded). +public enum ImageFormat +{ + Unknown, + Png, + Jpeg, + Gif, + Bmp, + WebP, + Tiff, + + /// HEIF with HEVC pictures (HEIC), or a generic HEIF. + Heif, + + /// HEIF with AV1 pictures. + Avif, +} + +/// Recognises an image format from the first bytes of a file. +public static class ImageFormatSniffer +{ + /// Bytes needs to tell every format apart; fewer are fine for most formats. + public const int HeaderLength = 32; + + /// The format the bytes start with, or . + public static ImageFormat Detect(ReadOnlySpan 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; + } + + /// The eight bytes every PNG file starts with. + internal static ReadOnlySpan PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + /// The sizes of the BMP information headers that exist (core, info, V2, V3, OS/2 2.x, V4, V5). + internal static bool IsBmpHeaderSize(uint size) => size is 12 or 16 or 40 or 52 or 56 or 64 or 108 or 124; +} diff --git a/src/Febe.Core/Codecs/Images/ImageGray.cs b/src/Febe.Core/Codecs/Images/ImageGray.cs new file mode 100644 index 0000000..838ab56 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageGray.cs @@ -0,0 +1,33 @@ +namespace Febe.Core.Codecs.Images; + +/// Grey levels of RGBA pixels. +public static class ImageGray +{ + /// + /// 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. + /// + public static void LumaOverWhite(ReadOnlySpan rgba, Span 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)); + } + } +} diff --git a/src/Febe.Core/Codecs/Images/ImageLimits.cs b/src/Febe.Core/Codecs/Images/ImageLimits.cs new file mode 100644 index 0000000..2702a01 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageLimits.cs @@ -0,0 +1,59 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +public sealed record ImageLimits +{ + /// The limits used when a caller passes none. + public static ImageLimits Default { get; } = new(); + + /// Largest width, in pixels. + public int MaxWidth { get; init; } = 65535; + + /// Largest height, in pixels. + public int MaxHeight { get; init; } = 65535; + + /// Largest width × height. 100 megapixels are 400 MB of RGBA. + public long MaxPixels { get; init; } = 100_000_000; + + /// + /// Largest working memory a decoder may take besides the decoded image (for example the indices of a GIF frame). + /// + public long MaxWorkingBytes { get; init; } = 512L * 1024 * 1024; + + /// + /// 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. + /// + public int MaxMetadataBytes { get; init; } = 16 * 1024 * 1024; + + /// Throws when an image of that size is not allowed. + 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."); + } + } + + /// Throws when a decoder would need more working memory than allowed. + 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})."); + } + } +} diff --git a/src/Febe.Core/Codecs/Images/ImageMetadata.cs b/src/Febe.Core/Codecs/Images/ImageMetadata.cs new file mode 100644 index 0000000..571c1a0 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageMetadata.cs @@ -0,0 +1,58 @@ +namespace Febe.Core.Codecs.Images; + +/// A text an image carries (PNG tEXt, zTXt, iTXt; GIF comment; JPEG COM). +/// The keyword («Title», «Comment», «XML:com.adobe.xmp»...); empty for a GIF or JPEG comment. +/// The text. +/// The language tag of an iTXt chunk, empty otherwise. +/// The translated keyword of an iTXt chunk, empty otherwise. +public sealed record ImageText(string Keyword, string Text, string Language = "", string TranslatedKeyword = ""); + +/// Metadata read from an image file, without interpreting it. +public sealed class ImageMetadata +{ + /// No metadata. + public static ImageMetadata Empty { get; } = new(); + + /// The EXIF block as a TIFF structure (starts with «II*\0» or «MM\0*»), or null. + public byte[]? Exif { get; init; } + + /// + /// The EXIF orientation, 1-8 (T.81 has none of its own: it is the Orientation tag of ); 1 when the + /// image has no EXIF block, no such tag or an invalid value. The decoders never apply it to the pixels. + /// + public int Orientation { get; init; } = 1; + + /// The ICC colour profile, decompressed, or null. + public byte[]? IccProfile { get; init; } + + /// The name of the ICC profile as the file gives it, or null. + public string? IccProfileName { get; init; } + + /// The XMP packet (from the iTXt chunk «XML:com.adobe.xmp» of a PNG, the APP1 segment of a JPEG), or null. + public string? Xmp { get; init; } + + /// The texts, in file order (the XMP packet is in , not here). + public IReadOnlyList Texts { get; init; } = []; + + /// + /// 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. + /// + public IReadOnlyList ColorChunks { get; init; } = []; +} + +/// What a file says about its image, read without decoding the pixels. +/// The format. +/// Width in pixels, as stored (no EXIF orientation applied). +/// Height in pixels, as stored. +/// Frames of an animation (GIF images, APNG frames); 1 for a still image. +/// Whether the format of the pixels can carry transparency (not whether any pixel is transparent). +/// The metadata. +public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int FrameCount, bool HasAlpha, ImageMetadata Metadata) +{ + /// + /// 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. + /// + public int BitsPerSample { get; init; } = 8; +} diff --git a/src/Febe.Core/Codecs/Images/ImageOrientation.cs b/src/Febe.Core/Codecs/Images/ImageOrientation.cs new file mode 100644 index 0000000..0220f31 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageOrientation.cs @@ -0,0 +1,70 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +public static class ImageOrientation +{ + /// Whether the orientation swaps width and height (5-8). + public static bool SwapsAxes(int orientation) => orientation is >= 5 and <= 8; + + /// The size of an image as shown, from its stored size. + public static (int Width, int Height) ShownSize(int width, int height, int orientation) => + SwapsAxes(orientation) ? (height, width) : (width, height); + + /// + /// The image turned upright. Returns itself for orientation 1 (or any value outside + /// 1-8); otherwise a new image (pooled when asked), and is left as it is. + /// + 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; + } +} diff --git a/src/Febe.Core/Codecs/Images/ImageResampler.cs b/src/Febe.Core/Codecs/Images/ImageResampler.cs new file mode 100644 index 0000000..cbdd54d --- /dev/null +++ b/src/Febe.Core/Codecs/Images/ImageResampler.cs @@ -0,0 +1,433 @@ +using System.Buffers; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Febe.Core.Codecs.Images; + +/// The filter weighs the source pixels with. +public enum ResampleFilter +{ + /// + /// 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). + /// + Lanczos3, + + /// + /// 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. + /// + Area, +} + +/// Options of . +public sealed record ResampleOptions +{ + /// The options used when a caller passes none. + public static ResampleOptions Default { get; } = new(); + + public ResampleFilter Filter { get; init; } = ResampleFilter.Lanczos3; + + /// + /// 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). + /// + public bool LinearLight { get; init; } +} + +/// +/// 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. +/// +public static class ImageResampler +{ + /// resized to × . + 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; + } + } + + /// + /// The size that fits × inside a square of + /// , keeping the proportions (rounded, at least 1); the same size when it already fits. + /// + 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.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 row, Span 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 input, Span 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 accumulator, ReadOnlySpan row, float weight) + { + var acc = MemoryMarshal.Cast(accumulator); + var add = MemoryMarshal.Cast(row); + var i = 0; + if (Vector.IsHardwareAccelerated && acc.Length >= Vector.Count) + { + var w = new Vector(weight); + var accVectors = MemoryMarshal.Cast>(acc); + var addVectors = MemoryMarshal.Cast>(add); + for (var v = 0; v < accVectors.Length; v++) + { + accVectors[v] += addVectors[v] * w; + } + + i = accVectors.Length * Vector.Count; + } + + for (; i < acc.Length; i++) + { + acc[i] += add[i] * weight; + } + } + + private static void StoreRow(ReadOnlySpan row, Span 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; + } + + /// + /// The weights of one direction: for each target index the first source index, how many follow and their + /// weights (summing to 1), slots per target index. Source indices outside the image are + /// folded onto the nearest edge pixel. + /// + 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 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); + } + } + + /// Conversions between 8-bit sRGB and linear light (IEC 61966-2-1). + 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; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegArithmetic.cs b/src/Febe.Core/Codecs/Images/JpegArithmetic.cs new file mode 100644 index 0000000..ac03559 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegArithmetic.cs @@ -0,0 +1,202 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +internal static class JpegArithmeticTable +{ + /// Index of the fixed estimate (Qe = 0x5A1D, never adapted) used for the signs of AC coefficients. + public const byte FixedState = 113; + + /// Qe of each index; entry 113 is the fixed estimate. + public static ReadOnlySpan 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, + ]; + + /// Next_Index_LPS of each index. + public static ReadOnlySpan 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, + ]; + + /// Next_Index_MPS of each index. + public static ReadOnlySpan 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, + ]; + + /// Switch_MPS of each index: 1 where an LPS inverts the sense of the MPS. + 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; + + /// The state of a context after coding its LPS with renormalization (T.81 D.1.5.4). + [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]); + } + + /// The state of a context after coding its MPS with renormalization (T.81 D.1.5.3). + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static byte AfterMps(byte state) => (byte)((state & 0x80) | NextMps[state & 0x7F]); +} + +/// +/// 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. +/// +internal ref struct JpegArithmeticDecoder +{ + private readonly ReadOnlySpan _data; + private int _position; + private uint _c; + private int _a; + private int _ct; + + public JpegArithmeticDecoder(ReadOnlySpan data, int position) + { + _data = data; + _position = position; + Initialize(); + } + + /// Position of the next byte not yet read. + public readonly int Position => _position; + + /// Initdec (Figure D.22) at , for a restart interval. + public void Restart(int position) + { + _position = position; + Initialize(); + } + + /// Decode(S) of Figure D.16: one binary decision of context , updated in place. + [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; + } + + /// A decision with the fixed estimate of probability one half (signs of AC coefficients). + [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; + } + + /// Byte_in of Figure D.20: a stuffed 0xFF 0x00 is one 0xFF; at a marker nothing is consumed. + 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; + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegDct.cs b/src/Febe.Core/Codecs/Images/JpegDct.cs new file mode 100644 index 0000000..1dc7847 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegDct.cs @@ -0,0 +1,257 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +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) + + /// + /// Dequantizes a block (natural order) and writes its 8×8 samples to , row after row + /// bytes apart. With 12 the samples are 12-bit and are + /// reduced to 8 bits through (4096 entries); with 8 they are written as they are. + /// + public static void Inverse(ReadOnlySpan block, ReadOnlySpan quantization, Span output, int stride, int precision, ReadOnlySpan to8Bit) + { + Span 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 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; + } + } + } + + /// + /// Like , but writes the block reduced by 2^ (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. + /// + /// + /// 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). + /// + public static void InverseReduced(ReadOnlySpan block, ReadOnlySpan quantization, Span output, int stride, int precision, ReadOnlySpan 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 column = stackalloc float[8]; + Span work = stackalloc float[32]; + Span 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; + } + } + } + + /// + /// The means of 2^ neighbouring points (shift 1 or 2) of the eight-point inverse of + /// (twice the T.81 inverse, like ): four or two values. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Reduce1D(ReadOnlySpan x, Span 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; + + /// + /// The forward transform of a block of level-shifted samples (natural order) into DCT coefficients, natural order, + /// not yet quantized. + /// + public static void Forward(ReadOnlySpan samples, Span coefficients) + { + Span 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; + } + } + + /// 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. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Inverse1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span 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; + } + + /// Eight points of X[k] = C(k) Σ x[n] cos((2n+1)kπ/16): twice the T.81 forward transform. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Forward1D(float x0, float x1, float x2, float x3, float x4, float x5, float x6, float x7, Span 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); + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegDecoder.cs b/src/Febe.Core/Codecs/Images/JpegDecoder.cs new file mode 100644 index 0000000..31109a9 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegDecoder.cs @@ -0,0 +1,112 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +/// +/// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged +/// (), 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 . +/// +public static class JpegDecoder +{ + /// Whether the bytes start like a JPEG file (SOI and the start of a marker). + public static bool IsJpeg(ReadOnlySpan data) => data.Length >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF; + + /// Size and metadata of a JPEG, without decoding the pixels. + /// The file is damaged or not a JPEG. + public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null) + { + var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Identify, readMetadata: true); + file.Run(); + return file.ToInfo(); + } + + /// Decodes a JPEG to straight RGBA8. + /// The file is damaged, truncated or not a JPEG. + /// The file uses the hierarchical process. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory 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); + } + + /// Decodes a JPEG to straight RGBA8 and returns what returns as well. + public static RgbaImage Decode(ReadOnlyMemory 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; + } + + /// + /// Decodes a JPEG reduced by 2^ in each direction (0 full size, 1 half, 2 quarter, + /// 3 eighth; sizes rounded up), with what 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. + /// + public static RgbaImage DecodeReduced(ReadOnlyMemory 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; + } + + /// + /// 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). + /// + internal static JpegCoefficients DecodeCoefficients(ReadOnlyMemory data, ImageLimits? limits = null) + { + var file = new JpegFile(data, limits ?? ImageLimits.Default, JpegFile.Mode.Coefficients, readMetadata: false); + file.Run(); + return file.ToCoefficients(); + } +} + +/// The coefficients of one component, natural order inside each block, blocks row after row. +/// Component identifier. +/// Horizontal sampling factor. +/// Vertical sampling factor. +/// Blocks that cover the component's samples horizontally. +/// Blocks that cover the component's samples vertically. +/// Blocks per row in (the MCU grid, at least ). +/// The quantization table the component used, natural order. +/// 64 coefficients per block. +internal sealed record JpegComponentCoefficients(int Id, int H, int V, int BlocksWide, int BlocksHigh, int Stride, ushort[] Quantization, short[] Coefficients) +{ + /// The DQT table the component refers to. + public int QuantizationTable { get; init; } + + /// Rows of blocks in . + public int StoredRows => Coefficients.Length / 64 / Stride; + + /// The 64 coefficients of block (, ). + public ReadOnlySpan Block(int x, int y) => Coefficients.AsSpan(((y * Stride) + x) * 64, 64); +} + +/// What returns. +internal sealed record JpegCoefficients( + int FrameMarker, + int Precision, + int Width, + int Height, + int RestartInterval, + int AdobeTransform, + bool Jfif, + int ScanCount, + IReadOnlyList Components); diff --git a/src/Febe.Core/Codecs/Images/JpegEncoder.cs b/src/Febe.Core/Codecs/Images/JpegEncoder.cs new file mode 100644 index 0000000..20d9648 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegEncoder.cs @@ -0,0 +1,796 @@ +using System.Buffers.Binary; +using System.Numerics; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// Chroma sampling of a colour JPEG. +public enum JpegSubsampling +{ + /// Chroma at half width and half height (H = V = 2 for luma): the usual choice for photos. + Ratio420, + + /// Chroma at full resolution. + Ratio444, +} + +/// How writes a file. +public sealed record JpegEncoderOptions +{ + /// The options used when a caller passes none. + public static JpegEncoderOptions Default { get; } = new(); + + /// Quality 1-100: the Annex K tables scaled (50 keeps them as they are). + public int Quality { get; init; } = 85; + + /// Chroma sampling of a colour image. + public JpegSubsampling Subsampling { get; init; } = JpegSubsampling.Ratio420; + + /// One component (luma) instead of three. + public bool Grayscale { get; init; } + + /// MCUs per restart interval (DRI and RSTn markers), 0 for none. + public int RestartInterval { get; init; } + + /// + /// EXIF to write in an APP1 segment: a TIFF structure («II*\0» or «MM\0*»), optionally preceded by «Exif\0\0». + /// + public byte[]? Exif { get; init; } + + /// ICC profile to write in APP2 «ICC_PROFILE» chunks. + public byte[]? IccProfile { get; init; } + + /// XMP packet to write in an APP1 segment (at most one segment: no extended XMP). + public string? Xmp { get; init; } + + /// Comments to write in COM segments, UTF-8. + public IReadOnlyList Comments { get; init; } = []; +} + +/// +/// 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. +/// +public static class JpegEncoder +{ + /// Encodes an image to a JPEG file. + public static byte[] Encode(RgbaImage image, JpegEncoderOptions? options = null) + { + var output = new JpegOutput(); + Write(image, options ?? JpegEncoderOptions.Default, output); + return output.ToArray(); + } + + /// Encodes an image to a JPEG file written to . + 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); + } + + /// + /// The quantized coefficients the encoder would write for , with its frame layout: what tests + /// compare with the decoder and with other entropy codings of the same image. + /// + 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); + } + + /// + /// 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. + /// + internal static JpegCoefficients TransformPlanes( + int width, + int height, + int precision, + IReadOnlyList<(int Id, int H, int V, int Table, int[] Samples)> planes, + IReadOnlyList 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 samples = stackalloc float[64]; + Span 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 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); + } + + /// One block, baseline: DC difference (F.1.2.1) and run-length coded AC (F.1.2.2). + internal static void EncodeBlock(JpegBitWriter writer, ReadOnlySpan 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); + } + } + + /// The Annex K Huffman tables, built once. + 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); + } + + /// Components, sampling factors and quantization of the frame the encoder writes. + 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; } + + /// Blocks per row of the MCU grid. + public int Stride { get; } + + /// Rows of blocks of the MCU grid. + public int Rows { get; } + } + + /// + /// 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. + /// + 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); + } + } + } + + /// Block (, row of the strip) of component , quantized. + public void Quantize(int i, int bx, int v, Span block) + { + Span samples = stackalloc float[64]; + Span 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); + } + } + } +} + +/// A growing byte buffer for the encoders. +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 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); + } + + /// Drops bytes from the end (the trailing zeros an arithmetic coder may leave out). + 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); +} + +/// Writes Huffman codes and extra bits of an entropy-coded segment, stuffing a zero after each 0xFF. +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); + } + + /// Symbol (run << 4 | category) and the low bits of (F.1.2.1, F.1.2.2). + 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); + } + } + + /// Pads the last byte with one bits (F.1.2.3). + public void Flush() + { + if (_count > 0) + { + WriteBits((1 << (8 - _count)) - 1, 8 - _count); + } + } +} + +/// Marker segments of T.81 Annex B and of JFIF, EXIF, XMP and ICC, for the encoders. +internal static class JpegSegments +{ + private const int MaxPayload = 65533; + private const int IccChunk = 65519; + + public static void WriteSegment(JpegOutput output, int marker, ReadOnlySpan 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? comments) + { + if (exif is not null) + { + ReadOnlySpan 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)); + } + } + } + + /// One DQT segment with every table (8-bit entries when all fit, 16-bit otherwise), zig-zag order. + public static void WriteQuantization(JpegOutput output, IReadOnlyList tables) + { + var payload = new List(); + 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 counts, ReadOnlySpan 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); + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs new file mode 100644 index 0000000..71886b7 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.Arithmetic.cs @@ -0,0 +1,338 @@ +namespace Febe.Core.Codecs.Images; + +/// Arithmetic-coded scans: sequential (T.81 F.2.4), progressive (G.1.3, G.2) and lossless (H.1.2.3). +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 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 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); + } + + /// + /// 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. + /// + 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; + } + + /// + /// 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 , magnitude bins from . The context of the next + /// difference is set from this one. + /// + private static int DecodeDifference(ref JpegArithmeticDecoder decoder, Span 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 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; + } + + /// Decode the bits below the leading one of Sz (Figure F.9 reversed), all with bin . + private static int DecodeMagnitudeBits(ref JpegArithmeticDecoder decoder, Span 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; + } + + /// AC coefficients of a sequential block or of the first scan of a band (Figure F.5, Table F.5). + private static void DecodeAcArithmetic(ref JpegArithmeticDecoder decoder, Span statistics, int kx, int ss, int se, int al, Span block, ReadOnlySpan 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)); + } + } + + /// A later scan of successive approximation of a band (Figures G.10, G.11; Table G.2). + private static void DecodeAcRefineArithmetic(ref JpegArithmeticDecoder decoder, Span statistics, in Scan scan, Span block, ReadOnlySpan 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); + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs new file mode 100644 index 0000000..0d1b27b --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.Huffman.cs @@ -0,0 +1,478 @@ +namespace Febe.Core.Codecs.Images; + +/// Huffman-coded scans: sequential (T.81 F.2), progressive (G.2) and lossless (H.2). +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 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 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); + } + + /// The error for a scan that needed bits it did not have: cut short () or interrupted by a marker. + 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 block, ReadOnlySpan 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 block, ReadOnlySpan 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 block, ReadOnlySpan 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); + } + + /// The predictors of T.81 H.1.2.1 and the samples they reconstruct. + 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; + } + + /// A restart interval starts at MCU row : its first line predicts like the first line of the scan. + public void Restart(int mcuRow) + { + for (var i = 0; i < _scan.Components.Length; i++) + { + _firstRow[i] = _single ? mcuRow : mcuRow * _scan.Components[i].V; + } + } + + /// Whether row of scan component is the first line of the scan or restart interval. + public bool IsFirstLine(int ci, int y) => y == _firstRow[ci]; + + /// The prediction for (x, y) of , the scan's component . + 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); + } + + /// Undoes the point transform and writes the 8-bit planes. + 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); + } + } + } + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.Render.cs b/src/Febe.Core/Codecs/Images/JpegFile.Render.cs new file mode 100644 index 0000000..18a5a7e --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.Render.cs @@ -0,0 +1,314 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// From the component planes to RGBA: upsampling of the chroma and colour conversion. +internal sealed partial class JpegFile +{ + /// The colour space of the components, as decoders choose it (JFIF, Adobe APP14, component identifiers). + 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.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.Shared.Return(buffer); + } + } + } + + return image; + } + + /// + /// Row of the image for component , 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. + /// + private ReadOnlySpan 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 grey, Span 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 r, ReadOnlySpan g, ReadOnlySpan b, Span 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 luma, ReadOnlySpan cb, ReadOnlySpan cr, Span 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; + } + } + + /// + /// 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). + /// + private static void WriteCmyk(ReadOnlySpan c0, ReadOnlySpan c1, ReadOnlySpan c2, ReadOnlySpan k, Span 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; + + /// + /// 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. + /// + 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]; + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegFile.cs b/src/Febe.Core/Codecs/Images/JpegFile.cs new file mode 100644 index 0000000..3f6e51d --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegFile.cs @@ -0,0 +1,1049 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// One component of a JPEG frame and what the decoder keeps of it. +internal sealed class JpegComponent +{ + public int Id; + public int Index; + public int H; + public int V; + public int QuantizationTable; + + /// Samples of the component: ceil(X × H / Hmax) × ceil(Y × V / Vmax). + public int Width; + public int Height; + + /// Data units (blocks, or samples in lossless) that cover the samples: what a non-interleaved scan codes. + public int UnitsWide; + public int UnitsHigh; + + /// Data units of the MCU grid of an interleaved scan (equal to the above in a one-component frame). + public int PaddedUnitsWide; + public int PaddedUnitsHigh; + + /// Coefficients, 64 per block of the padded grid, natural order; null when not kept. + public short[]? Coefficients; + + /// 8-bit samples, per row, covering the padded grid. + public byte[]? Plane; + public int PlaneStride; + + /// Lossless samples before the point transform is undone, same layout as . + public ushort[]? Samples; + + /// The quantization table latched at the component's first scan, natural order. + public ushort[]? Quantization; + + public bool Coded; + + // Scan state. + public int DcPredictor; + public int DcContext; + public int DcTable; + public int AcTable; +} + +/// +/// The marker-level reader of a JPEG file and its decoded state. One instance per call; the arrays it rents from the +/// pool go back in . +/// +internal sealed partial class JpegFile : IDisposable +{ + private const int MaxComponentsInScan = 4; + private const int MaxBlocksInMcu = 10; + + private readonly ReadOnlyMemory _memory; + private readonly ImageLimits _limits; + private readonly Mode _mode; + private readonly bool _readMetadata; + + private readonly ushort[]?[] _quantization = new ushort[4][]; + private readonly JpegHuffmanTable?[] _dcTables = new JpegHuffmanTable[4]; + private readonly JpegHuffmanTable?[] _acTables = new JpegHuffmanTable[4]; + private readonly byte[] _dcL = new byte[4]; + private readonly byte[] _dcU = [1, 1, 1, 1]; + private readonly byte[] _acK = [5, 5, 5, 5]; + + private int _restartInterval; + private bool _jfif; + private int _adobeTransform = -1; + private int _metadataBudget; + private byte[]? _exif; + private string? _xmp; + private List<(int Sequence, int Count, byte[] Data)>? _iccChunks; + private List? _texts; + + private bool _allocated; + private bool _pooledArrays; + private int _scaleShift; + private int _scanCount; + private int _sosEnd; + + public JpegFile(ReadOnlyMemory data, ImageLimits limits, Mode mode, bool readMetadata) + { + _memory = data; + _limits = limits; + _mode = mode; + _readMetadata = readMetadata; + _metadataBudget = limits.MaxMetadataBytes; + } + + internal enum Mode + { + /// Stop at the first scan: frame and metadata only. + Identify, + + /// Decode to samples. + Pixels, + + /// Decode and keep every coefficient (tests). + Coefficients, + } + + public int FrameMarker { get; private set; } + + public bool Progressive { get; private set; } + + public bool Arithmetic { get; private set; } + + public bool Lossless { get; private set; } + + public int Precision { get; private set; } + + public int Width { get; private set; } + + public int Height { get; private set; } + + public JpegComponent[] Components { get; private set; } = []; + + /// + /// The reduction of a DCT image decoded to samples, as a power of two (0 full size, 1 half, 2 quarter, 3 eighth): + /// each 8×8 block gives (8 >> shift)² samples, the means of its squares of samples (only its DC term at an + /// eighth). Set before ; a lossless file is always decoded at full size. + /// + public int ScaleShift + { + get => _scaleShift; + set => _scaleShift = Math.Clamp(value, 0, 3); + } + + /// Width of the decoded image: reduced by , rounded up. + public int OutputWidth => Reduce(Width); + + /// Height of the decoded image: reduced by , rounded up. + public int OutputHeight => Reduce(Height); + + private int Reduce(int length) => (length + (1 << _scaleShift) - 1) >> _scaleShift; + + public int MaxH { get; private set; } + + public int MaxV { get; private set; } + + /// MCUs per row and rows of MCUs of an interleaved scan. + public int McusWide { get; private set; } + + public int McusHigh { get; private set; } + + private ReadOnlySpan Data => _memory.Span; + + public void Run() + { + var data = Data; + if (!JpegDecoder.IsJpeg(data)) + { + throw new ImageDecodeException("Non è un file JPEG."); + } + + var pos = 2; + var sawEoi = false; + while (true) + { + // Bytes that are not a marker between segments are skipped, as decoders have always done. + while (pos < data.Length && data[pos] != 0xFF) + { + pos++; + } + + while (pos < data.Length && data[pos] == 0xFF) + { + pos++; + } + + if (pos >= data.Length) + { + break; + } + + int marker = data[pos++]; + if (marker == 0x00 || marker == 0x01 || marker is >= 0xD0 and <= 0xD7) + { + continue; + } + + if (marker == 0xD9) + { + sawEoi = true; + break; + } + + if (marker == 0xD8) + { + throw new ImageDecodeException("JPEG danneggiato: due marcatori di inizio."); + } + + if (data.Length - pos < 2) + { + throw Truncated(); + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(data[pos..]); + if (length < 2 || length > data.Length - pos) + { + throw Truncated(); + } + + var payload = data.Slice(pos + 2, length - 2); + var end = pos + length; + switch (marker) + { + case 0xC0 or 0xC1 or 0xC2 or 0xC3 or 0xC9 or 0xCA or 0xCB: + ReadFrame(marker, payload); + break; + case 0xC5 or 0xC6 or 0xC7 or 0xCD or 0xCE or 0xCF or 0xDE or 0xDF: + throw new ImageFormatNotSupportedException("Febe non legge i JPEG gerarchici (T.81, allegato J)."); + case 0xC4: + ReadHuffmanTables(payload); + break; + case 0xCC: + ReadArithmeticConditioning(payload); + break; + case 0xDB: + ReadQuantizationTables(payload); + break; + case 0xDD: + if (payload.Length < 2) + { + throw new ImageDecodeException("JPEG danneggiato: segmento DRI troppo corto."); + } + + _restartInterval = BinaryPrimitives.ReadUInt16BigEndian(payload); + break; + case 0xDC: + ReadDnl(payload); + break; + case >= 0xE0 and <= 0xEF: + ReadApplication(marker, payload); + break; + case 0xFE: + if (_readMetadata) + { + ReadComment(payload); + } + + break; + case 0xDA: + if (Components.Length == 0) + { + throw new ImageDecodeException("JPEG danneggiato: una scansione prima del fotogramma."); + } + + _sosEnd = end; + if (Height == 0) + { + FindDnl(end); + } + + if (_mode == Mode.Identify) + { + return; + } + + pos = DecodeScan(payload, end); + _scanCount++; + continue; + default: + // JPGn, reserved markers: skipped by their length. + break; + } + + pos = end; + } + + if (Components.Length == 0) + { + throw new ImageDecodeException(sawEoi ? "JPEG senza fotogramma." : "JPEG troncato prima del fotogramma."); + } + + if (_mode == Mode.Identify) + { + if (Height == 0) + { + throw new ImageDecodeException("JPEG senza altezza: manca il segmento DNL."); + } + + return; + } + + if (_scanCount == 0) + { + throw new ImageDecodeException("JPEG senza dati d'immagine."); + } + + foreach (var component in Components) + { + if (!component.Coded) + { + throw new ImageDecodeException("JPEG incompleto: una componente non ha dati."); + } + } + + if (Progressive && _mode == Mode.Pixels) + { + foreach (var component in Components) + { + TransformAll(component); + } + } + } + + public ImageInfo ToInfo() + { + var icc = AssembleIcc(); + var metadata = _exif is null && icc is null && _xmp is null && _texts is null + ? ImageMetadata.Empty + : new ImageMetadata + { + Exif = _exif, + Orientation = _exif is null ? 1 : ExifOrientation.Read(_exif), + IccProfile = icc, + Xmp = _xmp, + Texts = _texts ?? [], + }; + return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision }; + } + + public JpegCoefficients ToCoefficients() + { + if (Lossless) + { + throw new ImageFormatNotSupportedException("Un JPEG senza perdita non ha coefficienti."); + } + + var components = new List(Components.Length); + foreach (var c in Components) + { + components.Add(new JpegComponentCoefficients(c.Id, c.H, c.V, c.UnitsWide, c.UnitsHigh, c.PaddedUnitsWide, c.Quantization ?? new ushort[64], c.Coefficients!) { QuantizationTable = c.QuantizationTable }); + } + + return new JpegCoefficients(FrameMarker, Precision, Width, Height, _restartInterval, _adobeTransform, _jfif, _scanCount, components); + } + + public void Dispose() + { + if (!_pooledArrays) + { + return; + } + + foreach (var c in Components) + { + if (c.Plane is { } plane) + { + ImageBuffers.Return(plane); + c.Plane = null; + } + + if (c.Coefficients is { } coefficients) + { + ImageBuffers.Return(coefficients); + c.Coefficients = null; + } + + if (c.Samples is { } samples) + { + ImageBuffers.Return(samples); + c.Samples = null; + } + } + } + + private static ImageDecodeException Truncated() => new("JPEG troncato: un segmento finisce oltre la fine del file."); + + private void ReadFrame(int marker, ReadOnlySpan p) + { + if (Components.Length != 0) + { + throw new ImageDecodeException("JPEG danneggiato: più di un fotogramma."); + } + + if (p.Length < 6) + { + throw new ImageDecodeException("JPEG danneggiato: intestazione del fotogramma troppo corta."); + } + + FrameMarker = marker; + Progressive = marker is 0xC2 or 0xCA; + Arithmetic = marker >= 0xC8; + Lossless = marker is 0xC3 or 0xCB; + Precision = p[0]; + Height = BinaryPrimitives.ReadUInt16BigEndian(p[1..]); + Width = BinaryPrimitives.ReadUInt16BigEndian(p[3..]); + int count = p[5]; + if (Lossless ? Precision is < 2 or > 16 : Precision is not (8 or 12)) + { + throw new ImageFormatNotSupportedException($"Febe non legge i JPEG con campioni di {Precision} bit."); + } + + if (Width == 0) + { + throw new ImageDecodeException("JPEG danneggiato: larghezza zero."); + } + + if (count == 0 || p.Length < 6 + (3 * count)) + { + throw new ImageDecodeException("JPEG danneggiato: componenti del fotogramma mancanti."); + } + + if (count is 2 or > 4) + { + throw new ImageFormatNotSupportedException($"Febe non legge i JPEG con {count} componenti."); + } + + var components = new JpegComponent[count]; + for (var i = 0; i < count; i++) + { + var c = p.Slice(6 + (3 * i), 3); + var component = new JpegComponent { Id = c[0], Index = i, H = c[1] >> 4, V = c[1] & 15, QuantizationTable = c[2] }; + if (component.H is < 1 or > 4 || component.V is < 1 or > 4 || (component.QuantizationTable > 3 && !Lossless)) + { + throw new ImageDecodeException("JPEG danneggiato: fattori di campionamento o tabella di quantizzazione non validi."); + } + + for (var j = 0; j < i; j++) + { + if (components[j].Id == component.Id) + { + throw new ImageDecodeException("JPEG danneggiato: due componenti con lo stesso identificativo."); + } + } + + components[i] = component; + MaxH = Math.Max(MaxH, component.H); + MaxV = Math.Max(MaxV, component.V); + } + + Components = components; + if (Height != 0) + { + ComputeGeometry(); + } + } + + private void ComputeGeometry() + { + var unit = Lossless ? 1 : 8; + McusWide = Ceil(Width, unit * MaxH); + McusHigh = Ceil(Height, unit * MaxV); + foreach (var c in Components) + { + c.Width = Ceil(Width * c.H, MaxH); + c.Height = Ceil(Height * c.V, MaxV); + c.UnitsWide = Ceil(c.Width, unit); + c.UnitsHigh = Ceil(c.Height, unit); + if (Components.Length == 1) + { + c.PaddedUnitsWide = c.UnitsWide; + c.PaddedUnitsHigh = c.UnitsHigh; + } + else + { + c.PaddedUnitsWide = McusWide * c.H; + c.PaddedUnitsHigh = McusHigh * c.V; + } + } + } + + private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor; + + private void ReadDnl(ReadOnlySpan p) + { + if (p.Length < 2) + { + throw new ImageDecodeException("JPEG danneggiato: segmento DNL troppo corto."); + } + + if (Height == 0 && Components.Length > 0) + { + Height = BinaryPrimitives.ReadUInt16BigEndian(p); + if (Height == 0) + { + throw new ImageDecodeException("JPEG danneggiato: altezza zero nel segmento DNL."); + } + + ComputeGeometry(); + } + } + + /// A frame of height 0 gives it in a DNL segment right after the first scan (T.81 B.2.5). + private void FindDnl(int scanStart) + { + var data = Data; + var pos = FindNextMarker(scanStart); + if (pos + 6 <= data.Length && data[pos + 1] == 0xDC) + { + ReadDnl(data.Slice(pos + 4, 2)); + } + + if (Height == 0) + { + throw new ImageDecodeException("JPEG senza altezza: manca il segmento DNL."); + } + } + + private void ReadQuantizationTables(ReadOnlySpan p) + { + var zigzag = JpegTables.ZigZag; + while (p.Length > 0) + { + var precision = p[0] >> 4; + var id = p[0] & 15; + var size = precision == 0 ? 64 : 128; + if (id > 3 || precision > 1 || p.Length < 1 + size) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di quantizzazione non valida."); + } + + var table = new ushort[64]; + for (var k = 0; k < 64; k++) + { + table[zigzag[k]] = precision == 0 ? p[1 + k] : BinaryPrimitives.ReadUInt16BigEndian(p[(1 + (2 * k))..]); + } + + _quantization[id] = table; + p = p[(1 + size)..]; + } + } + + private void ReadHuffmanTables(ReadOnlySpan p) + { + while (p.Length > 0) + { + if (p.Length < 17) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman troncata."); + } + + var tableClass = p[0] >> 4; + var id = p[0] & 15; + if (tableClass > 1 || id > 3) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman non valida."); + } + + var counts = p.Slice(1, 16); + var total = 0; + foreach (var count in counts) + { + total += count; + } + + if (p.Length < 17 + total) + { + throw new ImageDecodeException("JPEG danneggiato: tabella di Huffman troncata."); + } + + var table = JpegHuffmanTable.Build(counts, p.Slice(17, total)); + (tableClass == 0 ? _dcTables : _acTables)[id] = table; + p = p[(17 + total)..]; + } + } + + private void ReadArithmeticConditioning(ReadOnlySpan p) + { + for (; p.Length >= 2; p = p[2..]) + { + var tableClass = p[0] >> 4; + var id = p[0] & 15; + var value = p[1]; + if (id > 3) + { + throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico non valido."); + } + + if (tableClass == 0) + { + var low = value & 15; + var high = value >> 4; + if (low > high) + { + throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico con L maggiore di U."); + } + + _dcL[id] = (byte)low; + _dcU[id] = (byte)high; + } + else + { + if (value is < 1 or > 63) + { + throw new ImageDecodeException("JPEG danneggiato: condizionamento aritmetico Kx non valido."); + } + + _acK[id] = value; + } + } + } + + private void ReadApplication(int marker, ReadOnlySpan p) + { + // JFIF and Adobe decide the colour space, so they are read even without metadata. + if (marker == 0xE0 && p.Length >= 5 && p[..5].SequenceEqual("JFIF\0"u8)) + { + _jfif = true; + return; + } + + if (marker == 0xEE && p.Length >= 12 && p[..5].SequenceEqual("Adobe"u8)) + { + _adobeTransform = p[11]; + return; + } + + if (!_readMetadata) + { + return; + } + + // Damaged or oversized metadata is skipped: it must never stop an image from being shown. + if (marker == 0xE1) + { + if (_exif is null && p.Length > 6 && p[..4].SequenceEqual("Exif"u8) && p[4] == 0) + { + var tiff = p[6..]; + if (Spend(tiff.Length)) + { + _exif = tiff.ToArray(); + } + } + else if (_xmp is null && p.StartsWith(XmpNamespace)) + { + var packet = p[XmpNamespace.Length..]; + if (Spend(packet.Length)) + { + _xmp = Encoding.UTF8.GetString(packet); + } + } + } + else if (marker == 0xE2 && p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8)) + { + int sequence = p[12]; + int count = p[13]; + var chunk = p[14..]; + if (sequence >= 1 && sequence <= count && Spend(chunk.Length)) + { + (_iccChunks ??= []).Add((sequence, count, chunk.ToArray())); + } + } + } + + /// The namespace that starts an XMP APP1 segment, with its terminating zero. + internal static ReadOnlySpan XmpNamespace => "http://ns.adobe.com/xap/1.0/\0"u8; + + private void ReadComment(ReadOnlySpan p) + { + if (!Spend(p.Length)) + { + return; + } + + string text; + try + { + text = new UTF8Encoding(false, true).GetString(p); + } + catch (DecoderFallbackException) + { + text = Encoding.Latin1.GetString(p); + } + + (_texts ??= []).Add(new ImageText(string.Empty, text.TrimEnd('\0'))); + } + + private bool Spend(int bytes) + { + if (bytes > _metadataBudget) + { + return false; + } + + _metadataBudget -= bytes; + return true; + } + + /// The ICC profile from its APP2 chunks, or null when a chunk is missing or they disagree. + private byte[]? AssembleIcc() + { + if (_iccChunks is null) + { + return null; + } + + var count = _iccChunks[0].Count; + var parts = new byte[count][]; + foreach (var (sequence, chunkCount, chunk) in _iccChunks) + { + if (chunkCount != count || parts[sequence - 1] is not null) + { + return null; + } + + parts[sequence - 1] = chunk; + } + + var total = 0; + foreach (var part in parts) + { + if (part is null) + { + return null; + } + + total += part.Length; + } + + var profile = new byte[total]; + var offset = 0; + foreach (var part in parts) + { + part.CopyTo(profile, offset); + offset += part.Length; + } + + return profile; + } + + /// The position of the next marker that is not a restart marker, or the end of the data. + private int FindNextMarker(int pos) + { + var data = Data; + while (pos + 1 < data.Length) + { + if (data[pos] == 0xFF) + { + var next = data[pos + 1]; + if (next == 0xFF) + { + pos++; + continue; + } + + if (next != 0 && next is not (>= 0xD0 and <= 0xD7)) + { + return pos; + } + + pos += 2; + continue; + } + + pos++; + } + + return data.Length; + } + + /// + /// After a restart interval: the position just after the next RSTn marker, skipping any stray bytes before it; or + /// the position of a marker that is not RSTn (it ends the scan), or the end of the data. + /// + private int SkipRestartMarker(int pos) + { + var data = Data; + while (pos + 1 < data.Length) + { + if (data[pos] == 0xFF) + { + var next = data[pos + 1]; + if (next is >= 0xD0 and <= 0xD7) + { + return pos + 2; + } + + if (next != 0 && next != 0xFF) + { + return pos; + } + } + + pos++; + } + + return data.Length; + } + + private void Allocate() + { + if (Lossless || _mode != Mode.Pixels) + { + _scaleShift = 0; + } + + _limits.CheckSize(OutputWidth, OutputHeight); + var keepCoefficients = Progressive || _mode == Mode.Coefficients; + long bytes = 0; + foreach (var c in Components) + { + var unit = Lossless ? 1 : 8; + long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit; + bytes += samples >> (2 * _scaleShift); + if (keepCoefficients && !Lossless) + { + bytes += samples * 2; + } + + if (Lossless) + { + // The samples before the point transform, and for arithmetic coding the class of every difference. + bytes += samples * (Arithmetic ? 3 : 2); + } + } + + _limits.CheckWorkingBytes(bytes); + _pooledArrays = _mode == Mode.Pixels; + foreach (var c in Components) + { + var unit = Lossless ? 1 : 8; + var planeUnit = unit >> _scaleShift; + c.PlaneStride = c.PaddedUnitsWide * planeUnit; + var samples = c.PlaneStride * c.PaddedUnitsHigh * unit; + if (_mode == Mode.Pixels) + { + c.Plane = ImageBuffers.Rent(c.PlaneStride * c.PaddedUnitsHigh * planeUnit); + } + + if (Lossless) + { + c.Samples = _pooledArrays ? ImageBuffers.Rent(samples) : new ushort[samples]; + } + else if (keepCoefficients) + { + var length = c.PaddedUnitsWide * c.PaddedUnitsHigh * 64; + if (_pooledArrays) + { + c.Coefficients = ImageBuffers.Rent(length); + c.Coefficients.AsSpan(0, length).Clear(); + } + else + { + c.Coefficients = new short[length]; + } + } + } + + _allocated = true; + } + + /// A scan: its components in order and its spectral and approximation parameters. + private readonly record struct Scan(JpegComponent[] Components, int Ss, int Se, int Ah, int Al); + + private int DecodeScan(ReadOnlySpan p, int start) + { + if (!_allocated) + { + Allocate(); + } + + var scan = ReadScanHeader(p); + foreach (var c in scan.Components) + { + if (!c.Coded) + { + c.Coded = true; + if (!Lossless) + { + c.Quantization = (ushort[])(_quantization[c.QuantizationTable] + ?? throw new ImageDecodeException("JPEG danneggiato: manca una tabella di quantizzazione.")).Clone(); + } + } + + c.DcPredictor = 0; + c.DcContext = 0; + } + + if (Lossless) + { + return Arithmetic ? DecodeLosslessArithmeticScan(scan, start) : DecodeLosslessHuffmanScan(scan, start); + } + + return Arithmetic ? DecodeArithmeticScan(scan, start) : DecodeHuffmanScan(scan, start); + } + + private Scan ReadScanHeader(ReadOnlySpan p) + { + if (p.Length < 1) + { + throw new ImageDecodeException("JPEG danneggiato: intestazione di scansione vuota."); + } + + int count = p[0]; + if (count is < 1 or > MaxComponentsInScan || p.Length < 4 + (2 * count)) + { + throw new ImageDecodeException("JPEG danneggiato: intestazione di scansione non valida."); + } + + var components = new JpegComponent[count]; + var blocks = 0; + for (var i = 0; i < count; i++) + { + int id = p[1 + (2 * i)]; + var tables = p[2 + (2 * i)]; + JpegComponent? found = null; + foreach (var c in Components) + { + if (c.Id == id) + { + found = c; + } + } + + if (found is null || Array.IndexOf(components, found, 0, i) >= 0) + { + throw new ImageDecodeException("JPEG danneggiato: la scansione nomina una componente che non c'è."); + } + + found.DcTable = tables >> 4; + found.AcTable = tables & 15; + if (found.DcTable > 3 || found.AcTable > 3) + { + throw new ImageDecodeException("JPEG danneggiato: tabella d'entropia non valida."); + } + + components[i] = found; + blocks += found.H * found.V; + } + + if (count > 1 && blocks > MaxBlocksInMcu) + { + throw new ImageDecodeException("JPEG danneggiato: troppi blocchi in un MCU."); + } + + var tail = p.Slice(1 + (2 * count), 3); + int ss = tail[0]; + int se = tail[1]; + var ah = tail[2] >> 4; + var al = tail[2] & 15; + if (Lossless) + { + if (ss is < 1 or > 7 || al >= Precision) + { + throw new ImageDecodeException("JPEG danneggiato: predittore o trasformazione di punto non validi."); + } + } + else if (Progressive) + { + var valid = se <= 63 && ss <= se && al <= 13 && ah <= 13 && (ss == 0 ? se == 0 : count == 1 && ss >= 1); + if (!valid) + { + throw new ImageDecodeException("JPEG danneggiato: parametri della scansione progressiva non validi."); + } + } + else + { + ss = 0; + se = 63; + ah = 0; + al = 0; + } + + return new Scan(components, ss, se, ah, al); + } + + /// The MCUs of a scan: one block (or sample) each when it has one component, the MCU grid otherwise. + private (int PerRow, int Total) McuLayout(in Scan scan) + { + if (scan.Components.Length == 1) + { + var c = scan.Components[0]; + return (c.UnitsWide, c.UnitsWide * c.UnitsHigh); + } + + return (McusWide, McusWide * McusHigh); + } + + private JpegHuffmanTable DcTable(int id) => + _dcTables[id] ?? (id < 2 ? DefaultTables.Dc[id] : throw new ImageDecodeException("JPEG danneggiato: manca una tabella di Huffman.")); + + private JpegHuffmanTable AcTable(int id) => + _acTables[id] ?? (id < 2 ? DefaultTables.Ac[id] : throw new ImageDecodeException("JPEG danneggiato: manca una tabella di Huffman.")); + + /// + /// The Annex K tables, used when a Huffman scan refers to table 0 or 1 that the file never defines (motion JPEG + /// frames leave them out). + /// + private static class DefaultTables + { + public static readonly JpegHuffmanTable[] Dc = + [ + JpegHuffmanTable.Build(JpegTables.LuminanceDcCounts, JpegTables.LuminanceDcValues), + JpegHuffmanTable.Build(JpegTables.ChrominanceDcCounts, JpegTables.ChrominanceDcValues), + ]; + + public static readonly JpegHuffmanTable[] Ac = + [ + JpegHuffmanTable.Build(JpegTables.LuminanceAcCounts, JpegTables.LuminanceAcValues), + JpegHuffmanTable.Build(JpegTables.ChrominanceAcCounts, JpegTables.ChrominanceAcValues), + ]; + } + + /// The IDCT of every visible block of a component whose coefficients were kept. + private void TransformAll(JpegComponent c) + { + var to8 = Precision == 12 ? Twelve.ToEight : default; + var coefficients = c.Coefficients!; + var plane = c.Plane!; + for (var by = 0; by < c.UnitsHigh; by++) + { + for (var bx = 0; bx < c.UnitsWide; bx++) + { + var block = coefficients.AsSpan(((by * c.PaddedUnitsWide) + bx) * 64, 64); + TransformBlock(c, plane, block, bx, by, to8); + } + } + } + + /// The samples of one block into the plane of its component, at the scale of . + private void TransformBlock(JpegComponent c, byte[] plane, ReadOnlySpan block, int bx, int by, ReadOnlySpan to8) + { + var n = 8 >> _scaleShift; + var output = plane.AsSpan((by * n * c.PlaneStride) + (bx * n)); + if (_scaleShift == 0) + { + JpegDct.Inverse(block, c.Quantization, output, c.PlaneStride, Precision, to8); + } + else + { + JpegDct.InverseReduced(block, c.Quantization, output, c.PlaneStride, Precision, to8, _scaleShift); + } + } + + /// 12-bit samples to 8 bits, rounded. + private static class Twelve + { + public static readonly byte[] ToEight = Build(); + + private static byte[] Build() + { + var table = new byte[4096]; + for (var i = 0; i < table.Length; i++) + { + table[i] = (byte)(((i * 255) + 2047) / 4095); + } + + return table; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegHuffman.cs b/src/Febe.Core/Codecs/Images/JpegHuffman.cs new file mode 100644 index 0000000..5e21bf4 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegHuffman.cs @@ -0,0 +1,276 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// A Huffman table of T.81 (Annex C): the canonical codes built from the counts per length, with a lookup of the +/// first bits for decoding and the code of every symbol for encoding. +/// +internal sealed class JpegHuffmanTable +{ + /// Bits looked up at once; longer codes take the slow path of T.81 F.2.2.3. + public const int LookupBits = 9; + + private JpegHuffmanTable(byte[] counts, byte[] values) + { + Counts = counts; + Values = values; + } + + /// Codes of each length 1-16. + public byte[] Counts { get; } + + /// The symbols, in code order. + public byte[] Values { get; } + + /// For each value of the next bits: (length << 8) | symbol, or 0. + public ushort[] Lookup { get; } = new ushort[1 << LookupBits]; + + /// Largest code of each length (index 1-16), -1 when there is none. + public int[] MaxCode { get; } = new int[17]; + + /// For each length, the index in of its first code minus that code. + public int[] ValueOffset { get; } = new int[17]; + + /// The code of each symbol (encoding). + public ushort[] Codes { get; } = new ushort[256]; + + /// The length of the code of each symbol, 0 when the table has no code for it (encoding). + public byte[] Sizes { get; } = new byte[256]; + + /// Builds a table from the 16 counts and the symbols of a DHT segment. + /// The counts describe more codes than fit, or do not match the symbols. + public static JpegHuffmanTable Build(ReadOnlySpan counts, ReadOnlySpan 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; + } +} + +/// +/// 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. +/// +internal ref struct JpegBitReader +{ + private readonly ReadOnlySpan _data; + private int _position; + private ulong _bits; + private int _count; + private int _padBits; + + public JpegBitReader(ReadOnlySpan data, int position) + { + _data = data; + _position = position; + } + + /// Position of the next byte not yet read. + public readonly int Position => _position; + + /// Whether the reader ran out of data (not at a marker). + public bool ReachedEnd { get; private set; } + + /// Whether a decoded symbol used bits past the end of the segment. + public readonly bool UsedPadding => _padBits > _count; + + /// Drops the bits of the current byte and those buffered, for a restart marker or the end of a scan. + public void Reset() + { + _bits = 0; + _count = 0; + _padBits = 0; + ReachedEnd = false; + } + + /// Moves to , with no buffered bits. + 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; + } + + /// The next bits (0-16) as an unsigned number. + [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; + } + + /// RECEIVE and EXTEND of T.81 F.2.2.1: bits as a signed value of category s. + [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; + } + + /// Decodes one symbol with . + /// The bits are no code of the table. + [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; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/JpegTables.cs b/src/Febe.Core/Codecs/Images/JpegTables.cs new file mode 100644 index 0000000..f8597b5 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/JpegTables.cs @@ -0,0 +1,136 @@ +namespace Febe.Core.Codecs.Images; + +/// Fixed tables of ITU-T T.81: the zig-zag order and the example tables of Annex K. +internal static class JpegTables +{ + /// Coefficients in a block. + public const int BlockSize = 64; + + /// + /// 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. + /// + public static readonly byte[] ZigZag = BuildZigZag(); + + /// T.81 Table K.1, luminance quantization, natural order. + public static ReadOnlySpan 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, + ]; + + /// T.81 Table K.2, chrominance quantization, natural order. + public static ReadOnlySpan 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, + ]; + + /// T.81 Table K.3 as code counts per length 1-16. + public static ReadOnlySpan LuminanceDcCounts => [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; + + /// T.81 Table K.3 symbols. + public static ReadOnlySpan LuminanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + + /// T.81 Table K.4 as code counts per length 1-16. + public static ReadOnlySpan ChrominanceDcCounts => [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; + + /// T.81 Table K.4 symbols. + public static ReadOnlySpan ChrominanceDcValues => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; + + /// T.81 Table K.5 as code counts per length 1-16. + public static ReadOnlySpan LuminanceAcCounts => [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7D]; + + /// T.81 Table K.5 symbols (run/size), in code order. + public static ReadOnlySpan 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, + ]; + + /// T.81 Table K.6 as code counts per length 1-16. + public static ReadOnlySpan ChrominanceAcCounts => [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; + + /// T.81 Table K.6 symbols (run/size), in code order. + public static ReadOnlySpan 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, + ]; + + /// + /// 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. + /// + public static ushort[] ScaledQuantization(ReadOnlySpan 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; + } +} diff --git a/src/Febe.Core/Codecs/Images/PngDecoder.cs b/src/Febe.Core/Codecs/Images/PngDecoder.cs new file mode 100644 index 0000000..7a92baa --- /dev/null +++ b/src/Febe.Core/Codecs/Images/PngDecoder.cs @@ -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; + +/// +/// 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. +/// +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 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, + ]; + + /// Whether the bytes start with the PNG signature. + public static bool IsPng(ReadOnlySpan data) => data.Length >= 8 && data[..8].SequenceEqual(ImageFormatSniffer.PngSignature); + + /// Size, frames and metadata of a PNG, without decoding the pixels. + public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits = null) + { + var file = Parse(data, limits ?? ImageLimits.Default, readMetadata: true); + return file.ToInfo(); + } + + /// Decodes a PNG to straight RGBA8. + /// The file is damaged, truncated or not a PNG. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false) + { + limits ??= ImageLimits.Default; + var file = Parse(data, limits, readMetadata: false); + return DecodePixels(data, file, limits, pooled); + } + + /// Decodes a PNG to straight RGBA8 and returns what returns as well. + public static RgbaImage Decode(ReadOnlyMemory 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; + + /// 256 RGBA entries; entries the file does not give are opaque black. + 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? Texts; + public List? 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 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 type) + { + foreach (var c in type) + { + if (!char.IsAsciiLetter((char)c)) + { + return false; + } + } + + return true; + } + + private static void ReadHeader(PngFile file, ReadOnlySpan 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 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 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 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 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; + } + + /// Inflates a zlib stream of metadata; null when it is damaged or longer than . + internal static byte[]? Inflate(ReadOnlySpan 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 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.Shared.Rent((int)maxRow + 1); + var previous = ArrayPool.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.Shared.Return(current); + ArrayPool.Shared.Return(previous); + } + } + + private static void DecodePass( + ZLibStream zlib, + PngFile file, + int width, + int height, + int bpp, + byte[] current, + byte[] previous, + Span 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; + } + } + + /// Undoes the row filter (PNG specification §7.3, §9.2): is changed in place. + internal static void Unfilter(byte filter, Span row, ReadOnlySpan 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.Count; + for (; i + width <= n; i += width) + { + (new Vector(row[i..]) + new Vector(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})."); + } + } + + /// The Paeth predictor (PNG specification §9.4). + 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; + } + + /// Converts pixels of an unfiltered row to RGBA8, one pixel every bytes. + private static void ConvertRow(PngFile file, ReadOnlySpan row, int count, Span 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(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 row, int count, Span 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(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(palette.AsSpan(index * 4))); + } + } + + private static void ConvertLowGrey(ReadOnlySpan row, int count, Span 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; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/PngEncoder.cs b/src/Febe.Core/Codecs/Images/PngEncoder.cs new file mode 100644 index 0000000..4f98482 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/PngEncoder.cs @@ -0,0 +1,475 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// What writes for the pixels. +public enum PngColorMode +{ + /// RGB when every pixel is opaque, RGBA otherwise. + Auto, + + /// 8-bit RGB (colour type 2): alpha is dropped. + Rgb, + + /// 8-bit RGBA (colour type 6). + Rgba, +} + +/// How picks the filter of each row. +public enum PngFilterStrategy +{ + /// + /// 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). + /// + Adaptive, + None, + Sub, + Up, + Average, + Paeth, +} + +/// Options of . +public sealed record PngEncoderOptions +{ + /// The options used when a caller passes none. + 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; + + /// + /// 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. + /// + public byte[]? Exif { get; init; } + + /// ICC profile to write, compressed, in an iCCP chunk. + public byte[]? IccProfile { get; init; } + + /// Name of the profile in the iCCP chunk: 1 to 79 Latin-1 characters. + public string IccProfileName { get; init; } = "ICC Profile"; + + /// XMP packet to write in an uncompressed iTXt chunk with the keyword «XML:com.adobe.xmp». + public string? Xmp { get; init; } + + /// + /// 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. + /// + public IReadOnlyList Texts { get; init; } = []; +} + +/// +/// 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 , optional eXIf, iCCP and XMP. +/// +public static class PngEncoder +{ + private const int IdatChunkSize = 64 * 1024; + + /// The PNG file of . + public static byte[] Encode(RgbaImage image, PngEncoderOptions? options = null) + { + using var output = new MemoryStream(); + Encode(image, output, options); + return output.ToArray(); + } + + /// Writes the PNG file of to . + 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 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.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 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); + } + } + + /// + /// Writes the filter byte and the filtered row to and returns the sum of the absolute + /// values of the filtered bytes, read as signed. + /// + internal static long Filter(byte filter, ReadOnlySpan row, ReadOnlySpan previous, int bpp, Span 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 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(); + } + + /// Whether can name a PNG text chunk: 1-79 printable Latin-1, no outer or double spaces. + 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 type, ReadOnlySpan payload) + { + Span 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); + } + + /// Collects the zlib stream and writes it out as IDAT chunks of bytes. + private sealed class IdatStream(Stream output) : Stream + { + private readonly byte[] _buffer = ArrayPool.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 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(); + } + } + } + + /// Writes the last, shorter chunk. + 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.Shared.Return(_buffer); + } + + base.Dispose(disposing); + } + + private void Emit() + { + WriteChunk(output, "IDAT"u8, _buffer.AsSpan(0, _count)); + _count = 0; + } + } +} diff --git a/src/Febe.Core/Codecs/Images/RgbaImage.cs b/src/Febe.Core/Codecs/Images/RgbaImage.cs new file mode 100644 index 0000000..a64aa6a --- /dev/null +++ b/src/Febe.Core/Codecs/Images/RgbaImage.cs @@ -0,0 +1,146 @@ +using System.Buffers; + +namespace Febe.Core.Codecs.Images; + +/// +/// A decoded image: × 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). +/// +/// +/// The pixels live either in an array of exactly the right size () or in a rented +/// array (: from up to 16 MiB, a plain array above, so that very +/// large pictures are not kept by the pool), which 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. +/// +public sealed class RgbaImage : IDisposable +{ + /// Bytes of one pixel. + public const int BytesPerPixel = 4; + + private byte[]? _buffer; + private readonly bool _pooled; + + /// A new image, every pixel (0, 0, 0, 0). + public RgbaImage(int width, int height) + : this(width, height, new byte[CheckedLength(width, height)], pooled: false) + { + } + + /// An image over , which must hold exactly width × height × 4 bytes; not copied. + 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; + } + + /// + /// 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 . + /// + public static RgbaImage Rent(int width, int height) + { + var length = CheckedLength(width, height); + var buffer = ImageBuffers.Rent(length); + buffer.AsSpan(0, length).Clear(); + return new RgbaImage(width, height, buffer, pooled: true); + } + + /// A new image for a decoder: size checked against , pooled or not. + 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); + } + + /// Width in pixels. + public int Width { get; } + + /// Height in pixels. + public int Height { get; } + + /// Bytes of one row ( × 4). + public int Stride => Width * BytesPerPixel; + + /// Bytes of the whole image. + public int Length { get; } + + /// Whether the pixels were rented with (and must not be used after ). + public bool IsPooled => _pooled; + + /// All the pixels, row after row. + public Span Pixels => Buffer.AsSpan(0, Length); + + /// The pixels of row (0 is the top row). + public Span GetRow(int y) + { + ArgumentOutOfRangeException.ThrowIfNegative(y); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(y, Height); + return Buffer.AsSpan(y * Stride, Stride); + } + + /// The pixel at (, ) as R, G, B, A. + 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]); + } + + /// Whether every pixel has alpha 255. + public bool IsOpaque() + { + var pixels = Pixels; + for (var i = 3; i < pixels.Length; i += BytesPerPixel) + { + if (pixels[i] != 255) + { + return false; + } + } + + return true; + } + + /// A copy of the pixels in an array of exactly bytes. + public byte[] ToArray() => Pixels.ToArray(); + + /// Gives a rented array back; the image cannot be used afterwards. + 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; + } +} diff --git a/src/Febe.Core/Codecs/Images/SegmentStream.cs b/src/Febe.Core/Codecs/Images/SegmentStream.cs new file mode 100644 index 0000000..fd8e3fe --- /dev/null +++ b/src/Febe.Core/Codecs/Images/SegmentStream.cs @@ -0,0 +1,66 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +internal sealed class SegmentStream(ReadOnlyMemory 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 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 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(); +} diff --git a/src/Febe.Core/Codecs/Images/Vp8BoolDecoder.cs b/src/Febe.Core/Codecs/Images/Vp8BoolDecoder.cs new file mode 100644 index 0000000..4f13a4f --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8BoolDecoder.cs @@ -0,0 +1,131 @@ +using System.Numerics; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// The boolean entropy decoder of VP8 (RFC 6386 §7): each call decodes one bit whose probability of being 0 is +/// prob/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. +/// +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(); + } + + /// + /// 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. + /// + 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; + } + + /// An unsigned value of bits, most significant first, each with probability ½ (L(n)). + public int GetLiteral(int bits) + { + var v = 0; + while (bits-- > 0) + { + v = (v << 1) | GetBit(128); + } + + return v; + } + + /// A magnitude of bits followed by a sign bit, as the frame header writes deltas. + public int GetSignedLiteral(int bits) + { + var v = GetLiteral(bits); + return GetBit(128) == 1 ? -v : v; + } + + /// An optional signed delta: a flag, then ; 0 when the flag is clear. + public int GetOptionalSigned(int bits) => GetBit(128) == 1 ? GetSignedLiteral(bits) : 0; + + /// + /// 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 probs[offset + i/2]. + /// + public int ReadTree(ReadOnlySpan tree, ReadOnlySpan 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; + } + } + } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8Decoder.cs b/src/Febe.Core/Codecs/Images/Vp8Decoder.cs new file mode 100644 index 0000000..c64d967 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8Decoder.cs @@ -0,0 +1,871 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +/// +/// 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. +/// +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; + } + + /// The size of a VP8 key frame, after checking its frame tag and start code. + /// The bytes are not a VP8 key frame that can be shown. + public static (int Width, int Height) ReadSize(ReadOnlySpan 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); + } + + /// + /// Decodes the VP8 frame in [..+] into + /// , which must have the frame's size; every alpha byte is set to 255. + /// + 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(); + } + } + + /// + /// 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). + /// + 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((int)lumaBytes); + _u = ImageBuffers.Rent((int)(lumaBytes / 4)); + _v = ImageBuffers.Rent((int)(lumaBytes / 4)); + _mbSegment = ImageBuffers.Rent(_mbWidth * _mbHeight); + _mbFlags = ImageBuffers.Rent(_mbWidth * _mbHeight); + _intraTop = ImageBuffers.Rent(_mbWidth * 4); + _nzTop = ImageBuffers.Rent(_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 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 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.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; + + /// Edge limit, interior limit and threshold for a macroblock, and whether its inner edges are filtered. + 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); + } +} + +/// BT.601 YUV (studio range) to RGB in 16-bit fixed point. +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 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 f) + { + var table = new int[256]; + for (var i = 0; i < 256; i++) + { + table[i] = f(i); + } + + return table; + } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs b/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs new file mode 100644 index 0000000..f1117eb --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8LDecoder.cs @@ -0,0 +1,721 @@ +using System.Buffers; +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +internal sealed class Vp8LDecoder +{ + /// The byte every VP8L bitstream starts with. + 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 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 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; + } + + /// Size and alpha hint of a VP8L bitstream, from its five-byte header. + /// The bytes are not a VP8L header. + public static (int Width, int Height, bool AlphaUsed) ReadHeader(ReadOnlySpan 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); + } + + /// Decodes a whole VP8L bitstream into , which must have its size. + 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); + } + } + + /// + /// 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. + /// + public static void DecodeAlpha(byte[] data, int start, int length, int width, int height, ImageLimits limits, Span 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(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((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 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); + } + + /// Reads one prefix code; with false it is only checked, and null comes back. + 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 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)); + } + + /// The (dx, dy) of short distance code 1-120. + 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 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."); +} diff --git a/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs b/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs new file mode 100644 index 0000000..1ee3fb2 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8LHuffman.cs @@ -0,0 +1,301 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +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(); + } + + /// Whether bits past the end of the data were consumed. + public bool EndOfStream { get; private set; } + + /// Reads bits (0-24), least significant first. + 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; + } + + /// At least 32 bits ready for when the data has them; zeros past the end. + 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; + } + } +} + +/// +/// 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. +/// +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; + } + + /// The symbol of a code that has only one (read with zero bits), or −1. + public int SingleSymbol { get; } + + /// Entries of the decoding tables, for the memory budget. + public int TableSize => _table.Length; + + /// + /// Whether would accept , without building any table: for the codes + /// of groups that no pixel uses. + /// + public static bool IsValid(ReadOnlySpan 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); + } + + /// + /// 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. + /// + public static Vp8LHuffman? Build(ReadOnlySpan lengths) + { + Span 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 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 longest = stackalloc byte[1 << RootBits]; + longest.Clear(); + var codes = new int[lengths.Length]; + { + Span 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 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); + } + + /// Reads one symbol. + 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; + } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs new file mode 100644 index 0000000..7e67ca8 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs @@ -0,0 +1,1074 @@ +using System.Buffers; + +namespace Febe.Core.Codecs.Images; + +/// Writes bits least significant first, as WebP lossless reads them. +internal sealed class Vp8LBitWriter +{ + private byte[] _buffer; + private int _length; + private ulong _accumulator; + private int _bits; + + public Vp8LBitWriter(int capacity = 4096) + { + _buffer = new byte[Math.Max(16, capacity)]; + } + + /// Bits written so far. + public long BitLength => ((long)_length * 8) + _bits; + + /// Writes the low bits (0-32) of . + public void WriteBits(uint value, int n) + { + if (n == 0) + { + return; + } + + _accumulator |= (ulong)(value & (uint)((1UL << n) - 1)) << _bits; + _bits += n; + while (_bits >= 8) + { + if (_length == _buffer.Length) + { + Array.Resize(ref _buffer, _buffer.Length * 2); + } + + _buffer[_length++] = (byte)_accumulator; + _accumulator >>= 8; + _bits -= 8; + } + } + + /// The bytes written, the last one padded with zero bits. + public byte[] ToArray() + { + var result = new byte[_length + (_bits > 0 ? 1 : 0)]; + _buffer.AsSpan(0, _length).CopyTo(result); + if (_bits > 0) + { + result[_length] = (byte)_accumulator; + } + + return result; + } +} + +/// A prefix code for writing: the length and the bit-reversed canonical code of every symbol. +internal sealed class Vp8LPrefixCode +{ + private Vp8LPrefixCode(byte[] lengths, ushort[] codes, bool single) + { + Lengths = lengths; + Codes = codes; + IsSingle = single; + } + + /// The code length of each symbol (0 when unused). + public byte[] Lengths { get; } + + /// The code of each symbol, reversed so that it is written least significant bit first. + public ushort[] Codes { get; } + + /// Whether at most one symbol is used: it is then written with zero bits. + public bool IsSingle { get; } + + public void Write(Vp8LBitWriter writer, int symbol) + { + if (!IsSingle) + { + writer.WriteBits(Codes[symbol], Lengths[symbol]); + } + } + + /// The length-limited code for the given symbol counts. + public static Vp8LPrefixCode FromCounts(ReadOnlySpan counts, int maxLength) + { + var lengths = new byte[counts.Length]; + var used = 0; + var last = 0; + for (var i = 0; i < counts.Length; i++) + { + if (counts[i] > 0) + { + used++; + last = i; + } + } + + if (used <= 1) + { + lengths[last] = 1; + return new Vp8LPrefixCode(lengths, new ushort[counts.Length], single: true); + } + + HuffmanLengths(counts, maxLength, lengths); + return new Vp8LPrefixCode(lengths, CanonicalCodes(lengths), single: false); + } + + private static ushort[] CanonicalCodes(byte[] lengths) + { + Span count = stackalloc int[Vp8LHuffman.MaxCodeLength + 1]; + foreach (var len in lengths) + { + count[len]++; + } + + count[0] = 0; + Span next = stackalloc int[Vp8LHuffman.MaxCodeLength + 2]; + var code = 0; + for (var len = 1; len <= Vp8LHuffman.MaxCodeLength; len++) + { + code = (code + count[len - 1]) << 1; + next[len] = code; + } + + var codes = new ushort[lengths.Length]; + for (var s = 0; s < lengths.Length; s++) + { + if (lengths[s] > 0) + { + codes[s] = (ushort)Vp8LHuffman.Reverse(next[lengths[s]]++, lengths[s]); + } + } + + return codes; + } + + // Huffman code lengths of the used symbols, at most maxLength: if the tree is too deep, the counts are flattened + // (divided, keeping every used symbol at least 1) and the tree is built again. + private static void HuffmanLengths(ReadOnlySpan counts, int maxLength, byte[] lengths) + { + var n = counts.Length; + var weights = new long[2 * n]; + var parent = new int[2 * n]; + var depth = new int[2 * n]; + for (var shift = 0; ; shift++) + { + var queue = new PriorityQueue(); + var nodes = 0; + var leaves = new List(); + for (var s = 0; s < n; s++) + { + if (counts[s] > 0) + { + var w = Math.Max(1L, (long)counts[s] >> shift); + weights[nodes] = w; + leaves.Add(s); + queue.Enqueue(nodes, (w << 20) | (uint)nodes); + nodes++; + } + } + + var leafCount = nodes; + while (queue.Count > 1) + { + var a = queue.Dequeue(); + var b = queue.Dequeue(); + weights[nodes] = weights[a] + weights[b]; + parent[a] = nodes; + parent[b] = nodes; + queue.Enqueue(nodes, (weights[nodes] << 20) | (uint)nodes); + nodes++; + } + + var root = nodes - 1; + depth[root] = 0; + var max = 0; + for (var i = root - 1; i >= 0; i--) + { + depth[i] = depth[parent[i]] + 1; + if (i < leafCount) + { + max = Math.Max(max, depth[i]); + } + } + + if (max <= maxLength) + { + Array.Clear(lengths); + for (var i = 0; i < leafCount; i++) + { + lengths[leaves[i]] = (byte)depth[i]; + } + + return; + } + } + } +} + +/// +/// The encoder of WebP lossless (RFC 9649 §3) behind : colour indexing for images of at most +/// 256 colours, otherwise subtract green, the predictor transform (the mode of each block chosen by the smallest sum +/// of residuals) and the colour transform (factors from a least-squares estimate refined by search), then LZ77 with +/// hash chains, a colour cache whose size is chosen by estimated entropy, and length-limited Huffman codes. +/// +internal static class Vp8LEncoder +{ + private const uint HashMultiplier = 0x1E35A7BD; + private const int MaxLength = 4096; + private const int MaxDistance = (1 << 20) - 120; + private const int HashBits = 18; + private const int NumLengthCodes = 24; + + private static ReadOnlySpan CodeLengthOrder => [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + + /// The image stream for (transforms, colour cache, codes, data), without header. + public static void WriteImageStream(Vp8LBitWriter writer, uint[] argb, int width, int height, Vp8LEncoderSettings settings) + { + var pixels = argb.AsSpan(0, width * height).ToArray(); + var xsize = width; + if (settings.Palette && TryPalette(pixels, out var palette)) + { + writer.WriteBits(1, 1); + writer.WriteBits(3, 2); + writer.WriteBits((uint)(palette.Length - 1), 8); + var deltas = new uint[palette.Length]; + deltas[0] = palette[0]; + for (var i = 1; i < palette.Length; i++) + { + deltas[i] = Vp8LDecoder.SubtractPixels(palette[i], palette[i - 1]); + } + + WriteEntropyImage(writer, deltas, palette.Length, 1, settings); + pixels = Bundle(pixels, width, height, palette, out xsize); + } + else + { + if (settings.SubtractGreen) + { + writer.WriteBits(1, 1); + writer.WriteBits(2, 2); + SubtractGreen(pixels); + } + + if (settings.Predictor) + { + writer.WriteBits(1, 1); + writer.WriteBits(0, 2); + writer.WriteBits((uint)(settings.PredictorBits - 2), 3); + var modes = ApplyPredictor(pixels, width, height, settings.PredictorBits); + WriteEntropyImage(writer, modes, Vp8LDecoder.DivRoundUp(width, settings.PredictorBits), Vp8LDecoder.DivRoundUp(height, settings.PredictorBits), settings); + } + + if (settings.ColorTransform) + { + writer.WriteBits(1, 1); + writer.WriteBits(1, 2); + writer.WriteBits((uint)(settings.ColorTransformBits - 2), 3); + var elements = ApplyColorTransform(pixels, width, height, settings.ColorTransformBits); + WriteEntropyImage(writer, elements, Vp8LDecoder.DivRoundUp(width, settings.ColorTransformBits), Vp8LDecoder.DivRoundUp(height, settings.ColorTransformBits), settings); + } + } + + writer.WriteBits(0, 1); // no more transforms + WriteCoded(writer, pixels, xsize, height, settings, mainImage: true); + } + + private static void WriteEntropyImage(Vp8LBitWriter writer, uint[] pixels, int width, int height, Vp8LEncoderSettings settings) => + WriteCoded(writer, pixels, width, height, settings with { ColorCacheBits = 0 }, mainImage: false); + + // Colour cache info, (for the main image) no meta prefix codes, the five codes and the data. + private static void WriteCoded(Vp8LBitWriter writer, uint[] pixels, int width, int height, Vp8LEncoderSettings settings, bool mainImage) + { + var count = width * height; + var lengths = ImageBuffers.Rent(count); + var distances = ImageBuffers.Rent(count); + try + { + var tokens = settings.Lz77 ? FindMatches(pixels, width, count, settings.ChainLength, lengths, distances) : Literals(count, lengths); + var cacheBits = settings.ColorCacheBits ?? ChooseCacheBits(pixels, lengths.AsSpan(0, tokens)); + writer.WriteBits(cacheBits > 0 ? 1u : 0u, 1); + if (cacheBits > 0) + { + writer.WriteBits((uint)cacheBits, 4); + } + + if (mainImage) + { + writer.WriteBits(0, 1); // one group of prefix codes for the whole image + } + + var cacheSize = cacheBits > 0 ? 1 << cacheBits : 0; + var green = new int[256 + NumLengthCodes + cacheSize]; + var red = new int[256]; + var blue = new int[256]; + var alpha = new int[256]; + var distance = new int[40]; + var cache = cacheBits > 0 ? new uint[cacheSize] : null; + var shift = 32 - cacheBits; + + // First pass: the symbols, to count them; second pass: write them with the codes. + for (var pass = 0; pass < 2; pass++) + { + Vp8LPrefixCode? gc = null, rc = null, bc = null, ac = null, dc = null; + if (pass == 1) + { + gc = Vp8LPrefixCode.FromCounts(green, Vp8LHuffman.MaxCodeLength); + rc = Vp8LPrefixCode.FromCounts(red, Vp8LHuffman.MaxCodeLength); + bc = Vp8LPrefixCode.FromCounts(blue, Vp8LHuffman.MaxCodeLength); + ac = Vp8LPrefixCode.FromCounts(alpha, Vp8LHuffman.MaxCodeLength); + dc = Vp8LPrefixCode.FromCounts(distance, Vp8LHuffman.MaxCodeLength); + WriteCode(writer, gc); + WriteCode(writer, rc); + WriteCode(writer, bc); + WriteCode(writer, ac); + WriteCode(writer, dc); + if (cache is not null) + { + Array.Clear(cache); + } + } + + var pos = 0; + for (var t = 0; t < tokens; t++) + { + var length = lengths[t]; + if (length == 0) + { + var p = pixels[pos++]; + var key = cache is null ? 0 : (int)((HashMultiplier * p) >> shift); + if (cache is not null && cache[key] == p) + { + if (pass == 0) + { + green[256 + NumLengthCodes + key]++; + } + else + { + gc!.Write(writer, 256 + NumLengthCodes + key); + } + } + else + { + int g = (byte)(p >> 8), r = (byte)(p >> 16), b = (byte)p, a = (byte)(p >> 24); + if (pass == 0) + { + green[g]++; + red[r]++; + blue[b]++; + alpha[a]++; + } + else + { + gc!.Write(writer, g); + rc!.Write(writer, r); + bc!.Write(writer, b); + ac!.Write(writer, a); + } + + if (cache is not null) + { + cache[key] = p; + } + } + + continue; + } + + var (lengthSymbol, lengthBits, lengthExtra) = Prefix(length); + var (distanceSymbol, distanceBits, distanceExtra) = Prefix(DistanceCode(distances[t], width)); + if (pass == 0) + { + green[256 + lengthSymbol]++; + distance[distanceSymbol]++; + } + else + { + gc!.Write(writer, 256 + lengthSymbol); + writer.WriteBits((uint)lengthExtra, lengthBits); + dc!.Write(writer, distanceSymbol); + writer.WriteBits((uint)distanceExtra, distanceBits); + } + + if (cache is not null) + { + for (var k = 0; k < length; k++) + { + var p = pixels[pos + k]; + cache[(HashMultiplier * p) >> shift] = p; + } + } + + pos += length; + } + } + } + finally + { + ImageBuffers.Return(lengths); + ImageBuffers.Return(distances); + } + } + + private static int Literals(int count, int[] lengths) + { + lengths.AsSpan(0, count).Clear(); + return count; + } + + // Greedy LZ77 over hash chains of pixel pairs; the distances 1 (left) and width (above) are always tried. Fills + // one entry per token: length 0 for a literal pixel, else the length and the distance of a backward reference. + private static int FindMatches(uint[] pixels, int width, int count, int chainLength, int[] lengths, int[] distances) + { + var head = ArrayPool.Shared.Rent(1 << HashBits); + var previous = ImageBuffers.Rent(count); + try + { + head.AsSpan(0, 1 << HashBits).Fill(-1); + var tokens = 0; + var i = 0; + while (i < count) + { + var bestLength = 0; + var bestDistance = 0; + var limit = Math.Min(MaxLength, count - i); + if (limit >= 2) + { + TryMatch(pixels, i, 1, limit, ref bestLength, ref bestDistance); + if (width > 1) + { + TryMatch(pixels, i, width, limit, ref bestLength, ref bestDistance); + } + + var candidate = head[Hash(pixels, i)]; + for (var c = 0; c < chainLength && candidate >= 0 && bestLength < limit; c++) + { + var d = i - candidate; + if (d > MaxDistance) + { + break; + } + + TryMatch(pixels, i, d, limit, ref bestLength, ref bestDistance); + candidate = previous[candidate]; + } + } + + var cheap = bestDistance == 1 || bestDistance == width; + if (bestLength >= 3 || (bestLength == 2 && cheap)) + { + lengths[tokens] = bestLength; + distances[tokens] = bestDistance; + tokens++; + for (var k = 0; k < bestLength; k++) + { + Insert(pixels, i + k, count, head, previous); + } + + i += bestLength; + } + else + { + lengths[tokens] = 0; + tokens++; + Insert(pixels, i, count, head, previous); + i++; + } + } + + return tokens; + } + finally + { + ArrayPool.Shared.Return(head); + ImageBuffers.Return(previous); + } + } + + private static void TryMatch(uint[] pixels, int i, int distance, int limit, ref int bestLength, ref int bestDistance) + { + if (distance > i || distance <= 0) + { + return; + } + + var from = i - distance; + if (bestLength >= limit || (bestLength > 0 && pixels[from + bestLength] != pixels[i + bestLength])) + { + return; + } + + var length = 0; + while (length < limit && pixels[from + length] == pixels[i + length]) + { + length++; + } + + if (length > bestLength) + { + bestLength = length; + bestDistance = distance; + } + } + + private static void Insert(uint[] pixels, int i, int count, int[] head, int[] previous) + { + if (i + 1 >= count) + { + return; + } + + var h = Hash(pixels, i); + previous[i] = head[h]; + head[h] = i; + } + + private static int Hash(uint[] pixels, int i) + { + var next = i + 1 < pixels.Length ? pixels[i + 1] : 0; + var key = (pixels[i] * HashMultiplier) ^ (next * 0x9E3779B1); + return (int)(key >> (32 - HashBits)); + } + + // RFC 9649 §3.6: a distance as a distance code, using the 120 short codes for neighbours when one matches. + internal static int DistanceCode(int distance, int width) + { + for (var dy = 0; dy <= 7; dy++) + { + var dx = distance - (dy * width); + if (dx is >= -7 and <= 8) + { + var index = ShortCodes[(dy * 16) + (dx + 7)]; + if (index > 0) + { + return index; + } + } + } + + return distance + 120; + } + + // ShortCodes[dy * 16 + dx + 7] = 1-based short distance code of (dx, dy), 0 when there is none. + private static readonly int[] ShortCodes = BuildShortCodes(); + + private static int[] BuildShortCodes() + { + var table = new int[8 * 16]; + for (var code = 1; code <= 120; code++) + { + var (dx, dy) = Vp8LDecoder.ShortDistance(code); + table[(dy * 16) + dx + 7] = code; + } + + return table; + } + + /// The prefix symbol, the number of extra bits and their value for a length or distance code ≥ 1. + internal static (int Symbol, int Bits, int Extra) Prefix(int value) + { + var d = value - 1; + if (d < 4) + { + return (d, 0, 0); + } + + var high = 31 - System.Numerics.BitOperations.LeadingZeroCount((uint)d); + var second = (d >> (high - 1)) & 1; + var bits = high - 1; + return ((2 * high) + second, bits, d & ((1 << bits) - 1)); + } + + // Estimates, for cache sizes 0-10, the entropy of the symbols the cache would produce; returns the cheapest. + private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan lengths) + { + var bestBits = 0; + var bestCost = double.MaxValue; + var green = new int[256 + NumLengthCodes + (1 << 10)]; + var red = new int[256]; + var blue = new int[256]; + var alpha = new int[256]; + foreach (var bits in (ReadOnlySpan)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + { + Array.Clear(green); + Array.Clear(red); + Array.Clear(blue); + Array.Clear(alpha); + var cache = bits > 0 ? new uint[1 << bits] : null; + var shift = 32 - bits; + var pos = 0; + foreach (var length in lengths) + { + if (length > 0) + { + if (cache is not null) + { + for (var k = 0; k < length; k++) + { + var q = pixels[pos + k]; + cache[(HashMultiplier * q) >> shift] = q; + } + } + + pos += length; + continue; + } + + var p = pixels[pos++]; + if (cache is not null) + { + var key = (int)((HashMultiplier * p) >> shift); + if (cache[key] == p) + { + green[256 + NumLengthCodes + key]++; + continue; + } + + cache[key] = p; + } + + green[(byte)(p >> 8)]++; + red[(byte)(p >> 16)]++; + blue[(byte)p]++; + alpha[(byte)(p >> 24)]++; + } + + var cost = Entropy(green) + Entropy(red) + Entropy(blue) + Entropy(alpha); + if (cost < bestCost) + { + bestCost = cost; + bestBits = bits; + } + } + + return bestBits; + } + + // Bits to code the counts with an ideal code, plus a rough price for describing the code. + private static double Entropy(ReadOnlySpan counts) + { + long total = 0; + var used = 0; + foreach (var c in counts) + { + total += c; + used += c > 0 ? 1 : 0; + } + + if (used <= 1) + { + return 8; + } + + var bits = 0.0; + foreach (var c in counts) + { + if (c > 0) + { + bits -= c * Math.Log2((double)c / total); + } + } + + return bits + (used * 4.0); + } + + // Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length + // coded with 16/17/18 and themselves Huffman coded. + private static void WriteCode(Vp8LBitWriter writer, Vp8LPrefixCode code) + { + var lengths = code.Lengths; + Span symbols = stackalloc int[2]; + var used = 0; + for (var s = 0; s < lengths.Length && used <= 2; s++) + { + if (lengths[s] > 0) + { + if (used < 2) + { + symbols[used] = s; + } + + used++; + } + } + + if (used <= 2 && symbols[0] < 256 && (used < 2 || symbols[1] < 256)) + { + writer.WriteBits(1, 1); + writer.WriteBits((uint)(used - 1), 1); + if (symbols[0] <= 1) + { + writer.WriteBits(0, 1); + writer.WriteBits((uint)symbols[0], 1); + } + else + { + writer.WriteBits(1, 1); + writer.WriteBits((uint)symbols[0], 8); + } + + if (used == 2) + { + writer.WriteBits((uint)symbols[1], 8); + } + + return; + } + + // Run-length tokens of the code lengths: (symbol, extra bits value). + var tokens = new List<(int Symbol, int Extra)>(lengths.Length); + var previous = 8; + for (var i = 0; i < lengths.Length;) + { + var value = lengths[i]; + var run = 1; + while (i + run < lengths.Length && lengths[i + run] == value) + { + run++; + } + + i += run; + if (value == 0) + { + while (run >= 11) + { + var n = Math.Min(run, 138); + tokens.Add((18, n - 11)); + run -= n; + } + + if (run >= 3) + { + tokens.Add((17, run - 3)); + run = 0; + } + + for (; run > 0; run--) + { + tokens.Add((0, 0)); + } + + continue; + } + + if (value != previous) + { + tokens.Add((value, 0)); + previous = value; + run--; + } + + while (run >= 3) + { + var n = Math.Min(run, 6); + tokens.Add((16, n - 3)); + run -= n; + } + + for (; run > 0; run--) + { + tokens.Add((value, 0)); + } + } + + Span counts = stackalloc int[19]; + counts.Clear(); + foreach (var (symbol, _) in tokens) + { + counts[symbol]++; + } + + var lengthCode = Vp8LPrefixCode.FromCounts(counts, 7); + var written = 4; + for (var i = 0; i < 19; i++) + { + if (lengthCode.Lengths[CodeLengthOrder[i]] > 0) + { + written = Math.Max(written, i + 1); + } + } + + writer.WriteBits(0, 1); + writer.WriteBits((uint)(written - 4), 4); + for (var i = 0; i < written; i++) + { + writer.WriteBits(lengthCode.Lengths[CodeLengthOrder[i]], 3); + } + + writer.WriteBits(0, 1); // the lengths of the whole alphabet follow + foreach (var (symbol, extra) in tokens) + { + lengthCode.Write(writer, symbol); + switch (symbol) + { + case 16: + writer.WriteBits((uint)extra, 2); + break; + case 17: + writer.WriteBits((uint)extra, 3); + break; + case 18: + writer.WriteBits((uint)extra, 7); + break; + } + } + } + + private static bool TryPalette(uint[] pixels, out uint[] palette) + { + var colors = new HashSet(); + foreach (var p in pixels) + { + if (colors.Add(p) && colors.Count > 256) + { + palette = []; + return false; + } + } + + palette = [.. colors]; + Array.Sort(palette); + return true; + } + + // Indices into the palette, bundled 2, 4 or 8 to a pixel for palettes of at most 16, 4 or 2 colours. + private static uint[] Bundle(uint[] pixels, int width, int height, uint[] palette, out int packedWidth) + { + var index = new Dictionary(palette.Length); + for (var i = 0; i < palette.Length; i++) + { + index[palette[i]] = i; + } + + var bits = palette.Length > 16 ? 0 : palette.Length > 4 ? 1 : palette.Length > 2 ? 2 : 3; + packedWidth = Vp8LDecoder.DivRoundUp(width, bits); + var packed = new uint[packedWidth * height]; + var bitsPerPixel = 8 >> bits; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + var i = index[pixels[(y * width) + x]]; + var at = (y * packedWidth) + (x >> bits); + packed[at] |= (uint)i << (8 + ((x & ((1 << bits) - 1)) * bitsPerPixel)); + } + } + + for (var i = 0; i < packed.Length; i++) + { + packed[i] |= 0xFF000000; + } + + return packed; + } + + private static void SubtractGreen(uint[] pixels) + { + for (var i = 0; i < pixels.Length; i++) + { + var p = pixels[i]; + var green = (p >> 8) & 0xFF; + var redBlue = (p | 0xFF00FF00) - ((green << 16) | green); + pixels[i] = (p & 0xFF00FF00) | (redBlue & 0x00FF00FF); + } + } + + // Replaces the pixels with their residuals; returns the image of modes (in the green channel). + private static uint[] ApplyPredictor(uint[] pixels, int width, int height, int bits) + { + var blocksWide = Vp8LDecoder.DivRoundUp(width, bits); + var blocksHigh = Vp8LDecoder.DivRoundUp(height, bits); + var modes = new uint[blocksWide * blocksHigh]; + var size = 1 << bits; + Span costs = stackalloc long[14]; + for (var by = 0; by < blocksHigh; by++) + { + for (var bx = 0; bx < blocksWide; bx++) + { + costs.Clear(); + var y0 = by * size; + var x0 = bx * size; + var y1 = Math.Min(height, y0 + size); + var x1 = Math.Min(width, x0 + size); + for (var y = Math.Max(1, y0); y < y1; y++) + { + for (var x = Math.Max(1, x0); x < x1; x++) + { + var i = (y * width) + x; + var p = pixels[i]; + uint left = pixels[i - 1], top = pixels[i - width], topRight = pixels[i - width + 1], topLeft = pixels[i - width - 1]; + for (var mode = 0; mode < 14; mode++) + { + costs[mode] += ResidualCost(Vp8LDecoder.SubtractPixels(p, Vp8LDecoder.Predict(mode, left, top, topRight, topLeft))); + } + } + } + + var best = 0; + for (var mode = 1; mode < 14; mode++) + { + if (costs[mode] < costs[best]) + { + best = mode; + } + } + + modes[(by * blocksWide) + bx] = 0xFF000000 | ((uint)best << 8); + } + } + + // Residuals from the original neighbours, last pixel first so that every neighbour is still original. + for (var y = height - 1; y >= 0; y--) + { + for (var x = width - 1; x >= 0; x--) + { + var i = (y * width) + x; + uint prediction; + if (y == 0) + { + prediction = x == 0 ? 0xFF000000 : pixels[i - 1]; + } + else if (x == 0) + { + prediction = pixels[i - width]; + } + else + { + var mode = (int)(modes[((y >> bits) * blocksWide) + (x >> bits)] >> 8) & 0xF; + prediction = Vp8LDecoder.Predict(mode, pixels[i - 1], pixels[i - width], pixels[i - width + 1], pixels[i - width - 1]); + } + + pixels[i] = Vp8LDecoder.SubtractPixels(pixels[i], prediction); + } + } + + return modes; + } + + private static int ResidualCost(uint residual) + { + var cost = 0; + for (var shift = 0; shift < 32; shift += 8) + { + var v = (sbyte)(residual >> shift); + cost += v < 0 ? -v : v; + } + + return cost; + } + + // Chooses green-to-red, green-to-blue and red-to-blue per block and applies the forward transform. + private static uint[] ApplyColorTransform(uint[] pixels, int width, int height, int bits) + { + var blocksWide = Vp8LDecoder.DivRoundUp(width, bits); + var blocksHigh = Vp8LDecoder.DivRoundUp(height, bits); + var elements = new uint[blocksWide * blocksHigh]; + var size = 1 << bits; + for (var by = 0; by < blocksHigh; by++) + { + for (var bx = 0; bx < blocksWide; bx++) + { + var y0 = by * size; + var x0 = bx * size; + var y1 = Math.Min(height, y0 + size); + var x1 = Math.Min(width, x0 + size); + var greenToRed = BestFactor(pixels, width, x0, x1, y0, y1, 8, 16, 0, 0, 0); + var greenToBlue = BestFactor(pixels, width, x0, x1, y0, y1, 8, 0, 0, 0, 0); + var redToBlue = BestFactor(pixels, width, x0, x1, y0, y1, 16, 0, 8, greenToBlue, 1); + elements[(by * blocksWide) + bx] = 0xFF000000 | ((uint)(byte)redToBlue << 16) | ((uint)(byte)greenToBlue << 8) | (byte)greenToRed; + for (var y = y0; y < y1; y++) + { + for (var x = x0; x < x1; x++) + { + var i = (y * width) + x; + var p = pixels[i]; + var green = (sbyte)(p >> 8); + var red = (sbyte)(p >> 16); + var newRed = (int)((p >> 16) & 0xFF) - ((greenToRed * green) >> 5); + var newBlue = (int)(p & 0xFF) - ((greenToBlue * green) >> 5) - ((redToBlue * red) >> 5); + pixels[i] = (p & 0xFF00FF00) | ((uint)(newRed & 0xFF) << 16) | (uint)(newBlue & 0xFF); + } + } + } + } + + return elements; + } + + // The factor t in [-128, 127] that minimises Σ|target − (t·source >> 5) − (prior·other >> 5)| over a block, from + // the least-squares estimate and a search around it (and 0). + private static int BestFactor(uint[] pixels, int width, int x0, int x1, int y0, int y1, int sourceShift, int targetShift, int otherShift, int prior, int usePrior) + { + long sumProduct = 0; + long sumSquares = 0; + for (var y = y0; y < y1; y++) + { + for (var x = x0; x < x1; x++) + { + var p = pixels[(y * width) + x]; + int s = (sbyte)(p >> sourceShift); + var t = Target(p, targetShift, otherShift, prior, usePrior); + sumProduct += s * t; + sumSquares += s * s; + } + } + + var estimate = sumSquares == 0 ? 0 : (int)Math.Clamp(Math.Round(32.0 * sumProduct / sumSquares), -128, 127); + var best = 0; + var bestCost = long.MaxValue; + for (var candidate = estimate - 4; candidate <= estimate + 4 + 1; candidate++) + { + var factor = candidate == estimate + 5 ? 0 : Math.Clamp(candidate, -128, 127); + long cost = 0; + for (var y = y0; y < y1 && cost < bestCost; y++) + { + for (var x = x0; x < x1; x++) + { + var p = pixels[(y * width) + x]; + int s = (sbyte)(p >> sourceShift); + var v = (sbyte)(Target(p, targetShift, otherShift, prior, usePrior) - ((factor * s) >> 5)); + cost += v < 0 ? -v : v; + } + } + + if (cost < bestCost) + { + bestCost = cost; + best = factor; + } + } + + return best; + } + + // The target channel as a signed value, less the contribution already removed by the prior factor. + private static int Target(uint p, int targetShift, int otherShift, int prior, int usePrior) + { + int t = (sbyte)(p >> targetShift); + if (usePrior == 1) + { + // Blue after green-to-blue: the source here is red, the prior factor applies to green. + t = (sbyte)(t - ((prior * (sbyte)(p >> otherShift)) >> 5)); + } + + return t; + } +} + +/// Settings of , internal so that tests can exercise each tool alone. +internal sealed record Vp8LEncoderSettings +{ + public static Vp8LEncoderSettings Default { get; } = new(); + + public bool Palette { get; init; } = true; + + public bool SubtractGreen { get; init; } = true; + + public bool Predictor { get; init; } = true; + + public int PredictorBits { get; init; } = 4; + + public bool ColorTransform { get; init; } = true; + + public int ColorTransformBits { get; init; } = 5; + + public bool Lz77 { get; init; } = true; + + public int ChainLength { get; init; } = 32; + + /// Bits of the colour cache (0 = none), or null to choose by estimated entropy. + public int? ColorCacheBits { get; init; } +} diff --git a/src/Febe.Core/Codecs/Images/Vp8Reconstruction.cs b/src/Febe.Core/Codecs/Images/Vp8Reconstruction.cs new file mode 100644 index 0000000..3e7331b --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8Reconstruction.cs @@ -0,0 +1,565 @@ +using System.Runtime.CompilerServices; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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 at. +/// +internal static class Vp8Predict +{ + /// A 16×16 luma or 8×8 chroma prediction (DC_PRED, V_PRED, H_PRED, TM_PRED). + public static void Block(Span 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; + } + } + } + + /// A 4×4 luma subblock prediction (the ten intra_bmode of RFC 6386 §12.3). + public static void Sub4x4(Span 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 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)[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 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 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; + } +} + +/// The inverse transforms of VP8 (RFC 6386 §14.3 and §14.4), exact integer arithmetic. +internal static class Vp8Transforms +{ + private const int C1 = 20091; // cos(π/8)·√2 − 1, ×65536 + private const int S1 = 35468; // sin(π/8)·√2, ×65536 + + /// + /// 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 ). + /// + public static void InverseWht(ReadOnlySpan input, Span blocks) + { + Span 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); + } + } + + /// + /// Adds the inverse DCT of (raster order) to the 4×4 pixels at : + /// 0 means an empty block, 1 only a DC coefficient, 2 any coefficients. + /// + public static void AddBlock(ReadOnlySpan coeffs, int kind, Span 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 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); +} + +/// The loop filters of VP8 (RFC 6386 §15), applied to the whole reconstructed frame in raster order. +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); + } + } + } + } + + /// + /// The simple filter over 16 pixels of an edge: crosses the edge (1 for a vertical edge), + /// moves along it; is twice the edge limit plus one. + /// + 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); +} diff --git a/src/Febe.Core/Codecs/Images/Vp8Tables.cs b/src/Febe.Core/Codecs/Images/Vp8Tables.cs new file mode 100644 index 0000000..3f6a46b --- /dev/null +++ b/src/Febe.Core/Codecs/Images/Vp8Tables.cs @@ -0,0 +1,426 @@ +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +internal static class Vp8Tables +{ + /// Intra modes of a 16×16 luma block or an 8×8 chroma block (RFC 6386 §8.1). + public const int DcPred = 0, VPred = 1, HPred = 2, TmPred = 3, BPred = 4; + + /// Modes of a 4×4 luma subblock, in the order of RFC 6386 §8.1 (intra_bmode). + 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; + + /// §11.2: kf_ymode_prob. + public static ReadOnlySpan KeyFrameYModeProbs => [145, 156, 163, 128]; + + /// §11.2: kf_uv_mode_prob. + public static ReadOnlySpan KeyFrameUvModeProbs => [142, 114, 183]; + + /// + /// §11.2: bmode_tree, as pairs of children; a child ≤ 0 is the leaf −mode, a positive child the index of the next + /// pair. + /// + public static ReadOnlySpan BModeTree => + [ + -BDc, 2, + -BTm, 4, + -BVe, 6, + 8, 12, + -BHe, 10, + -BRd, -BVr, + -BLd, 14, + -BVl, 16, + -BHd, -BHu, + ]; + + /// + /// §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. + /// + public static ReadOnlySpan 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, + ]; + + /// §14.1: dc_qlookup. + public static ReadOnlySpan 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, + ]; + + /// §14.1: ac_qlookup. + public static ReadOnlySpan 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, + ]; + + /// §13: the zigzag scan, from position in the token stream to raster index in the 4×4 block. + public static ReadOnlySpan Zigzag => [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + + /// §13.3: the band of each coefficient position (a 17th entry, never a real position, keeps lookups simple). + public static ReadOnlySpan Bands => [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]; + + /// §13.2: the probabilities of the extra bits of DCT_CAT3 to DCT_CAT6 (cat1 and cat2 are read inline). + public static ReadOnlySpan Cat3 => [173, 148, 140]; + + public static ReadOnlySpan Cat4 => [176, 155, 140, 135]; + + public static ReadOnlySpan Cat5 => [180, 157, 141, 134, 130]; + + public static ReadOnlySpan Cat6 => [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129]; + + /// Number of token probabilities: 4 block types × 8 bands × 3 contexts × 11 tree nodes. + public const int CoefficientProbCount = 4 * 8 * 3 * 11; + + /// §13.5: default_coeff_probs, flattened [type][band][context][node]. + public static ReadOnlySpan 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, + ]; + + /// §13.4: coeff_update_probs, flattened like . + public static ReadOnlySpan 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, + ]; +} diff --git a/src/Febe.Core/Codecs/Images/WebPDecoder.cs b/src/Febe.Core/Codecs/Images/WebPDecoder.cs new file mode 100644 index 0000000..b96bdc6 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/WebPDecoder.cs @@ -0,0 +1,511 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// +/// 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. +/// +/// +/// Strictness, as for PNG: data that ends before the last pixel of a picture is damaged (), +/// 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 are skipped. +/// +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 " + + /// Whether the bytes start like a WebP file (a RIFF of form WEBP). + public static bool IsWebP(ReadOnlySpan data) => + data.Length >= 12 && data[..4].SequenceEqual("RIFF"u8) && data.Slice(8, 4).SequenceEqual("WEBP"u8); + + /// Size, frames and metadata of a WebP, without decoding the pixels. + /// The file is damaged or not a WebP. + public static ImageInfo Identify(ReadOnlyMemory 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(); + } + + /// Decodes a WebP to straight RGBA8 (the first frame of an animation, on its canvas). + /// The file is damaged, truncated or not a WebP. + /// The image is larger than allow. + public static RgbaImage Decode(ReadOnlyMemory data, ImageLimits? limits = null, bool pooled = false) => + Decode(data, out _, limits, pooled, readMetadata: false); + + /// Decodes a WebP to straight RGBA8 and returns what returns as well. + public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits = null, bool pooled = false) => + Decode(data, out info, limits, pooled, readMetadata: true); + + private static RgbaImage Decode(ReadOnlyMemory 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); + + /// A picture: its bitstream chunk (VP8 or VP8L) and, for VP8, its optional ALPH chunk. + 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 ReadChunks(byte[] data, int start, int length) + { + var chunks = new List(); + 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)); + } + } + } + + /// + /// 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. + /// + internal static void Blend(ReadOnlySpan source, Span 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 b) => (uint)(b[0] | (b[1] << 8) | (b[2] << 16)); + + private static byte[] AsArray(ReadOnlyMemory 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(); + } +} + +/// The ALPH chunk of RFC 9649 §2.7.1.2: raw or VP8L-compressed alpha, then the inverse of its filter. +internal static class WebPAlpha +{ + /// Decodes the alpha plane of the chunk payload and writes it into the alpha bytes of . + 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(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); + } + } + + /// + /// 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. + /// + internal static void Unfilter(Span 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; + } + } + } +} diff --git a/src/Febe.Core/Codecs/Images/WebPEncoder.cs b/src/Febe.Core/Codecs/Images/WebPEncoder.cs new file mode 100644 index 0000000..a94c12f --- /dev/null +++ b/src/Febe.Core/Codecs/Images/WebPEncoder.cs @@ -0,0 +1,183 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Images; + +/// Options of . +public sealed record WebPEncoderOptions +{ + /// The options used when a caller passes none. + public static WebPEncoderOptions Default { get; } = new(); + + /// + /// 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. + /// + public byte[]? Exif { get; init; } + + /// ICC profile to write in an ICCP chunk. + public byte[]? IccProfile { get; init; } + + /// XMP packet to write in an XMP chunk (UTF-8). + public string? Xmp { get; init; } + + /// The tools of the lossless encoder (tests turn them on and off one by one). + internal Vp8LEncoderSettings Lossless { get; init; } = Vp8LEncoderSettings.Default; +} + +/// +/// 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. +/// +public static class WebPEncoder +{ + /// Largest width or height a WebP picture can have. + public const int MaxDimension = 16384; + + /// The WebP file of . + /// The image is wider or taller than . + /// The EXIF block is not a TIFF structure. + public static byte[] Encode(RgbaImage image, WebPEncoderOptions? options = null) + { + using var output = new MemoryStream(); + Encode(image, output, options); + return output.ToArray(); + } + + /// Writes the WebP file of to . + 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 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 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); + } + } + + /// The VP8L bitstream (signature, header, image stream) of . + 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(); + } + + /// + /// The headerless image stream of an ALPH chunk compressed with VP8L: the alpha values in the green channel. + /// + internal static byte[] EncodeAlphaStream(ReadOnlySpan 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 type, ReadOnlySpan payload) + { + Span 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 destination, int value) + { + destination[0] = (byte)value; + destination[1] = (byte)(value >> 8); + destination[2] = (byte)(value >> 16); + } + + private static byte[] ExifPayload(byte[] exif) + { + ReadOnlySpan 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(); + } +} diff --git a/src/Febe.Core/Collection/Requests/RequestCatalog.cs b/src/Febe.Core/Collection/Requests/RequestCatalog.cs index bd3ff7a..360d294 100644 --- a/src/Febe.Core/Collection/Requests/RequestCatalog.cs +++ b/src/Febe.Core/Collection/Requests/RequestCatalog.cs @@ -57,12 +57,14 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument) /// page section of the catalog says where to read (): lsd, fb_dtsg, /// app_id, account_id, and since S4 rev (__rev), hs (__hs), hsi /// (__hsi), dpr, ccg (__ccg), comet_req (__comet_req) and - /// entry_nonce (x-fb-entry-nonce). + /// entry_nonce (x-fb-entry-nonce), and since S4b spin_r, spin_b and spin_t + /// (__spin_r, __spin_b, __spin_t: a snapshot of the page at «Ho finito», decision of 18 November + /// 2026). /// public static IReadOnlySet SessionFields { get; } = new[] { "user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id", - "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", + "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t", }.ToFrozenSet(StringComparer.Ordinal); /// The session fields that need no page entry: the browser's user agent and the claim the site sets (H13). diff --git a/src/Febe.Core/Collection/Requests/SessionCopySettings.cs b/src/Febe.Core/Collection/Requests/SessionCopySettings.cs new file mode 100644 index 0000000..8a7194b --- /dev/null +++ b/src/Febe.Core/Collection/Requests/SessionCopySettings.cs @@ -0,0 +1,65 @@ +using Febe.Core.Storage; + +namespace Febe.Core.Collection.Requests; + +/// What a copy of the browser's session does when some value the requests need is missing (issue #36, S4b). +public enum IncompleteCopyChoice +{ + /// + /// «Sostituisci comunque» (the default): the new copy replaces the saved one all the same, because keeping an older + /// copy could keep the cookies of another login (§6.0). + /// + Replace, + + /// + /// «Tieni la copia completa»: when the saved copy has every value the configured operations need and the new one + /// does not, the saved one stays and the message says so. + /// + KeepComplete, +} + +/// +/// The settings of the copy of the session (issue #36, S4b; decision of Alberto of 18 November 2026, answer 9), in the +/// setting table like the other settings. Read at every copy: a change holds from the next copy, no restart. +/// +/// What an incomplete copy does. +public sealed record SessionCopySettings(IncompleteCopyChoice IncompleteCopy) +{ + /// The key of : sostituisci or tieni-completa. + public const string IncompleteCopyKey = "sessione.copia-incompleta"; + + /// The text of in the table and in the API. + public const string ReplaceText = "sostituisci"; + + /// The text of in the table and in the API. + public const string KeepCompleteText = "tieni-completa"; + + /// The settings of a database that never stored them: an incomplete copy replaces the saved one. + public static SessionCopySettings Default { get; } = new(IncompleteCopyChoice.Replace); + + /// The text of . + public static string ToText(IncompleteCopyChoice choice) => choice == IncompleteCopyChoice.KeepComplete ? KeepCompleteText : ReplaceText; + + /// The choice of ; null for any other text. + public static IncompleteCopyChoice? Parse(string? text) => text switch + { + ReplaceText => IncompleteCopyChoice.Replace, + KeepCompleteText => IncompleteCopyChoice.KeepComplete, + _ => null, + }; + + /// The stored settings; an unknown or missing value is the default. + public static async Task LoadAsync(ISettingsStore settings, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(settings); + var text = await settings.GetAsync(IncompleteCopyKey, ct).ConfigureAwait(false); + return Parse(text) is { } choice ? new SessionCopySettings(choice) : Default; + } + + /// Stores these settings. + public Task SaveAsync(ISettingsStore settings, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(settings); + return settings.SetAsync(IncompleteCopyKey, ToText(IncompleteCopy), ct); + } +} diff --git a/src/Febe.Core/Config/richieste.instagram.json b/src/Febe.Core/Config/richieste.instagram.json index 5c9ebd1..dffb37f 100644 --- a/src/Febe.Core/Config/richieste.instagram.json +++ b/src/Febe.Core/Config/richieste.instagram.json @@ -1,6 +1,6 @@ { "site": "instagram", - "note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, i doc_id dal modulo «_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, __d e __spin_r/__spin_b/__spin_t, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.", + "note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, __spin_r, __spin_b e __spin_t dalle chiavi omonime di SiteData (decisione di Alberto del 18 novembre 2026: si copiano dalla pagina a «Ho finito», come gli altri; chi le aggiunge alla richiesta resta da vedere, H23), i doc_id dal modulo «_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce, spin_r, spin_b, spin_t), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn e __d, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.", "page": { "note": "Dove la pagina tiene i valori della sessione: «Modulo.proprietà» del require della pagina; docIdModule con {operation} per il nome dell'operazione. Solo nomi, nessun valore.", "docIdModule": "{operation}_instagramRelayOperation", @@ -15,7 +15,10 @@ "dpr": "SiteData.pr", "comet_req": "SiteData.comet_env", "ccg": "WebConnectionClassServerGuess.connectionClass", - "entry_nonce": "BootloaderConfig.nonce" + "entry_nonce": "BootloaderConfig.nonce", + "spin_r": "SiteData.__spin_r", + "spin_b": "SiteData.__spin_b", + "spin_t": "SiteData.__spin_t" } }, "operations": [ @@ -66,9 +69,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -148,9 +151,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -226,9 +229,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -310,9 +313,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -389,9 +392,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -465,9 +468,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -538,9 +541,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -618,9 +621,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", @@ -699,9 +702,9 @@ "__rev": "session:rev", "__s": "pending", "__sjsp": "pending", - "__spin_b": "pending", - "__spin_r": "pending", - "__spin_t": "pending", + "__spin_b": "session:spin_b", + "__spin_r": "session:spin_r", + "__spin_t": "session:spin_t", "__user": "session:account_id", "av": "session:account_id", "doc_id": "session:doc_id", diff --git a/src/Febe.Core/Config/richieste.prova.json b/src/Febe.Core/Config/richieste.prova.json index 40ba8df..39744c1 100644 --- a/src/Febe.Core/Config/richieste.prova.json +++ b/src/Febe.Core/Config/richieste.prova.json @@ -15,7 +15,10 @@ "dpr": "VersioneProva.dpr", "comet_req": "VersioneProva.comet", "ccg": "ConnessioneProva.classe", - "entry_nonce": "AvvioProva.nonce" + "entry_nonce": "AvvioProva.nonce", + "spin_r": "GiroProva.revisione", + "spin_b": "GiroProva.ramo", + "spin_t": "GiroProva.tempo" } }, "operations": [ @@ -104,6 +107,9 @@ "__hs": "session:hs", "__hsi": "session:hsi", "__rev": "session:rev", + "__spin_r": "session:spin_r", + "__spin_b": "session:spin_b", + "__spin_t": "session:spin_t", "dpr": "session:dpr", "fb_dtsg": "session:fb_dtsg", "lsd": "session:lsd", @@ -121,7 +127,7 @@ "profilo" ], "sample": "000002-profilo-pubblico", - "note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram." + "note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req, __spin_r, __spin_b, __spin_t) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram." }, { "name": "profilo-altri", diff --git a/src/Febe.Core/Drawing/Brush.cs b/src/Febe.Core/Drawing/Brush.cs new file mode 100644 index 0000000..5ee787f --- /dev/null +++ b/src/Febe.Core/Drawing/Brush.cs @@ -0,0 +1,118 @@ +using System.Numerics; + +namespace Febe.Core.Drawing; + +/// What fills a shape: one colour or a gradient. +public abstract class Brush +{ + private protected Brush() + { + } + + /// + /// The colours of .Length pixels of row from column + /// : red, green and blue 0-255, alpha 0-1, not premultiplied. maps + /// canvas pixels back to the coordinates the brush was defined in. + /// + internal abstract void Shade(in Matrix3x2 toUser, int y, int x0, Span output); + + /// A colour as the shading works with it. + internal static Vector4 ToVector(Color color) => new(color.R, color.G, color.B, color.A / 255f); +} + +/// One colour. +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 output) => output.Fill(Value); +} + +/// +/// A linear gradient from to : 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. +/// +public sealed class LinearGradientBrush : Brush +{ + private readonly Vector4[] _colors; + private readonly float[] _positions; + + /// Where the first colour is, in the coordinates the shape is drawn in. + /// Where the last colour is. + /// Two or more colours. + /// Where each colour sits between start (0) and end (1), increasing; evenly spaced when null. + public LinearGradientBrush(Vector2 start, Vector2 end, IReadOnlyList colors, IReadOnlyList? 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 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); + } +} diff --git a/src/Febe.Core/Drawing/Canvas.cs b/src/Febe.Core/Drawing/Canvas.cs new file mode 100644 index 0000000..b738d8e --- /dev/null +++ b/src/Febe.Core/Drawing/Canvas.cs @@ -0,0 +1,549 @@ +using System.Buffers; +using System.Numerics; +using System.Runtime.CompilerServices; +using Febe.Core.Codecs.Images; + +namespace Febe.Core.Drawing; + +/// How the ends of a stroked line look. +public enum LineCap +{ + /// The line stops at its end points. + Butt, + + /// A half circle around each end point. + Round, + + /// The line goes on for half its width beyond each end point. + Square, +} + +/// +/// Draws anti-aliased shapes on an : 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 , which , +/// and change and / keep. +/// Written in house (no graphics library): the coverage of every pixel is the exact area of the shape inside it. +/// +public sealed class Canvas : IDisposable +{ + private readonly RgbaImage _target; + private readonly Stack _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; + + /// The image drawn on. + public RgbaImage Target => _target; + + /// From the coordinates of the shapes to the pixels of the canvas. + public Matrix2D Transform { get; set; } = Matrix2D.Identity; + + /// Remembers the transform, for . + public void Save() => _saved.Push(Transform); + + /// Back to the transform of the last . + 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); + + /// Rotates the shapes drawn next by around the origin, clockwise on screen. + public void Rotate(float degrees) => Transform = Transform.Then(Matrix2D.Rotation(degrees)); + + /// Every pixel set to , ignoring what was there. + public void Clear(Color color) + { + var pixels = _target.Pixels; + Span 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)); + + /// Fills the shape describes (non-zero winding). + 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)); + + /// Fills a rectangle; without rotation the coverage of its border pixels is computed directly. + 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); + + /// The outline of a rectangle, wide and centred on its sides, square corners. + 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); + } + + /// A ring: the outline of an ellipse, wide and centred on it. + 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); + + /// A straight line wide. + 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); + + /// + /// The contours of drawn as lines wide, with round joins + /// and the given caps on open contours. + /// + 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(); + foreach (var contour in path.Flatten(Transform)) + { + StrokePieces(contour, half, cap, pieces); + } + + FillPolygons(pieces, new SolidBrush(color)); + } + + /// + /// A disc whose edge is blurred by a Gaussian of (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. + /// + 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); + } + } + } + } + + /// Composites one colour over one pixel, without anti-aliasing (canvas pixels, the transform ignored). + 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); + } + + /// + /// Draws 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. + /// + 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 contours, Brush brush) + { + var polygons = new List(contours.Count); + foreach (var contour in contours) + { + if (contour.Points.Length >= 3) + { + polygons.Add(contour.Points); + } + } + + FillPolygons(polygons, brush); + } + + private void FillPolygons(List 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.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.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.Shared.Rent(width); + var coverage = ArrayPool.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.Shared.Return(columns); + ArrayPool.Shared.Return(coverage); + } + } + + private void BlendRow(int y, int left, ReadOnlySpan 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.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.Shared.Return(colors); + } + } + + /// Source over, straight alpha: is the colour's alpha times the coverage. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void BlendPixel(Span 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); + } + + /// The pieces of a stroke: a quadrilateral per segment, a disc per join, the caps; all turning the same way. + private static void StrokePieces(Polyline contour, float half, LineCap cap, List 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); + } + + /// The polygon turning clockwise on screen (positive signed area with y downwards), reversed if needed. + 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; + } + + /// The complementary error function, |error| < 1.5e-7 (Abramowitz and Stegun 7.1.26). + 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; + } +} diff --git a/src/Febe.Core/Drawing/Color.cs b/src/Febe.Core/Drawing/Color.cs new file mode 100644 index 0000000..cfb6a39 --- /dev/null +++ b/src/Febe.Core/Drawing/Color.cs @@ -0,0 +1,27 @@ +namespace Febe.Core.Drawing; + +/// A colour of the drawing code: 8-bit red, green, blue and alpha, not premultiplied. +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); + + /// An opaque colour from 0xRRGGBB. + public static Color FromRgb(uint rgb) => new((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb); + + /// The same colour with another alpha. + public Color WithAlpha(byte alpha) => this with { A = alpha }; + + /// + /// The colour of the way from this one to (0 this, 1 the other), + /// truncated to whole levels; the alpha of this colour. + /// + 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); +} diff --git a/src/Febe.Core/Drawing/CoverageRasterizer.cs b/src/Febe.Core/Drawing/CoverageRasterizer.cs new file mode 100644 index 0000000..7c8cecc --- /dev/null +++ b/src/Febe.Core/Drawing/CoverageRasterizer.cs @@ -0,0 +1,237 @@ +using System.Buffers; +using System.Numerics; + +namespace Febe.Core.Drawing; + +/// +/// 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. +/// +internal sealed class CoverageRasterizer : IDisposable +{ + private float[] _cells = []; + private int _stride; + + /// Left column of the window in the canvas. + public int Left { get; private set; } + + /// Top row of the window in the canvas. + public int Top { get; private set; } + + public int Width { get; private set; } + + public int Height { get; private set; } + + /// Starts a new shape in the window (, , width × height). + 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.Shared.Return(_cells); + } + + _cells = ArrayPool.Shared.Rent(length); + } + + _cells.AsSpan(0, length).Clear(); + } + + /// Adds the edges of a closed polygon (canvas pixels; the last point joins the first). + public void AddPolygon(ReadOnlySpan points) + { + for (var i = 0; i < points.Length; i++) + { + AddEdge(points[i], points[(i + 1) % points.Length]); + } + } + + /// Adds one edge, in canvas pixels. + 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 cuts = stackalloc float[4]; + var count = 0; + cuts[count++] = 0; + foreach (var border in (ReadOnlySpan)[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); + } + } + } + + /// The coverage of row of the window (0-1 for each of its columns). + public void Coverage(int y, Span 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.Shared.Return(_cells); + _cells = []; + } + } + + /// One edge with 0 ≤ x ≤ Width, the rows outside the window ignored. + 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; + } + } +} diff --git a/src/Febe.Core/Drawing/Matrix2D.cs b/src/Febe.Core/Drawing/Matrix2D.cs new file mode 100644 index 0000000..f91ad4c --- /dev/null +++ b/src/Febe.Core/Drawing/Matrix2D.cs @@ -0,0 +1,28 @@ +using System.Numerics; + +namespace Febe.Core.Drawing; + +/// +/// An affine transform of the plane: x' = M11·x + M21·y + M31, y' = M12·x + M22·y + M32 (the layout of +/// , which does the arithmetic). Transforms compose as with a canvas: the last one applied +/// to the canvas acts first on the shapes drawn. +/// +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)); + + /// A rotation by around the origin, clockwise on screen (y grows downwards). + public static Matrix2D Rotation(float degrees) => new(Matrix3x2.CreateRotation(degrees * MathF.PI / 180f)); + + /// The transform that applies first and then this one. + public Matrix2D Then(Matrix2D inner) => new(inner.Value * Value); + + public Vector2 Apply(Vector2 point) => Vector2.Transform(point, Value); + + /// How much the transform enlarges lengths, on average (the square root of the area scale). + public float LengthScale => MathF.Sqrt(MathF.Abs(Value.GetDeterminant())); +} diff --git a/src/Febe.Core/Drawing/PathBuilder.cs b/src/Febe.Core/Drawing/PathBuilder.cs new file mode 100644 index 0000000..8a08af1 --- /dev/null +++ b/src/Febe.Core/Drawing/PathBuilder.cs @@ -0,0 +1,275 @@ +using System.Numerics; + +namespace Febe.Core.Drawing; + +/// +/// 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. +/// +public sealed class PathBuilder +{ + private readonly List _commands = []; + + private enum Kind + { + Move, + Line, + Quad, + Cubic, + Arc, + Close, + } + + /// Whether nothing was added. + public bool IsEmpty => _commands.Count == 0; + + /// Starts a new contour at (, ). + public PathBuilder MoveTo(float x, float y) + { + _commands.Add(new Command(Kind.Move, new Vector2(x, y))); + return this; + } + + /// A straight line to (, ). + public PathBuilder LineTo(float x, float y) + { + _commands.Add(new Command(Kind.Line, new Vector2(x, y))); + return this; + } + + /// A quadratic Bézier curve through the control point (cx, cy) to (x, y). + 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; + } + + /// A cubic Bézier curve through the control points (c1x, c1y) and (c2x, c2y) to (x, y). + 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; + } + + /// + /// A new contour along the ellipse inscribed in the rectangle (, )– + /// (, ), from for + /// (negative: the other way round). + /// + 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; + } + + /// Closes the current contour with a straight line back to its start. + public PathBuilder Close() + { + _commands.Add(new Command(Kind.Close, default)); + return this; + } + + /// A closed ellipse centred on (cx, cy), clockwise on screen (or the other way round). + 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(); + } + + /// A closed circle. + public PathBuilder AddCircle(float cx, float cy, float r, bool clockwise = true) => AddEllipse(cx, cy, r, r, clockwise); + + /// A closed rectangle, clockwise on screen (or the other way round). + 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(); + } + + /// A closed rectangle with corners rounded to quarter circles of . + 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(); + } + + /// A closed polygon through (x0, y0, x1, y1, ...). + public PathBuilder AddPolygon(ReadOnlySpan 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(); + } + + /// + /// The contours as polylines in canvas pixels, the curves divided finely enough that no chord strays more than + /// 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. + /// + internal List Flatten(Matrix2D transform, float tolerance = 0.01f) + { + var result = new List(); + var scale = Math.Max(transform.LengthScale, 1e-6f); + List? 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; + } + + /// An arc that continues the current contour (used by the rounded rectangle). + 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); + } + + /// Chords of an arc of radius , each with a sagitta of at most the tolerance. + 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; } + } +} + +/// A flattened contour in canvas pixels. +internal readonly record struct Polyline(Vector2[] Points, bool Closed); diff --git a/src/Febe.Core/Engine/EngineRuntime.cs b/src/Febe.Core/Engine/EngineRuntime.cs index 4132c0d..074eab2 100644 --- a/src/Febe.Core/Engine/EngineRuntime.cs +++ b/src/Febe.Core/Engine/EngineRuntime.cs @@ -12,6 +12,7 @@ public sealed class EngineRuntime private readonly Lock _gate = new(); private readonly Func _userIsDriving; private readonly Func? _isConnected; + private readonly Func? _sessionCopyMissing; private CautionProfile _profile = CautionProfile.Prudent; private DateTimeOffset? _rampStart; private SessionContext? _session; @@ -23,10 +24,15 @@ public sealed class EngineRuntime /// True while Alberto uses the browser (). /// Whether the Instagram session exists in the browser; null when unknown. - public EngineRuntime(Func? userIsDriving = null, Func? isConnected = null) + /// + /// True when the browser holds the session but the saved session of the raccolta «richieste» is missing (issue #36, + /// S4b): is then false and the monitor says «Serve «Ho finito»». Null: never. + /// + public EngineRuntime(Func? userIsDriving = null, Func? isConnected = null, Func? sessionCopyMissing = null) { _userIsDriving = userIsDriving ?? (() => false); _isConnected = isConnected; + _sessionCopyMissing = sessionCopyMissing; } /// The effective caution profile (settings applied). @@ -56,6 +62,9 @@ public sealed class EngineRuntime /// Whether the browser holds an Instagram session; null when the host does not say. public bool? IsConnected => _isConnected?.Invoke(); + /// True when the browser holds the session but the copy for the requests is missing (S4b). + public bool SessionCopyMissing => _sessionCopyMissing?.Invoke() == true; + /// The session in progress, if any. The Governor refuses every site action without one. public SessionContext? CurrentSession { diff --git a/src/Febe.Core/Engine/EngineServices.cs b/src/Febe.Core/Engine/EngineServices.cs index 4ca22a2..009cd9c 100644 --- a/src/Febe.Core/Engine/EngineServices.cs +++ b/src/Febe.Core/Engine/EngineServices.cs @@ -85,6 +85,7 @@ public sealed class EngineServices /// True while Alberto uses the browser. /// Whether the browser holds an Instagram session; null when unknown. /// Cancellation. + /// True when the session is in the browser but its saved copy is missing (S4b). public static async Task CreateAsync( IFebeStorage storage, IClock clock, @@ -92,14 +93,15 @@ public sealed class EngineServices EngineOptions? options = null, Func? userIsDriving = null, Func? isConnected = null, - CancellationToken ct = default) + CancellationToken ct = default, + Func? sessionCopyMissing = null) { ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(random); options ??= EngineOptions.Default; - var runtime = new EngineRuntime(userIsDriving, isConnected); + var runtime = new EngineRuntime(userIsDriving, isConnected, sessionCopyMissing); var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false); runtime.Profile = settings.EffectiveProfile; runtime.IsPaused = await storage.Settings.GetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false); diff --git a/src/Febe.Core/Engine/Monitor.cs b/src/Febe.Core/Engine/Monitor.cs index 92c2d07..b50be18 100644 --- a/src/Febe.Core/Engine/Monitor.cs +++ b/src/Febe.Core/Engine/Monitor.cs @@ -35,7 +35,10 @@ public sealed class EngineMonitor : IEngineMonitor var session = runtime.CurrentSession; var mode = ModeOf(runtime, breaker, session, window); var resumes = ResumesAround(mode, runtime, breaker, nextWindow, now); - var (headline, details, sidebar) = Texts(mode, runtime, breaker, session, resumes, now, zone); + + // Read once: the headline and the flag of the snapshot say the same thing. + var copyMissing = mode == EngineMode.NotConnected && runtime.SessionCopyMissing; + var (headline, details, sidebar) = Texts(mode, copyMissing, runtime, breaker, session, resumes, now, zone); var budgets = _s.Governor.GetEffectiveBudgets(now); var statuses = await _s.Governor.GetBudgetStatusAsync(ct).ConfigureAwait(false); @@ -62,6 +65,7 @@ public sealed class EngineMonitor : IEngineMonitor RecentActions = await RecentAsync(now, zone, ct).ConfigureAwait(false), SuspendedRecipes = [.. _host.SuspendedRecipes.Select(r => new SuspendedRecipeView(r.Key, ItalianText.Capitalize(SessionComposer.RecipeName(r.Key)), r.Value))], Breaker = breaker, + SessionCopyMissing = copyMissing, }; } @@ -136,6 +140,7 @@ public sealed class EngineMonitor : IEngineMonitor private static (string Headline, IReadOnlyList Details, string Sidebar) Texts( EngineMode mode, + bool copyMissing, EngineRuntime runtime, BreakerState breaker, SessionContext? session, @@ -184,6 +189,8 @@ public sealed class EngineMonitor : IEngineMonitor case EngineMode.Disconnected: return ("Scollegato", ["La sessione di Instagram non c'è più.", "Apri il browser, accedi di nuovo, poi premi «Riprendi». Febe non prova a rientrare da solo."], "Accedi di nuovo"); + case EngineMode.NotConnected when copyMissing: + return ("Serve «Ho finito»", ["Il browser è collegato, ma manca la copia della sessione per le richieste.", "Dalla pagina Collegamento apri il browser e premi «Ho finito» sulla tua pagina iniziale."], "Serve «Ho finito»"); case EngineMode.NotConnected: return ("Non collegato", ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento."], "Non collegato"); case EngineMode.UserDriving: diff --git a/src/Febe.Core/Engine/MonitorModels.cs b/src/Febe.Core/Engine/MonitorModels.cs index 25d7ad0..972286a 100644 --- a/src/Febe.Core/Engine/MonitorModels.cs +++ b/src/Febe.Core/Engine/MonitorModels.cs @@ -190,4 +190,10 @@ public sealed record EngineSnapshot public required IReadOnlyList SuspendedRecipes { get; init; } public required BreakerState Breaker { get; init; } + + /// + /// Not connected because the copy for the requests is missing (issue #36, S4b): the browser has the session cookie, + /// the raccolta «richieste» has no readable saved session. The headline is then «Serve «Ho finito»». + /// + public bool SessionCopyMissing { get; init; } } diff --git a/src/Febe.Core/Febe.Core.csproj b/src/Febe.Core/Febe.Core.csproj index ce06a54..4ed7bb1 100644 --- a/src/Febe.Core/Febe.Core.csproj +++ b/src/Febe.Core/Febe.Core.csproj @@ -1,9 +1,6 @@ - - - diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs index d250a4b..1afca4d 100644 --- a/src/Febe.Core/Import/ContentAnalysis.cs +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -67,7 +67,7 @@ internal static class ContentAnalysis sha = Convert.ToHexStringLower(SHA256.HashData(bytes)); ct.ThrowIfCancellationRequested(); - (width, height, hash) = Decode(() => new MemoryStream(bytes, writable: false)); + (width, height, hash) = Decode(bytes); } else { @@ -80,25 +80,47 @@ internal static class ContentAnalysis return new ContentFacts(type, length, sha, width, height, null, hash, date, null); } + /// Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. HEIC). + 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); + } + } + + /// + /// The same for a photo over , which the analysis does not keep for the copy: it is read once + /// more, whole (up to ; the codecs need the bytes in memory), and decoded + /// once for both hash and size. + /// private static (int? Width, int? Height, ulong? Hash) Decode(Func open) { try { - int? width = null, height = null; + byte[]? data; using (var stream = open()) { - if (ImageDecoding.ReadSize(stream) is { } size) - { - (width, height) = size; - } + data = ImageDecoding.ReadAll(stream); } - using var again = open(); - return (width, height, PerceptualHash.Compute(again)); + if (data is null) + { + 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 } } diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index 0bae0c3..762e1c7 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -517,11 +517,11 @@ public sealed class ImportCopier(ImportEnvironment env) { try { - hash = PerceptualHash.ComputeFromFile(saved.FullPath); - await using var stream = File.OpenRead(saved.FullPath); - if (ImageDecoding.ReadSize(stream) is { } size) + // One read of the file gives both the perceptual hash and the size as shown. + (hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath); + if (size is { } shown) { - (width, height) = size; + (width, height) = shown; } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) diff --git a/src/Febe.Core/Import/ImportPreview.cs b/src/Febe.Core/Import/ImportPreview.cs index 5b699c9..f9d66fc 100644 --- a/src/Febe.Core/Import/ImportPreview.cs +++ b/src/Febe.Core/Import/ImportPreview.cs @@ -1,34 +1,20 @@ using Febe.Core.Library; -using SkiaSharp; namespace Febe.Core.Import; /// In-memory previews of source photos for the comparison panel (nothing is written to disk). internal static class ImportPreview { - private const int JpegQuality = 82; - /// A JPEG of the image, upright, at most pixels; null when it cannot be decoded. public static byte[]? RenderJpeg(Stream encodedImage, int longSide) { - using var bitmap = ImageDecoding.DecodeUpright(encodedImage, longSide); - if (bitmap is null) + using var image = ThumbnailStore.DecodeFor(encodedImage, longSide); + if (image is null) { return null; } - var scale = Math.Min(1.0, (double)longSide / Math.Max(bitmap.Width, bitmap.Height)); - var width = Math.Max(1, (int)Math.Round(bitmap.Width * scale)); - 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(); + using var small = ThumbnailStore.Render(image, longSide); + return ThumbnailStore.Jpeg(small); } } diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md index 3ed596b..dd0861c 100644 --- a/src/Febe.Core/Import/LEGGIMI.md +++ b/src/Febe.Core/Import/LEGGIMI.md @@ -159,7 +159,7 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per ## 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. - 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. diff --git a/src/Febe.Core/Library/DamagedImage.cs b/src/Febe.Core/Library/DamagedImage.cs new file mode 100644 index 0000000..af2ac28 --- /dev/null +++ b/src/Febe.Core/Library/DamagedImage.cs @@ -0,0 +1,42 @@ +namespace Febe.Core.Library; + +/// +/// «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. +/// +/// +/// 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. +/// +public static class DamagedImage +{ + /// + /// 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. + /// + public static bool IsDamaged(ReadOnlyMemory data) => ImageDecoding.IsDamaged(data); + + /// + /// for a file on disk, read once; false when it cannot be read or is + /// larger than . + /// + 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); + } +} diff --git a/src/Febe.Core/Library/ImageDecoding.cs b/src/Febe.Core/Library/ImageDecoding.cs index f0941c4..45f9c9e 100644 --- a/src/Febe.Core/Library/ImageDecoding.cs +++ b/src/Febe.Core/Library/ImageDecoding.cs @@ -1,10 +1,11 @@ -using SkiaSharp; +using Febe.Core.Codecs.Images; namespace Febe.Core.Library; /// -/// Decodes images with SkiaSharp, applying the EXIF orientation (photos from phones) and, when the codec allows it, -/// decoding directly at a reduced size to save memory and time. +/// Decodes images with the in-house codecs (: JPEG, PNG, GIF, BMP, WebP), applying the +/// 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. /// internal static class ImageDecoding { @@ -14,118 +15,203 @@ internal static class ImageDecoding /// public const long MaxDecodedPixels = 100_000_000; + /// Files larger than this are not read into memory to be decoded (no picture Febe keeps comes near it). + public const long MaxFileBytes = 512L * 1024 * 1024; + + private static readonly ImageLimits Limits = ImageLimits.Default with { MaxPixels = MaxDecodedPixels }; + /// - /// Decodes an image upright, as premultiplied RGBA. When is given the codec may - /// decode at a lower resolution, but never below that long side (unless the image is smaller). - /// Returns null when the content is not a decodable image. + /// Decodes an image upright, as straight RGBA. When is given the codec may decode + /// at a lower resolution, but never below that long side (unless the image is smaller). Returns null when the + /// content is not a decodable image (unknown format, HEIC, damaged or truncated file, too large). /// - public static SKBitmap? DecodeUpright(Stream stream, int? minLongSide = null) + public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null) { ArgumentNullException.ThrowIfNull(stream); - using var data = SKData.Create(stream); - 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); + return ReadAll(stream) is { } data ? DecodeUpright(data, minLongSide) : null; } + /// Like , from bytes already in memory. + public static RgbaImage? DecodeUpright(ReadOnlyMemory data, int? minLongSide = null) => DecodeUpright(data, minLongSide, out _); + + /// + /// Like , and also gives what + /// would (the full size as shown, even when the picture comes back reduced or not at all), from the same bytes. + /// + public static RgbaImage? DecodeUpright(ReadOnlyMemory 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(); + } + } + + /// + /// True when 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. + /// + internal static bool IsDamaged(ReadOnlyMemory 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; + } + } + + /// The smallest long side lets a JPEG be decoded at: the cheapest reduction. + private const int DamageCheckSide = 1; + + /// + /// Bytes read first by 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. + /// + internal const int HeaderBytes = 256 * 1024; + /// Dimensions of an image as displayed (orientation applied), without decoding the pixels. public static (int Width, int Height)? ReadSize(Stream stream) { ArgumentNullException.ThrowIfNull(stream); - using var codec = SKCodec.Create(stream); - if (codec is null) + if (!stream.CanSeek) + { + return ReadAll(stream) is { } all ? ReadSize(all) : null; + } + + var remaining = stream.Length - stream.Position; + if (remaining <= 0 || remaining > MaxFileBytes) { return null; } - var (w, h) = (codec.Info.Width, codec.Info.Height); - 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) + if (remaining <= HeaderBytes) { - return full; + return ReadSize(ReadAll(stream)); } - var best = full; - foreach (var scale in new[] { 0.5f, 0.25f, 0.125f }) + var data = new byte[HeaderBytes]; + stream.ReadExactly(data); + if (ImageFormatSniffer.Detect(data) is not (ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp)) { - var scaled = codec.GetScaledDimensions(scale); - if (scaled.Width <= 0 || scaled.Height <= 0 || Math.Max(scaled.Width, scaled.Height) < min) + // PNG keeps metadata (eXIf) anywhere before IEND and checks every chunk, WebP refuses a RIFF that runs + // 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); + } + + /// Like , from bytes already in memory. + public static (int Width, int Height)? ReadSize(ReadOnlyMemory 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; + } + } + + /// The rest of , or null when it is empty or over . + 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; - } - - private static bool SwapsAxes(SKEncodedOrigin origin) => - 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) + using var copy = new MemoryStream(); + var buffer = new byte[81920]; + int read; + while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { - return source; + if (copy.Length + read > MaxFileBytes) + { + return null; + } + + copy.Write(buffer, 0, read); } - float w = source.Width, h = source.Height; - 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; + return copy.Length == 0 ? null : copy.ToArray(); } } diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index 08f8f58..cc883d0 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -278,11 +278,11 @@ public sealed class LibraryIngest( { try { - hash = PerceptualHash.ComputeFromFile(saved.FullPath); - await using var stream = File.OpenRead(saved.FullPath); - if (ImageDecoding.ReadSize(stream) is { } size) + // One read of the file gives both the perceptual hash and the size as shown. + (hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath); + if (size is { } shown) { - (width, height) = size; + (width, height) = shown; } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index 1b59398..484dd97 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -445,13 +445,11 @@ public sealed class LibraryRebuilder( { if (!isVideo) { - phash = PerceptualHash.ComputeFromFile(path); - await using (var stream = File.OpenRead(path)) + // One read of the file gives both the perceptual hash and the size as shown. + (phash, var size) = PerceptualHash.ComputeWithSizeFromFile(path); + if (size is { } shown) { - if (ImageDecoding.ReadSize(stream) is { } size) - { - (width, height) = size; - } + (width, height) = shown; } } } diff --git a/src/Febe.Core/Library/PerceptualHash.cs b/src/Febe.Core/Library/PerceptualHash.cs index 63b88f5..bb2892a 100644 --- a/src/Febe.Core/Library/PerceptualHash.cs +++ b/src/Febe.Core/Library/PerceptualHash.cs @@ -1,5 +1,5 @@ using System.Numerics; -using SkiaSharp; +using Febe.Core.Codecs.Images; namespace Febe.Core.Library; @@ -38,6 +38,9 @@ public static class PerceptualHash private const int Size = 32; private const int Low = 8; + /// A JPEG is decoded reduced, but never below this long side. + private const int MinDecodedSide = 256; + private static readonly double[,] Cosines = BuildCosines(); /// Hamming distance between two hashes (0–64). @@ -50,8 +53,8 @@ public static class PerceptualHash public static ulong? Compute(Stream encodedImage) { ArgumentNullException.ThrowIfNull(encodedImage); - using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256); - return bitmap is null ? null : Compute(bitmap); + using var image = ImageDecoding.DecodeUpright(encodedImage, minLongSide: MinDecodedSide); + return image is null ? null : Compute(image); } /// Hash of an image file; null when it is not a decodable image. @@ -61,17 +64,33 @@ public static class PerceptualHash return Compute(stream); } - /// Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible). - 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). + /// + internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSize(ReadOnlyMemory encodedImage) { - ArgumentNullException.ThrowIfNull(bitmap); - using var rgba = bitmap.ColorType == SKColorType.Rgba8888 && bitmap.AlphaType == SKAlphaType.Premul - ? null - : bitmap.Copy(SKColorType.Rgba8888); - var source = rgba ?? bitmap; - var grey = Luminance(source); - var small = AreaResample(grey, source.Width, source.Height, Size, Size); - return HashOf(small); + using var image = ImageDecoding.DecodeUpright(encodedImage, MinDecodedSide, out var size); + return (image is null ? null : Compute(image), size); + } + + /// Like for a file, read once. + internal static (ulong? Hash, (int Width, int Height)? Size) ComputeWithSizeFromFile(string path) + { + byte[]? data; + using (var stream = File.OpenRead(path)) + { + data = ImageDecoding.ReadAll(stream); + } + + return data is null ? (null, null) : ComputeWithSize(data); + } + + /// Hash of a decoded image (any size), upright as it is shown. + internal static ulong Compute(RgbaImage image) + { + ArgumentNullException.ThrowIfNull(image); + return HashOf(AreaResample(image, Size, Size)); } /// The hash of a 32×32 grey image (row-major). @@ -123,50 +142,37 @@ public static class PerceptualHash return hash; } - /// Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white. - private static double[] Luminance(SKBitmap bitmap) + /// + /// The grey levels (0–255, over white: ) of an image reduced to dw × dh by area + /// averaging, one source row at a time (memory: one row and dw × source height values). + /// + internal static double[] AreaResample(RgbaImage image, int dw, int dh) { - var width = bitmap.Width; - var height = bitmap.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; - } - - /// Area-averaging resample with exact fractional coverage (no aliasing when reducing). - internal static double[] AreaResample(double[] source, int sw, int sh, int dw, int dh) - { - var horizontal = new double[dw * sh]; + var sw = image.Width; + var sh = image.Height; var xs = Weights(sw, dw); + var horizontal = new double[dw * sh]; + var grey = new double[sw]; for (var y = 0; y < sh; y++) { + ImageGray.LumaOverWhite(image.GetRow(y), grey); for (var dx = 0; dx < dw; dx++) { double sum = 0; foreach (var (index, weight) in xs[dx]) { - sum += source[(y * sw) + index] * weight; + sum += grey[index] * weight; } 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 ys = Weights(sh, dh); for (var dy = 0; dy < dh; dy++) diff --git a/src/Febe.Core/Library/ThumbnailStore.cs b/src/Febe.Core/Library/ThumbnailStore.cs index 7dceb90..a3951f6 100644 --- a/src/Febe.Core/Library/ThumbnailStore.cs +++ b/src/Febe.Core/Library/ThumbnailStore.cs @@ -1,4 +1,5 @@ -using SkiaSharp; +using Febe.Core.Codecs.Images; +using Febe.Core.Drawing; namespace Febe.Core.Library; @@ -54,13 +55,14 @@ public sealed class ThumbnailStore return true; } - using var bitmap = ImageDecoding.DecodeUpright(encodedImage, LongSide); - if (bitmap is null) + using var image = DecodeFor(encodedImage, LongSide); + if (image is null) { return false; } - WriteJpeg(target, Render(bitmap, LongSide)); + using var thumbnail = Render(image, LongSide); + WriteJpeg(target, thumbnail); return true; } @@ -94,26 +96,20 @@ public sealed class ThumbnailStore } 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)); - var canvas = surface.Canvas; - canvas.Clear(new SKColor(0xE4, 0xE4, 0xE4)); - using (var paint = new SKPaint { Color = new SKColor(0x9A, 0x9A, 0x9A), IsAntialias = true, Style = SKPaintStyle.Fill }) + using var tile = new RgbaImage(width, height); + using (var canvas = new Canvas(tile)) { - 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 }) - { - // A play triangle drawn as three thin rectangles would be blurry; vertices keep it crisp. - var cx = width / 2f + 4; + // The play sign: a triangle pointing right, a little right of the centre to look centred. + var cx = (width / 2f) + 4; var cy = height / 2f; - SKPoint[] triangle = [new(cx - 10, cy - 15), new(cx - 10, cy + 15), new(cx + 15, cy)]; - canvas.DrawVertices(SKVertexMode.Triangles, triangle, null, null, paint); + canvas.Fill(new PathBuilder().AddPolygon([cx - 10, cy - 15, cx - 10, cy + 15, cx + 15, cy]), background); } - using var image = surface.Snapshot(); - using var bitmap = SKBitmap.FromImage(image); - WriteJpeg(path, bitmap.Copy()); + WriteJpeg(path, tile); return path; } @@ -125,67 +121,66 @@ public sealed class ThumbnailStore { ArgumentNullException.ThrowIfNull(source); ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16); - using var decoded = ImageDecoding.DecodeUpright(source, longSide); + using var decoded = DecodeFor(source, longSide); if (decoded is null) { return null; } using var small = Render(decoded, longSide); - using var pixmap = small.PeekPixels(); - if (pixmap is null) - { - return null; - } - - using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality)); - return data?.ToArray(); + return Jpeg(small); } - private static SKBitmap Render(SKBitmap source, int longSide) + /// + /// Decodes an image upright for a picture of 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. + /// + internal static RgbaImage? DecodeFor(Stream encodedImage, int longSide) => + ImageDecoding.DecodeUpright(encodedImage, 2 * longSide); + + /// + /// The image reduced to 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. + /// + internal static RgbaImage Render(RgbaImage source, int longSide) { - var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height)); - var width = Math.Max(1, (int)Math.Round(source.Width * scale)); - var height = Math.Max(1, (int)Math.Round(source.Height * scale)); - 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); + var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, longSide); + var result = ImageResampler.Resize(source, width, height, pooled: true); + ImageBackground.Flatten(result, Color.White); return result; } - private static void WriteJpeg(string target, SKBitmap bitmap) + /// The JPEG of a thumbnail: quality , chroma 4:2:0. + 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)!); - var temp = target + "." + Guid.NewGuid().ToString("N")[..8] + ".tmp"; + using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write)) + { + file.Write(data); + } + try { - using (var pixmap = bitmap.PeekPixels() ?? throw new InvalidOperationException("Miniatura senza pixel.")) - 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. - } + File.Move(temp, target, overwrite: false); } - finally + catch (IOException) when (File.Exists(target)) { - if (File.Exists(temp)) - { - File.Delete(temp); - } + // Created meanwhile by another task: same content. + } + } + finally + { + if (File.Exists(temp)) + { + File.Delete(temp); } } } diff --git a/src/Febe.Desktop.Core/BrandIcon.cs b/src/Febe.Desktop.Core/BrandIcon.cs index 88c3e38..45b6eec 100644 --- a/src/Febe.Desktop.Core/BrandIcon.cs +++ b/src/Febe.Desktop.Core/BrandIcon.cs @@ -1,11 +1,12 @@ using System.Buffers.Binary; -using SkiaSharp; +using Febe.Core.Codecs.Images; +using Febe.Core.Drawing; namespace Febe.Desktop.Core; /// /// 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 () at any size, the same way the SVG describes it: /// /// <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"/> @@ -17,57 +18,32 @@ public static class BrandMark /// The sizes of the Windows icon: window, notification area, taskbar, Explorer, installer. public static IReadOnlyList 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); - /// The mark as a square bitmap of pixels, premultiplied BGRA, transparent corners. - public static SKBitmap Render(int size) + /// The mark as a square image of pixels, straight RGBA, transparent corners. + public static RgbaImage Render(int size) { ArgumentOutOfRangeException.ThrowIfLessThan(size, 1); ArgumentOutOfRangeException.ThrowIfGreaterThan(size, 1024); - var bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Premul)); - using var canvas = new SKCanvas(bitmap); - canvas.Clear(SKColors.Transparent); - var scale = size / 32f; - canvas.Scale(scale); - using (var square = new SKPaint { Color = Accent, IsAntialias = true, Style = SKPaintStyle.Fill }) - { - 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; + var image = new RgbaImage(size, size); + using var canvas = new Canvas(image); + canvas.Scale(size / 32f); + canvas.FillRoundRect(0, 0, 32, 32, 8, Accent); + canvas.StrokeCircle(14.5f, 17.5f, 7.4f, 2.6f, Color.White); + canvas.FillCircle(23.2f, 8.8f, 3.1f, Color.White); + return image; } /// The multi-size Windows icon () of the mark, as the bytes of an .ico file. public static byte[] RenderIcon() { - var images = new List(); - try + var images = new List(); + foreach (var size in IconSizes) { - foreach (var size in IconSizes) - { - images.Add(Render(size)); - } + images.Add(Render(size)); + } - return IcoWriter.Write(images); - } - finally - { - foreach (var image in images) - { - image.Dispose(); - } - } + return IcoWriter.Write(images); } } @@ -86,7 +62,7 @@ public static class IcoWriter private const int BitmapInfoHeader = 40; /// The .ico bytes of square (1 to 256 pixels), in the order given. - public static byte[] Write(IReadOnlyList images) + public static byte[] Write(IReadOnlyList images) { ArgumentNullException.ThrowIfNull(images); if (images.Count is 0 or > ushort.MaxValue) @@ -167,41 +143,48 @@ public static class IcoWriter return entries; } - /// The image of an entry as a bitmap (DIB or PNG), for comparisons. - public static SKBitmap Decode(ReadOnlySpan ico, IcoEntry entry) + /// The image of an entry (DIB or PNG) as straight RGBA, for comparisons. + public static RgbaImage Decode(ReadOnlySpan ico, IcoEntry entry) { ArgumentNullException.ThrowIfNull(entry); var data = ico.Slice(entry.Offset, entry.Length); 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 bitmap = new SKBitmap(new SKImageInfo(size, size, SKColorType.Bgra8888, SKAlphaType.Unpremul)); + var image = new RgbaImage(size, size); var pixels = data[BitmapInfoHeader..]; for (var y = 0; y < size; y++) { var row = pixels.Slice((size - 1 - y) * size * 4, size * 4); + var target = image.GetRow(y); 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 PngSignature => [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; - private static byte[] Png(SKBitmap image) - { - using var data = image.Encode(SKEncodedImageFormat.Png, 100) ?? throw new InvalidOperationException("Codifica PNG non riuscita."); - return data.ToArray(); - } + private static byte[] Png(RgbaImage image) => PngEncoder.Encode(image, new PngEncoderOptions { ColorMode = PngColorMode.Rgba }); /// A 32-bit DIB: BITMAPINFOHEADER with twice the height (image + mask), BGRA rows bottom-up, AND mask. - private static byte[] Dib(SKBitmap image) + private static byte[] Dib(RgbaImage image) { var size = image.Width; 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); 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); - row[x * 4] = c.Blue; - row[(x * 4) + 1] = c.Green; - row[(x * 4) + 2] = c.Red; - row[(x * 4) + 3] = c.Alpha; - if (c.Alpha == 0) + row[x * 4] = c.B; + row[(x * 4) + 1] = c.G; + row[(x * 4) + 2] = c.R; + row[(x * 4) + 3] = c.A; + if (c.A == 0) { // 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); diff --git a/src/Febe.Desktop/Browser/BrowserWindow.cs b/src/Febe.Desktop/Browser/BrowserWindow.cs index c3d1a5e..9b8933e 100644 --- a/src/Febe.Desktop/Browser/BrowserWindow.cs +++ b/src/Febe.Desktop/Browser/BrowserWindow.cs @@ -4,6 +4,7 @@ using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Threading; +using Febe.App; using Febe.Desktop.Native; namespace Febe.Desktop.Browser; @@ -135,8 +136,11 @@ internal sealed class BrowserWindow : Window /// Raised by «Pagina iniziale». public event EventHandler? HomeRequested; - /// Raised when Alberto closes the window, or leaves it minimised too long: the owner puts it out of view. - public event EventHandler? DoneRequested; + /// + /// Raised when Alberto closes the window, or leaves it minimised too long (which one is the argument): the owner puts + /// it out of view. + /// + public event EventHandler? DoneRequested; /// Raised when the page area changed size (a new fit): the owner sizes WebView2 again. public event EventHandler? PageAreaChanged; @@ -253,7 +257,7 @@ internal sealed class BrowserWindow : Window { // The browser stays open: closing the window means «ho finito», it goes out of view. e.Cancel = true; - DoneRequested?.Invoke(this, EventArgs.Empty); + DoneRequested?.Invoke(this, BrowserWindowLetGo.Closed); } base.OnClosing(e); @@ -283,7 +287,7 @@ internal sealed class BrowserWindow : Window if (WindowState == WindowState.Minimized) { // Restored out of view by the owner (MoveOffScreen), never first on screen where it was. - DoneRequested?.Invoke(this, EventArgs.Empty); + DoneRequested?.Invoke(this, BrowserWindowLetGo.MinimizedTooLong); } } diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index b8fb7d9..e10eeea 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser _options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height); Host = new WebView2Host( ui, - new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage), + new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage, context.CopyOnWindowClosed), context.Log); Host.BrowserProcessFailed += (_, _) => RequestRestart(null); } diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 830ac43..15a160c 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -23,7 +23,12 @@ namespace Febe.Desktop.Browser; /// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise, /// once the engine's session ended and with the page's turn. Null: the button does nothing. /// -internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null); +/// +/// What closing the window (or leaving it minimised too long, the argument says which) does before the page goes back +/// to the engine (issue #36, S4b): the connection copies the session, when it keeps a saved one. The window keeps the +/// engine still until the task ends. Null: nothing. +/// +internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null, Func? CopyOnClose = null); /// What the host does when a process of WebView2 fails (issue #52). internal enum ProcessFailureResponse @@ -349,7 +354,7 @@ internal sealed class WebView2Host : IBrowserHost window.MoveOffScreen(); window.Show(); window.Activated += OnActivated; - window.DoneRequested += (_, _) => Done(); + window.DoneRequested += (_, how) => Done(how); window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack); window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true); window.HomeRequested += (_, _) => OpenStartPage(); @@ -554,12 +559,42 @@ internal sealed class WebView2Host : IBrowserHost TakeLease(); } - /// Alberto closed the window (or left it minimised too long): done, out of view. - private void Done() + /// + /// Alberto closed the window (or left it minimised too long): done, out of view at once. With a saved session + /// (S4b) the session is copied first: a hold of the driving gate keeps the page his until the copy is over, and only + /// then does it go back to the engine (rule 7). + /// + private void Done(BrowserWindowLetGo how) { _window?.MoveOffScreen(); - ReleaseLease(); NotifyPositionChanged(); + if (_lease is null || _closing || _settings.CopyOnClose is not { } copy) + { + ReleaseLease(); + return; + } + + var hold = UserDriving.Begin(); + ReleaseLease(); + _ = CopyThenLetGoAsync(copy, how, hold); + } + + private async Task CopyThenLetGoAsync(Func copy, BrowserWindowLetGo how, IDisposable hold) + { + try + { + await copy(how, CancellationToken.None).ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // The kind of error only: the page and the browser may hold what the session holds. + _log.Warn("browser", $"Copia della sessione alla chiusura della finestra non riuscita ({ex.GetType().Name})."); + } + finally + { + hold.Dispose(); + _settings.MarkUsed(); + } } private void UserNavigation(Action action, Func allowed) diff --git a/src/Febe.Desktop/Febe.Desktop.csproj b/src/Febe.Desktop/Febe.Desktop.csproj index 4e44622..5171830 100644 --- a/src/Febe.Desktop/Febe.Desktop.csproj +++ b/src/Febe.Desktop/Febe.Desktop.csproj @@ -2,7 +2,7 @@ WinExe @@ -47,8 +47,8 @@ + cartella Dati; i simboli e la documentazione XML dei pacchetti non servono a chi usa Febe. Niente di tutto + questo esce accanto all'eseguibile. --> diff --git a/src/Febe.Desktop/Febe.ico b/src/Febe.Desktop/Febe.ico index 9665cdb..a8f622c 100644 Binary files a/src/Febe.Desktop/Febe.ico and b/src/Febe.Desktop/Febe.ico differ diff --git a/src/Febe.Server/BrowserRemoteView.cs b/src/Febe.Server/BrowserRemoteView.cs index 451d37e..cd58b07 100644 --- a/src/Febe.Server/BrowserRemoteView.cs +++ b/src/Febe.Server/BrowserRemoteView.cs @@ -26,6 +26,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost private readonly IClock _browserClock; private readonly FebeLog _log; private readonly Func? _openStartPage; + private readonly Action? _viewClosed; private readonly Lock _gate = new(); private readonly SemaphoreSlim _opening = new(1, 1); private BrowserRemoteViewConnection? _current; @@ -43,7 +44,12 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost /// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and /// with the page's turn; null: the button does nothing. /// - public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func? openStartPage = null) + /// + /// Told when a view ends from the page's side (the page left, the tab closed, the link lost), not when another view + /// takes its place or Febe stops: the connection then knows that Alberto may have left the browser (Docker, answer of + /// 25 November 2026, spec §6.0 «Quando si copia»); null: nobody is told. + /// + public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func? openStartPage = null, Action? viewClosed = null) { _browser = browser ?? throw new ArgumentNullException(nameof(browser)); _tracker = tracker ?? throw new ArgumentNullException(nameof(tracker)); @@ -51,6 +57,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost _log = log ?? throw new ArgumentNullException(nameof(log)); _browserClock = browserClock ?? new SystemClock(clock.LocalZone); _openStartPage = openStartPage; + _viewClosed = viewClosed; } /// @@ -104,8 +111,8 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost catch (Exception ex) { // Whatever went wrong (the page gone away, an unexpected frame tree), nothing of the view stays behind: - // no lease, no screencast, no subscription. - await connection.DisposeAsync().ConfigureAwait(false); + // no lease, no screencast, no subscription. Ended by the server: the page did not leave the browser. + await connection.EndAsync(RemoteViewEnd.BrowserStopped).ConfigureAwait(false); if (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException) { throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex); @@ -158,7 +165,9 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost } } - internal void Closed(BrowserRemoteViewConnection connection) + /// The view that ended. + /// True when the page ended it (left, tab closed, link lost), false when the server did. + internal void Closed(BrowserRemoteViewConnection connection, bool byPage) { lock (_gate) { @@ -169,6 +178,10 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost } _log.Info("vista", "Vista remota chiusa."); + if (byPage) + { + _viewClosed?.Invoke(); + } } } @@ -445,6 +458,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection return; } + // No reason given by the server (another view, Febe stopping, the browser gone): the page closed it. + var byPage = Ended is null; Ended ??= RemoteViewEnd.BrowserStopped; await _ended.CancelAsync().ConfigureAwait(false); _session.Screencast.FrameReceived -= OnFrame; @@ -462,7 +477,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection // The browser is gone: the lease is released anyway. } - _owner.Closed(this); + _owner.Closed(this, byPage); } private void MarkUsed() diff --git a/src/Febe.Server/DockerPlatform.cs b/src/Febe.Server/DockerPlatform.cs index 06da93e..dec0c64 100644 --- a/src/Febe.Server/DockerPlatform.cs +++ b/src/Febe.Server/DockerPlatform.cs @@ -87,7 +87,15 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(app); - RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask); + // A view closed by its page may be Alberto leaving the browser (answer of 25 November 2026): the connection copies + // the session and gives the page back if no other view opens within a moment (spec §6.0 «Quando si copia»). + RemoteView = new BrowserRemoteViewHost( + app.Browser!, + app.Tracker, + app.Clock, + app.Log, + openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask, + viewClosed: () => app.Connection?.RemoteViewClosed()); services.AddSingleton(RemoteView); } diff --git a/src/Febe.Server/Febe.Server.csproj b/src/Febe.Server/Febe.Server.csproj index ce6b18b..fda03d6 100644 --- a/src/Febe.Server/Febe.Server.csproj +++ b/src/Febe.Server/Febe.Server.csproj @@ -12,7 +12,6 @@ - diff --git a/src/Febe.Web/Api/ConnectionApi.cs b/src/Febe.Web/Api/ConnectionApi.cs index 23f60e7..d81b243 100644 --- a/src/Febe.Web/Api/ConnectionApi.cs +++ b/src/Febe.Web/Api/ConnectionApi.cs @@ -1,4 +1,6 @@ using Febe.Core.Abstractions; +using Febe.Core.Collection.Requests; +using Febe.Core.Storage; using Febe.Web.Connection; using Febe.Web.Engine; using Febe.Web.Native; @@ -36,7 +38,9 @@ public static class ConnectionApi }); // «Annulla», or a page left without either button ({ pageLeft: true }). On Windows the browser is a window of its - // own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52). + // own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52). In Docker leaving + // the page lets go of the browser like closing that window: the session is copied, not cancelled (answer of + // 25 November 2026). Only the button «Annulla» cancels without copying. endpoints.MapPost("/api/connection/cancel", async (HttpContext context, IConnectionService connection, IBrowserWindow window, CancellationToken ct) => { var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest, new CancelDrivingRequest(false)).ConfigureAwait(false); @@ -44,6 +48,10 @@ public static class ConnectionApi { await connection.ReleaseAsync(ct).ConfigureAwait(false); } + else if (body.PageLeft) + { + await connection.LeavePageAsync(ct).ConfigureAwait(false); + } else { await connection.CancelAsync(ct).ConfigureAwait(false); @@ -57,19 +65,54 @@ public static class ConnectionApi await connection.DisconnectAsync(ct).ConfigureAwait(false); return Results.NoContent(); }); + + // What an incomplete copy of the session does (issue #36, S4b, answer 9): read at every copy, no restart. + endpoints.MapGet("/api/connection/settings", async (IFebeStorage storage, CancellationToken ct) => + ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto)); + + endpoints.MapPut("/api/connection/settings", async (HttpContext context, IFebeStorage storage, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConnectionSettingsDto).ConfigureAwait(false); + var choice = SessionCopySettings.Parse(body.IncompleteCopy) + ?? throw new BadRequestException($"Scelta sconosciuta per la copia incompleta: ammesse «{SessionCopySettings.ReplaceText}» e «{SessionCopySettings.KeepCompleteText}»."); + await new SessionCopySettings(choice).SaveAsync(storage.Settings, ct).ConfigureAwait(false); + return ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto); + }); + } + + private static async Task SettingsAsync(IFebeStorage storage, CancellationToken ct) + { + var settings = await SessionCopySettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + return new ConnectionSettingsDto(SessionCopySettings.ToText(settings.IncompleteCopy)); } public static ConnectionStatusDto ToDto(ConnectionStatus status) { ArgumentNullException.ThrowIfNull(status); - return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl); + return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl, ToDto(status.SavedSession)); } + /// The saved session in counts and names; null without one. + public static SavedSessionDto? ToDto(SavedSessionStatus? saved) => saved is null + ? null + : new SavedSessionDto( + saved.State, + saved.CopiedAt?.ToUnixTimeMilliseconds(), + saved.Cookies, + saved.ValuesPresent, + saved.ValuesExpected, + saved.MissingValues, + saved.DocIdsPresent, + saved.DocIdsExpected, + saved.MissingDocIds, + saved.NeededMissing); + public static string State(ConnectionState state) => state switch { ConnectionState.NotConnected => "notConnected", ConnectionState.Connected => "connected", ConnectionState.VerificationRequired => "verificationRequired", + ConnectionState.SessionCopyMissing => "copyMissing", _ => "browserUnavailable", }; } diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs index 3edbc74..71faf7d 100644 --- a/src/Febe.Web/Api/Dtos.cs +++ b/src/Febe.Web/Api/Dtos.cs @@ -77,7 +77,8 @@ public sealed record MediaDto( string? Folder, string? Thumb, bool Available, - string State); + string State, + bool Damaged = false); /// Everything the viewer shows of an entry. public sealed record EntryDto( diff --git a/src/Febe.Web/Api/EngineApi.cs b/src/Febe.Web/Api/EngineApi.cs index 465ad23..89eab65 100644 --- a/src/Febe.Web/Api/EngineApi.cs +++ b/src/Febe.Web/Api/EngineApi.cs @@ -84,8 +84,9 @@ public static class EngineApi /// /// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known: /// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with - /// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run - /// (or there is none in this process) the connection is asked. + /// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so, and whether the copy for + /// the requests is missing too (, no round trip to the browser at every + /// event); only when it does not run (or there is none in this process) the connection is asked. /// public static async Task SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) { @@ -98,10 +99,16 @@ public static class EngineApi var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false); var state = snapshot.Mode switch { - EngineMode.NotConnected => "notConnected", + // The cookie is there but the copy for the requests is missing (S4b): «Serve «Ho finito»», with the account. + EngineMode.NotConnected => snapshot.SessionCopyMissing ? "copyMissing" : "notConnected", EngineMode.StoppedForVerification => "verification", EngineMode.Disconnected => "disconnected", - EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected", + EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State switch + { + ConnectionState.Connected => "connected", + ConnectionState.SessionCopyMissing => "copyMissing", + _ => "notConnected", + }, _ => "connected", }; var link = state == "notConnected" diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs index 3035868..1edd824 100644 --- a/src/Febe.Web/Api/FebeJsonContext.cs +++ b/src/Febe.Web/Api/FebeJsonContext.cs @@ -48,6 +48,7 @@ namespace Febe.Web.Api; [JsonSerializable(typeof(LoginDto))] [JsonSerializable(typeof(Library.LibraryChange))] [JsonSerializable(typeof(ConnectionStatusDto))] +[JsonSerializable(typeof(ConnectionSettingsDto))] [JsonSerializable(typeof(BeginDrivingRequest))] [JsonSerializable(typeof(CancelDrivingRequest))] [JsonSerializable(typeof(FinishDto))] diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs index 39fb041..6b73f75 100644 --- a/src/Febe.Web/Api/LibraryApi.cs +++ b/src/Febe.Web/Api/LibraryApi.cs @@ -237,6 +237,7 @@ public static class LibraryApi folder = string.IsNullOrEmpty(directory) ? accountFolder : Path.Combine(accountFolder, directory); } + var path = files.Resolve(account, m); return new MediaDto( m.Id, m.Position, @@ -248,8 +249,9 @@ public static class LibraryApi relative is null ? null : Path.GetFileName(LibraryLayout.ToPlatform(relative)), folder, m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null, - files.Resolve(account, m) is not null, - ApiMapping.State(m.State)); + path is not null, + ApiMapping.State(m.State), + IsDamaged(m, path)); }).ToList(); return new EntryDto( @@ -272,6 +274,14 @@ public static class LibraryApi media); } + /// + /// «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). + /// + 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) { var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato."); diff --git a/src/Febe.Web/Api/Part2Dtos.cs b/src/Febe.Web/Api/Part2Dtos.cs index 5b56b85..6bdc318 100644 --- a/src/Febe.Web/Api/Part2Dtos.cs +++ b/src/Febe.Web/Api/Part2Dtos.cs @@ -5,8 +5,33 @@ namespace Febe.Web.Api; // ---------------------------------------------------------------- connection (PROTOCOLLO.md) -/// GET /api/connection. : notConnected, connected, verificationRequired, browserUnavailable. -public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl); +/// +/// GET /api/connection. : notConnected, connected, copyMissing, verificationRequired, +/// browserUnavailable. only with the raccolta «richieste». +/// +public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl, SavedSessionDto? SavedSession = null); + +/// +/// The saved session in counts and names (issue #36, S4b): present, none or unreadable; +/// Unix milliseconds. Never a value. +/// +public sealed record SavedSessionDto( + string State, + long? CopiedAt, + int Cookies, + int ValuesPresent, + int ValuesExpected, + IReadOnlyList MissingValues, + int DocIdsPresent, + int DocIdsExpected, + IReadOnlyList MissingDocIds, + int NeededMissing); + +/// +/// GET/PUT /api/connection/settings: what an incomplete copy of the session does, sostituisci (the +/// default) or tieni-completa. +/// +public sealed record ConnectionSettingsDto(string IncompleteCopy); /// POST /api/connection/begin. public sealed record BeginDrivingRequest(bool OpenLogin); diff --git a/src/Febe.Web/Connection/IConnectionService.cs b/src/Febe.Web/Connection/IConnectionService.cs index 2f051c8..34fb95c 100644 --- a/src/Febe.Web/Connection/IConnectionService.cs +++ b/src/Febe.Web/Connection/IConnectionService.cs @@ -14,6 +14,48 @@ public enum ConnectionState /// The browser is not available (starting, crashed, demo without browser). BrowserUnavailable, + + /// + /// The session cookie is in the browser, but the raccolta «richieste» has no readable saved session to send it with + /// (issue #36, S4b): «Serve «Ho finito»». The engine waits until a copy is made. + /// + SessionCopyMissing, +} + +/// +/// The saved session of the raccolta «richieste» as the Collegamento page shows it (issue #36, S4b): counts and names +/// only, never a value (rule 10). +/// +/// , or . +/// When the copy was made; null when there is none or it is not known. +/// How many cookies it holds. +/// Values of the page it holds. +/// Values of the page the copy reads. +/// Names of the values it lacks. +/// doc_id it holds. +/// doc_id the copy reads. +/// Operations whose doc_id it lacks. +/// How many of those a configured operation sends (its requests do not leave). +public sealed record SavedSessionStatus( + string State, + DateTimeOffset? CopiedAt, + int Cookies, + int ValuesPresent, + int ValuesExpected, + IReadOnlyList MissingValues, + int DocIdsPresent, + int DocIdsExpected, + IReadOnlyList MissingDocIds, + int NeededMissing) +{ + /// A readable saved session. + public const string Present = "present"; + + /// No saved session. + public const string None = "none"; + + /// A file that cannot be read: counts as none. + public const string Unreadable = "unreadable"; } /// What the interface knows about the link to Instagram. @@ -22,12 +64,14 @@ public enum ConnectionState /// Display name, when known. /// True while Alberto is using the browser (login page, remote view, browser window): the engine is still. /// Address shown in the remote view's address bar, without query string. +/// The saved session (raccolta «richieste»); null when this start keeps none. public sealed record ConnectionStatus( ConnectionState State, string? Username, string? DisplayName, bool UserIsDriving, - string? CurrentUrl); + string? CurrentUrl, + SavedSessionStatus? SavedSession = null); /// Result of «Ho finito» on the Collegamento page. /// True when the session cookie now exists. @@ -70,6 +114,15 @@ public interface IConnectionService /// Task ReleaseAsync(CancellationToken ct); + /// + /// The Febe page that took the browser was left (another page, a reload, the tab closed) while the browser is the + /// remote view (Docker, answer of Alberto of 25 November 2026, spec §6.0 «Quando si copia»): like closing the window + /// «Browser di Febe» on Windows, not like «Annulla». If within a moment no view opens again and no «Accedi» / «Usa il + /// browser» comes (a reload is not leaving), the session is copied while the page is still his, and then the page goes + /// back to the engine. By default, for a service without a saved session to copy, it is «Annulla». + /// + Task LeavePageAsync(CancellationToken ct) => CancelAsync(ct); + /// «Scollega» (after confirmation in the UI): stops the engine and deletes the browser profile. Task DisconnectAsync(CancellationToken ct); } diff --git a/src/Febe.Web/Connection/PROTOCOLLO.md b/src/Febe.Web/Connection/PROTOCOLLO.md index b67224e..04ecc1b 100644 --- a/src/Febe.Web/Connection/PROTOCOLLO.md +++ b/src/Febe.Web/Connection/PROTOCOLLO.md @@ -7,11 +7,12 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe | Endpoint | Corpo e risposta | |---|---| -| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl }` | +| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"copyMissing"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl, savedSession }` | | `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera; senza, se il browser è a riposo (`about:blank`) apre la pagina iniziale (sotto) | | `POST /api/connection/finish` | → `{ connected: bool, message }` («Ho finito») | | `POST /api/connection/cancel` | corpo facoltativo `{ pageLeft: bool }` → 204 («Annulla»; con `pageLeft` la pagina è stata lasciata, sotto) | | `POST /api/connection/disconnect` | → 204 («Scollega», dopo la conferma nell'interfaccia) | +| `GET /api/connection/settings`, `PUT /api/connection/settings` | `{ incompleteCopy: "sostituisci"\|"tieni-completa" }`: che cosa fa una copia della sessione incompleta (raccolta «richieste»); un altro valore → 400 | | `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale | **Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la @@ -27,9 +28,23 @@ di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`. +**Raccolta «richieste»** (issue #36, S4b): `savedSession` è `null` senza sessione salvata in questo avvio («pagine», o +nessuna operazione configurata); altrimenti `{ state: "present"|"none"|"unreadable", copiedAt (ms Unix o null), cookies, +valuesPresent, valuesExpected, missingValues: [nomi], docIdsPresent, docIdsExpected, missingDocIds: [operazioni], +neededMissing }`: solo conteggi e nomi, mai valori. Con il cookie di sessione nel browser ma senza una sessione salvata +leggibile lo stato è `copyMissing` («Serve «Ho finito»»): il motore aspetta, e `/api/engine` dice `copyMissing` nel +collegamento. La sessione si copia a «Ho finito», alla chiusura della finestra del browser su Windows, lasciando la +pagina del browser in Docker (sotto) e quando il permesso di guida finisce da solo, sempre prima che la pagina torni al +motore. «Annulla» non copia mai. + L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch` -con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo). +con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker non è «Annulla» (`IConnectionService.LeavePageAsync`, +risposta di Alberto del 25 novembre 2026): è come chiudere la finestra del browser su Windows. Febe lo nota e aspetta +5 secondi; anche la vista remota chiusa dalla sua pagina (scheda chiusa, collegamento perso, non sostituita da un'altra +scheda) fa ricominciare l'attesa. Se in quel tempo non si apre un'altra vista e non arriva un `begin` (una pagina +ricaricata fa tutti e due), copia la sessione come alla chiusura della finestra (solo da una pagina del sito che non sia +di accesso o di verifica), poi il permesso finisce e il motore rimette il browser a riposo. Su Windows, dove il browser è una finestra a parte, finisce solo il permesso tenuto dalla pagina: la finestra resta com'è, sullo schermo e con la sua pagina, finché Alberto non la chiude (e finché è sullo schermo il motore resta fermo). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`. diff --git a/src/Febe.Web/Demo/DemoImages.cs b/src/Febe.Web/Demo/DemoImages.cs index 933d615..01f7dbc 100644 --- a/src/Febe.Web/Demo/DemoImages.cs +++ b/src/Febe.Web/Demo/DemoImages.cs @@ -1,4 +1,6 @@ -using SkiaSharp; +using System.Numerics; +using Febe.Core.Codecs.Images; +using Febe.Core.Drawing; namespace Febe.Web.Demo; @@ -35,8 +37,8 @@ public static class DemoImages { ArgumentOutOfRangeException.ThrowIfLessThan(width, 16); ArgumentOutOfRangeException.ThrowIfLessThan(height, 16); - using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); - using (var canvas = new SKCanvas(bitmap)) + var image = new RgbaImage(width, height); + using (var canvas = new Canvas(image)) { var painter = new Painter(canvas, width, height, new Random(seed * 7919 + (int)subject)); switch (subject) @@ -59,64 +61,54 @@ public static class DemoImages } } - using var image = SKImage.FromBitmap(bitmap); - using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality); - return data.ToArray(); + return JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = quality }); } - private sealed class Painter(SKCanvas canvas, float w, float h, Random random) + /// A rectangle by its edges. + 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 T Pick(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( - (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 static Color Mix(Color a, Color b, float t) => a.Mix(b, t).WithAlpha(255); - 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.Translate(cx, cy); - canvas.RotateDegrees(rotate); - canvas.DrawOval(new SKRect(-rx, -ry, rx, ry), paint); + canvas.Rotate(rotate); + canvas.FillEllipse(0, 0, rx, ry, color); 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 }; - canvas.DrawRoundRect(new SKRect(x, y, x + rw, y + rh), radius, radius, paint); + if (radius > 0) + { + canvas.FillRoundRect(x, y, rw, rh, radius, color); + } + else + { + canvas.FillRect(x, y, rw, rh, color); + } } /// A soft ridge across the picture at height , filled down to the bottom. - 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); const int steps = 48; for (var i = 0; i <= steps; i++) @@ -138,23 +130,23 @@ public static class DemoImages var cx = R(-0.1f, 1.1f) * w; var cy = R(top, bottom) * 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 - (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); - 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) { 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)); var greens = Pick( new[] { C(0x8DB867), C(0x6E9E4C), C(0x4F8A3E), C(0x3C7232) }, @@ -164,7 +156,7 @@ public static class DemoImages for (var layer = 0; layer < 4; layer++) { 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]); if (!road && layer < 3) { @@ -178,7 +170,7 @@ public static class DemoImages if (road) { var horizon = baseY + (h * 0.03f); - using var path = new SKPathBuilder(); + var path = new PathBuilder(); path.MoveTo(w * 0.47f, horizon); path.LineTo(w * 0.53f, horizon); path.LineTo(w * 0.86f, h); @@ -208,13 +200,13 @@ public static class DemoImages public void Mountains() { 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) }; for (var r = 0; r < 3; r++) { var baseY = h * (0.55f + (r * 0.08f)); var peaks = random.Next(2, 4) + r; - using var path = new SKPathBuilder(); + var path = new PathBuilder(); path.MoveTo(0, h); path.LineTo(0, baseY); 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 ratio = depth / (baseY - py); - using var cap = new SKPathBuilder(); + var cap = new PathBuilder(); cap.MoveTo(px, py); cap.LineTo(px + (half * ratio), py + depth); 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 size = h * R(0.06f, 0.11f); var y = groundY + (h * R(-0.01f, 0.08f)); - using var tree = new SKPathBuilder(); + var tree = new PathBuilder(); tree.MoveTo(x, y - size); 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 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 sunY = h * R(0.5f, 0.6f); 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)); var hills = new[] { C(0x6B4A73), C(0x4E3A63), C(0x35294D) }; 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]); } } @@ -291,32 +283,31 @@ public static class DemoImages { var sky = Pick(C(0x8CC4E8), C(0x7BB8E2), C(0x9CCDEB)); 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)); var water = Pick(C(0x2AA3C1), C(0x1F8FB3), C(0x31A9BE)); var sand = random.Next(3) == 0; - Gradient(new SKRect(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 }) + Gradient(new Box(0, horizon, w, h), water, Mix(water, C(0x0B4A6B), 0.55f)); + 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; - canvas.DrawLine(x, y, x + (w * R(0.03f, 0.08f)), y, wave); - } + var y = horizon + ((h - horizon) * R(0.1f, 0.9f)); + var x = R(0.05f, 0.85f) * w; + canvas.DrawLine(x, y, x + (w * R(0.03f, 0.08f)), y, waveWidth, foam, LineCap.Round); } 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)); } var bx = w * R(0.3f, 0.65f); var by = horizon + ((h - horizon) * R(0.2f, 0.4f)); 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.LineTo(bx + (s * 0.45f), by - (s * 0.1f)); sail.LineTo(bx, by - (s * 0.1f)); @@ -324,8 +315,8 @@ public static class DemoImages Fill(sail, C(0xF6F6F4)); } - using (var sail2 = new SKPathBuilder()) { + var sail2 = new PathBuilder(); 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.38f), by - (s * 0.12f)); @@ -333,8 +324,8 @@ public static class DemoImages Fill(sail2, C(0xE0533F)); } - using (var hull = new SKPathBuilder()) { + var hull = new PathBuilder(); 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.4f), by + (s * 0.1f)); @@ -346,10 +337,10 @@ public static class DemoImages 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++) { - 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++) @@ -384,7 +375,7 @@ public static class DemoImages public void Leaves(bool flowers) { 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 size = Math.Max(w, h); for (var i = 0; i < 46; i++) @@ -395,11 +386,10 @@ public static class DemoImages var angle = R(0, 360); var color = greens[random.Next(greens.Length)]; 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.Translate(cx, cy); - canvas.RotateDegrees(angle); - canvas.DrawLine(-rx * 0.85f, 0, rx * 0.85f, 0, vein); + canvas.Rotate(angle); + 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(); } @@ -426,21 +416,16 @@ public static class DemoImages { var table = Pick(C(0xE9E6E1), C(0xEFEBE4), C(0xDCD7CF)); 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), line); - } + canvas.DrawLine(0, y, w, y + (h * 0.01f), Math.Max(2, w * 0.004f), grooves); } var r = Math.Min(w, h) * R(0.28f, 0.34f); var cx = w * R(0.42f, 0.55f); 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.DrawCircle(cx + (r * 0.04f), cy + (r * 0.06f), r, shadow); - } + canvas.FillBlurredCircle(cx + (r * 0.04f), cy + (r * 0.06f), r, r * 0.06f, new Color(0, 0, 0, 40)); Circle(cx, cy, r, C(0xFAFAF8)); Circle(cx, cy, r * 0.78f, C(0xF0EEEA)); @@ -458,24 +443,23 @@ public static class DemoImages var cr = Math.Min(w, h) * 0.085f; Circle(cupX, cupY, cr, C(0xF5F3EF)); 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), fork); + 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); } public void Portrait() { 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 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 cx = w * 0.5f; var unit = Math.Min(w, h * 0.8f); 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); - using var top = new SKPathBuilder(); - 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); + var top = new PathBuilder(); + 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(); Fill(top, hair); } @@ -484,23 +468,23 @@ public static class DemoImages { var wall = Pick(C(0xE5DFCF), C(0xE9E2D2), C(0xDCD6C6)); var floorY = h * R(0.68f, 0.74f); - Gradient(new SKRect(0, 0, w, floorY), Mix(wall, SKColors.White, 0.2f), wall); - Gradient(new SKRect(0, floorY, w, h), C(0xC9AE84), C(0xB89A6E)); + Gradient(new Box(0, 0, w, floorY), Mix(wall, Color.White, 0.2f), wall); + Gradient(new Box(0, floorY, w, h), C(0xC9AE84), C(0xB89A6E)); var winX = w * R(0.25f, 0.45f); var winW = w * R(0.26f, 0.34f); var winY = h * 0.1f; var winH = h * 0.38f; 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, winY + (winH / 2) - 3, winW, 6, C(0xF7F7F5)); var sofa = Pick(C(0x6E9F7A), C(0x4E8F86), C(0x8A6A9E), C(0xA05A5A)); var sx = w * R(0.05f, 0.15f); 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); 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.LineTo(px + (w * 0.045f), floorY - (h * 0.08f)); pot.LineTo(px + (w * 0.035f), floorY + (h * 0.01f)); @@ -518,34 +502,34 @@ public static class DemoImages 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 size = Math.Max(w, h); for (var i = 0; i < 40; i++) { 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)) }; - canvas.DrawCircle(R(0, 1) * w, R(0, 1) * h, size * R(0.02f, 0.06f), paint); + var sigma = size * R(0.004f, 0.012f); + 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() { - 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) }; for (var i = 0; i < 5; i++) { var x = w * (0.12f + (i * 0.19f)) + R(-0.04f, 0.04f) * w; var color = beams[random.Next(beams.Length)]; - using var paint = new SKPaint { IsAntialias = true }; - paint.Shader = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, h * 0.75f), [color.WithAlpha(40), color.WithAlpha(190)], null, SKShaderTileMode.Clamp); - using var beam = new SKPathBuilder(); + var light = new LinearGradientBrush(new Vector2(0, 0), new Vector2(0, h * 0.75f), [color.WithAlpha(40), color.WithAlpha(190)]); + var beam = new PathBuilder(); 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.Close(); - using var beamPath = beam.Detach(); - canvas.DrawPath(beamPath, paint); + canvas.Fill(beam, light); } Rect(0, h * 0.72f, w, h * 0.04f, C(0x2B2838)); @@ -560,7 +544,7 @@ public static class DemoImages public void Houses() { 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 x = 0f; while (x < w) @@ -569,7 +553,7 @@ public static class DemoImages var top = h * R(0.12f, 0.4f); var color = facades[random.Next(facades.Length)]; 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; for (var wy = top + (cell * 0.8f); wy < h - cell; wy += cell * 1.4f) { diff --git a/src/Febe.Web/Demo/DemoPart2.cs b/src/Febe.Web/Demo/DemoPart2.cs index 1ce513e..f872d41 100644 --- a/src/Febe.Web/Demo/DemoPart2.cs +++ b/src/Febe.Web/Demo/DemoPart2.cs @@ -1,6 +1,8 @@ using System.Security.Cryptography; using Febe.Core.Abstractions; +using Febe.Core.Codecs.Images; using Febe.Core.Domain; +using Febe.Core.Drawing; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Web.Api; @@ -8,7 +10,6 @@ using Febe.Web.Connection; using Febe.Web.Engine; using Febe.Web.Library; using Microsoft.AspNetCore.Http; -using SkiaSharp; namespace Febe.Web.Demo; @@ -90,18 +91,18 @@ public sealed class DemoBrowserPreview(IHttpContextAccessor accessor, DemoWorld const int width = 640; const int height = 360; - using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); - using (var canvas = new SKCanvas(bitmap)) + using var frame = new RgbaImage(width, height); + 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 wide = tall * 9 / 16; var gap = 26f; 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++) { - using var image = SKImage.FromEncodedData(files[i]); + using var image = DecodeOrNull(files[i]); if (image is null) { continue; @@ -112,18 +113,27 @@ public sealed class DemoBrowserPreview(IHttpContextAccessor accessor, DemoWorld var h = tall * scale; var x = left + (i * (wide + gap)) + ((wide - w) / 2); var y = (height - h) / 2; - var rect = new SKRect(x, y, x + w, y + h); - canvas.DrawImage(image, rect, new SKSamplingOptions(SKCubicResampler.Mitchell)); + canvas.DrawImage(image, x, y, w, h); if (i != 1) { - canvas.DrawRect(rect, dim); + canvas.FillRect(x, y, w, h, dim); } } } - using var frame = SKImage.FromBitmap(bitmap); - using var encoded = frame.Encode(SKEncodedImageFormat.Jpeg, 80); - return encoded.ToArray(); + return JpegEncoder.Encode(frame, new JpegEncoderOptions { Quality = 80 }); + } + + private static RgbaImage? DecodeOrNull(byte[] bytes) + { + try + { + return ImageDecoder.Decode(bytes); + } + catch (ImageDecodeException) + { + return null; + } } } @@ -270,22 +280,22 @@ internal static class DemoDuplicates /// The picture resized by and recompressed: the same photo saved again, smaller. public static (byte[] Bytes, int Width, int Height)? Variant(byte[] jpeg, double scale, int quality) { - using var image = SKImage.FromEncodedData(jpeg); - if (image is null) + RgbaImage image; + try + { + image = ImageDecoder.Decode(jpeg); + } + catch (ImageDecodeException) { return null; } - var width = Math.Max(16, (int)Math.Round(image.Width * scale)); - 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)) + using (image) { - 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); } } diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index 633fe34..7a5e494 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -802,6 +802,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento .collega-destra h2.sez{margin-bottom:12px} .collega-destra .avviso{font-size:13.5px;line-height:1.5;padding:13px 16px} .nota-password{background:var(--accento-tinta)} +.sessione-salvata{padding:14px 16px;font-size:13.5px;line-height:1.5} +.sessione-salvata p{margin:0 0 6px} +.sessione-salvata h2.sez{margin-bottom:8px} +.sessione-salvata h3.sez{font-size:13.5px;font-weight:650;margin:12px 0 8px} +.sessione-salvata .avviso{margin:4px 0 8px} +.sessione-salvata .scelte{display:flex;flex-direction:column;gap:10px} +.sessione-salvata .scelte .voce{align-items:flex-start} +.sessione-salvata .scelte .voce .tondo{margin-top:2px} +.sessione-salvata .scelte small{display:block;color:var(--testo-2);font-size:12.5px} .passi-collegamento{list-style:none;margin:0 0 8px;padding:0;display:flex;flex-direction:column;gap:18px} .passi-collegamento li{display:flex;gap:14px} .passi-collegamento .numero{width:24px;height:24px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--accento-tinta);color:var(--accento-scuro);font-weight:650;font-size:12.5px;margin-top:1px} diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js index 003deef..354f002 100644 --- a/src/Febe.Web/wwwroot/js/core/shell.js +++ b/src/Febe.Web/wwwroot/js/core/shell.js @@ -63,7 +63,7 @@ function renderStatus(state) { const s = state.snapshot; const meter = s.profilesOpenedToday; const connection = state.connection; - const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato'); + const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : connection.state === 'copyMissing' ? 'stato.copiaMancante' : 'stato.collegato'); // The own account is known only after the first sweep (a verification can come before it): no «@null». const who = connection.state === 'notConnected' ? h('div.chi', h('span.av.segnaposto', icon('user', 's')), diff --git a/src/Febe.Web/wwwroot/js/pages/browser.js b/src/Febe.Web/wwwroot/js/pages/browser.js index 059f52f..ad0b7d8 100644 --- a/src/Febe.Web/wwwroot/js/pages/browser.js +++ b/src/Febe.Web/wwwroot/js/pages/browser.js @@ -1,8 +1,8 @@ // Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the // server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the // engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito» -// (another page, a reload, closing the tab) gives the browser back, like «Annulla» (on Windows the window stays as it -// is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection) +// (another page, a reload, closing the tab) gives the browser back, like closing the window on Windows: the server copies +// the session if no view opens again within a moment (on Windows the window stays as it is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection) // opens the login page, once: the parameter leaves the address straight away. import { api } from '../core/api.js'; diff --git a/src/Febe.Web/wwwroot/js/pages/connection.js b/src/Febe.Web/wwwroot/js/pages/connection.js index 6f54b60..ea18578 100644 --- a/src/Febe.Web/wwwroot/js/pages/connection.js +++ b/src/Febe.Web/wwwroot/js/pages/connection.js @@ -2,7 +2,9 @@ // the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without // being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di // Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and -// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. +// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. With the raccolta «richieste» +// (issue #36, S4b) the page also shows the saved session in counts and names (never values), the choice for an +// incomplete copy, and «Serve «Ho finito»» when the browser is connected but the copy is missing. import { api } from '../core/api.js'; import { caps } from '../core/context.js'; @@ -10,10 +12,10 @@ import { h, icon, fill } from '../core/dom.js'; import { engineState, refreshEngine } from '../core/engine.js'; import { navigate } from '../core/shell.js'; import { t } from '../core/text.js'; -import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js'; +import { avatar, confirmDialog, label, radio, showError, toast } from '../core/ui.js'; import { remoteView } from './remote-view.js'; -const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' }; +const STATE_KIND = { notConnected: 'ambra', connected: 'verde', copyMissing: 'ambra', verificationRequired: 'rosso', browserUnavailable: '' }; /** True while the engine waits for «Riprendi» (the stop strip of a verification or a disconnection). */ function waitsForResume(state) { @@ -40,9 +42,10 @@ export async function beginDriving(openLogin) { /** * The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin() * takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the - * page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like «Annulla» (the - * browser goes back to the empty page and the engine may work again); on Windows the window «Browser di Febe» stays as - * it is, on screen until Alberto closes it (issue #52), and only the page's hold ends. + * page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like closing the + * window on Windows, not like «Annulla» (answer of 25 November 2026: if no view opens again within a moment, the + * server copies the session and the engine may work again; a reload opens the view again); on Windows the window + * «Browser di Febe» stays as it is, on screen until Alberto closes it (issue #52), and only the page's hold ends. */ export function drivingLease(page) { let held = false; @@ -120,6 +123,7 @@ export async function mountConnection(page) { fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || '')); if (status.state === 'connected') drawConnected(); else if (status.state === 'browserUnavailable') drawUnavailable(); + else if (status.state === 'copyMissing') drawLogin({ copyMissing: true }); else drawLogin(); } @@ -145,15 +149,17 @@ export async function mountConnection(page) { }); // ------------------------------------------------------------------------------------------- login or verification - function drawLogin() { + function drawLogin({ copyMissing = false } = {}) { const verification = status.state === 'verificationRequired'; + // Connected but without the copy for the requests: the start page (the site's home), never the login page. + const login = !verification && !copyMissing; waitingResume = false; closeView(); - lease.begin(!verification); + lease.begin(login); if (windows) { fill(left, windowPanel()); } else { - view = remoteView(page, { url: status.currentUrl, login: !verification }); + view = remoteView(page, { url: status.currentUrl, login }); fill(left, view.element); } const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi'); @@ -161,6 +167,8 @@ export async function mountConnection(page) { fill(right, verification ? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto'))) + : copyMissing + ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', h('b', t('impostazioni.collegamento.copiaMancanteTitolo')), ' ', t('impostazioni.collegamento.copiaMancanteTesto'))) : h('div', h('h2.sez', t('impostazioni.collegamento.come')), h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))), @@ -168,6 +176,7 @@ export async function mountConnection(page) { h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))), // Windows: one engine per account (spec §5) said before the login too; Docker keeps mockup 10 as it is. windows ? h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))) : null, + copyMissing ? savedSessionBox(status.savedSession, page) : null, message, h('div.molla'), h('div.bottoni-collegamento', @@ -235,7 +244,8 @@ export async function mountConnection(page) { fill(right, passwordNote(windows), h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))), - h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore')))); + h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))), + savedSessionBox(status.savedSession, page)); } async function useBrowser() { @@ -287,6 +297,81 @@ export async function mountConnection(page) { await draw(); } +/** + * The saved session of the raccolta «richieste» (issue #36, S4b): when it was copied, the values and doc_id present + * and the names of the missing ones — counts and names only, the server never sends a value — and the choice for an + * incomplete copy. Nothing without a saved session in this start («pagine»). + */ +export function savedSessionBox(saved, page) { + if (!saved) return null; + const k = (key, vars) => t(`impostazioni.collegamento.salvata.${key}`, vars); + const lines = []; + if (saved.state === 'present') { + if (saved.copiedAt) { + const when = new Date(saved.copiedAt).toLocaleString('it-IT', { dateStyle: 'medium', timeStyle: 'short' }); + lines.push(h('p', k('copiata', { quando: when }))); + } + lines.push(h('p.muto', [ + k('valori', { presenti: String(saved.valuesPresent), attesi: String(saved.valuesExpected) }), + k('docId', { presenti: String(saved.docIdsPresent), attesi: String(saved.docIdsExpected) }), + k('cookie', { n: String(saved.cookies) }), + ].join(' '))); + const missing = [...(saved.missingValues || []), ...(saved.missingDocIds || [])]; + if (missing.length) lines.push(h('p', k('mancano', { nomi: missing.join(', ') }))); + lines.push(saved.neededMissing + ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', k('servono', { n: String(saved.neededMissing) }))) + : h('p', k('completa'))); + } else { + lines.push(h('p', k(saved.state === 'unreadable' ? 'illeggibile' : 'nessuna'))); + } + + // Neither choice is shown as chosen, and neither can be picked, until the server says which one is stored: the page + // never claims a choice the next copy will not follow. Once Alberto picks one, a late answer no longer changes it; + // a choice the server did not save goes back to the one before. + let stored = null; + let chosen = false; + const show = (value) => { + keep.input.checked = value === 'tieni-completa'; + replace.input.checked = value === 'sostituisci'; + }; + const choose = async (value) => { + chosen = true; + const before = stored; + try { + const settings = await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } }); + stored = settings && settings.incompleteCopy ? settings.incompleteCopy : value; + unknown.hidden = true; + toast(k('salvato')); + } catch (error) { + show(before); + showError(error); + } + }; + const replace = radio({ name: 'copia-incompleta', value: 'sostituisci', onchange: choose, labelNode: h('span', h('b', k('sostituisci')), h('small', k('sostituisciAiuto'))) }); + const keep = radio({ name: 'copia-incompleta', value: 'tieni-completa', onchange: choose, labelNode: h('span', h('b', k('tieni')), h('small', k('tieniAiuto'))) }); + const unknown = h('p.aiuto.piccolo.scelta-ignota', { hidden: true }, k('sceltaIgnota')); + for (const choice of [replace, keep]) choice.input.disabled = true; + api('/api/connection/settings', { signal: page && page.signal }).then((settings) => { + if (chosen) return; + stored = settings.incompleteCopy; + show(stored); + }).catch(() => { + if (page && page.signal && page.signal.aborted) return; // the page was left + if (!chosen) unknown.hidden = false; + }).finally(() => { + if (page && page.signal && page.signal.aborted) return; + for (const choice of [replace, keep]) choice.input.disabled = false; + }); + + return h('div.pannello.sessione-salvata', + h('h2.sez', k('titolo')), + ...lines, + h('p.aiuto.piccolo', k('nota')), + h('h3.sez', k('incompleta')), + h('div.scelte', { role: 'radiogroup', 'aria-label': k('incompleta') }, replace, keep), + unknown); +} + /** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */ export function passwordNote(windows) { return h('div.avviso.nota-password', icon('shield-check', 's'), diff --git a/src/Febe.Web/wwwroot/js/pages/settings-about.js b/src/Febe.Web/wwwroot/js/pages/settings-about.js index 4a54508..e311a41 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings-about.js +++ b/src/Febe.Web/wwwroot/js/pages/settings-about.js @@ -1,6 +1,6 @@ // 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 -// 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 { h, icon, fill, brand } from '../core/dom.js'; diff --git a/src/Febe.Web/wwwroot/js/pages/viewer.js b/src/Febe.Web/wwwroot/js/pages/viewer.js index da6e2c7..a3b302c 100644 --- a/src/Febe.Web/wwwroot/js/pages/viewer.js +++ b/src/Febe.Web/wwwroot/js/pages/viewer.js @@ -143,6 +143,11 @@ export function openViewer({ tile, source, origin, onDeleted }) { h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante')))); 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`; 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) })); diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index d69c491..1727851 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -24,6 +24,7 @@ "nessunAccount": "Nessun account", "verifica": "Verifica richiesta", "scollegato": "Sessione chiusa", + "copiaMancante": "Serve «Ho finito»", "accountDaLeggere": "Nome non ancora noto", "nonDisponibile": "Stato del motore non disponibile" }, @@ -201,6 +202,8 @@ "elimina": "Elimina dalla libreria", "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.", + "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}", "tipoSingolo": "{tipo}, {media}", "seguito": "Seguito", @@ -690,9 +693,32 @@ "stati": { "notConnected": "Non collegato", "connected": "Collegato", + "copyMissing": "Serve «Ho finito»", "verificationRequired": "Verifica richiesta", "browserUnavailable": "Browser non disponibile" }, + "copiaMancanteTitolo": "Manca la copia della sessione", + "copiaMancanteTesto": "Il browser è collegato, ma Febe non ha ancora una copia della sessione per le richieste (o non riesce a leggerla). Apri la tua pagina iniziale nel browser e premi «Ho finito»: fino ad allora il motore aspetta.", + "salvata": { + "titolo": "Sessione salvata per le richieste", + "copiata": "Copiata {quando}.", + "nessuna": "Nessuna copia: premi «Ho finito» sulla tua pagina iniziale.", + "illeggibile": "C'è un file, ma Febe non riesce a leggerlo (un'altra chiave o un file rovinato): conta come nessuna copia. Il prossimo «Ho finito» lo sostituisce.", + "valori": "Valori della pagina: {presenti} su {attesi}.", + "docId": "doc_id: {presenti} su {attesi}.", + "cookie": "Cookie: {n}.", + "mancano": "Mancano: {nomi}.", + "servono": "{n} di questi serve alle richieste configurate: le richieste che lo usano non partono e, alla prima, Febe si ferma come disconnessione.|{n} di questi servono alle richieste configurate: quelle richieste non partono e, alla prima, Febe si ferma come disconnessione.", + "completa": "Nulla di ciò che le richieste configurate mandano manca.", + "nota": "Qui ci sono solo conteggi e nomi, mai i valori.", + "incompleta": "Se una copia nuova è incompleta", + "sostituisci": "Sostituisci comunque (consigliato)", + "sostituisciAiuto": "La copia nuova prende sempre il posto di quella salvata: una copia più vecchia potrebbe avere i cookie di un altro accesso.", + "tieni": "Tieni la copia completa", + "tieniAiuto": "Se alla copia nuova manca qualcosa che le richieste usano e quella salvata è completa, Febe tiene quella salvata e te lo dice.", + "salvato": "Scelta salvata: vale dalla prossima copia.", + "sceltaIgnota": "Febe non è riuscito a leggere la scelta salvata: scegline una per salvarla di nuovo." + }, "come": "Come collegarti", "passi": [ { @@ -817,7 +843,6 @@ { "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": "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": "WebView2", "testo": "solo versione Windows, licenza Microsoft" } ], diff --git a/tests/Febe.Tests.Windows/BrowserWindowTests.cs b/tests/Febe.Tests.Windows/BrowserWindowTests.cs index 41631cd..a972531 100644 --- a/tests/Febe.Tests.Windows/BrowserWindowTests.cs +++ b/tests/Febe.Tests.Windows/BrowserWindowTests.cs @@ -2,6 +2,7 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Interop; +using Febe.App; using Febe.Browser.Cdp; using Febe.Desktop.Browser; using Febe.SitoDiProva; @@ -162,7 +163,14 @@ public sealed class BrowserWindowTests public async Task AMinimisedWindowKeepsAlbertoAtTheWheelUntilItIsMinimisedTooLong() { var ct = TestContext.CancellationToken; - await using var bed = await BrowserBed.CreateAsync("finestra-ridotta"); + + // What the window tells the connection when it lets go (S4b): the log must not say «chiusa» for this. + var letGo = new System.Collections.Concurrent.ConcurrentQueue(); + await using var bed = await BrowserBed.CreateAsync("finestra-ridotta", copyOnWindowClosed: (how, _) => + { + letGo.Enqueue(how); + return Task.CompletedTask; + }); await bed.StartAsync(ct); var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra"); await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromSeconds(1)); @@ -174,6 +182,7 @@ public sealed class BrowserWindowTests // Left there: restored and put out of view, as if closed (S2: never minimised for long). await bed.WaitUntilAsync(() => !bed.Browser.UserIsDriving, TimeSpan.FromSeconds(15), "la fine della guida dopo la finestra ridotta a icona", ct); + CollectionAssert.AreEqual(new[] { BrowserWindowLetGo.MinimizedTooLong }, letGo.ToArray()); Assert.AreEqual(WindowState.Normal, await bed.OnUiAsync(() => window.WindowState)); Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen)); Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar)); diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs index 03f3928..fe082de 100644 --- a/tests/Febe.Tests.Windows/Support/BrowserBed.cs +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -50,7 +50,8 @@ internal sealed class BrowserBed : IAsyncDisposable /// does nothing (never the default login page of the options, which is Instagram's). /// /// What «Pagina iniziale» does instead (it wins over ). - public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func? startPage = null, Func? openStartPage = null) + /// What closing the window, or leaving it minimised too long, does (S4b); null: nothing. + public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func? startPage = null, Func? openStartPage = null, Func? copyOnWindowClosed = null) { var folder = new TestFolder(name); var ui = await UiThread.StartAsync(); @@ -63,7 +64,7 @@ internal sealed class BrowserBed : IAsyncDisposable var tracker = new BrowserUseTracker(); WebView2Browser? built = null; openStartPage ??= startPage is null ? null : async ct => await built!.Cdp.NavigateAsync(startPage(), ct); - var context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage); + var context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage, copyOnWindowClosed); var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2()); // Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits. diff --git a/tests/Febe.Tests.Windows/Support/DesktopBed.cs b/tests/Febe.Tests.Windows/Support/DesktopBed.cs index 8a1e1af..290d1af 100644 --- a/tests/Febe.Tests.Windows/Support/DesktopBed.cs +++ b/tests/Febe.Tests.Windows/Support/DesktopBed.cs @@ -58,7 +58,9 @@ internal sealed class DesktopBed : IAsyncDisposable /// Prefix of the temporary folder. /// --accesso-di-prova: the composition opens the test site once at start-up. - public static async Task StartAsync(string name, bool autoLogin, CancellationToken ct) + /// Cancels the start. + /// More options of Febe.exe (--raccolta richieste). + public static async Task StartAsync(string name, bool autoLogin, CancellationToken ct, string[]? extra = null) { var site = await TestSite.StartAsync(new TestSiteOptions(), ct); var folder = new TestFolder(name); @@ -77,6 +79,8 @@ internal sealed class DesktopBed : IAsyncDisposable arguments.Add("--accesso-di-prova"); } + arguments.AddRange(extra ?? []); + if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem)) { throw new ArgumentException(problem); diff --git a/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs index 8dd5722..d444503 100644 --- a/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs +++ b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs @@ -1,3 +1,4 @@ +using Febe.Browser.Cdp; using Febe.Core.Storage; using Febe.Tests.Windows.Support; using Febe.Web.Connection; @@ -64,4 +65,43 @@ public sealed class WebView2ConnectionTests Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text); Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text); } + + [TestMethod] + [Timeout(240_000, CooperativeCancellation = true)] + public async Task WithRichiesteClosingTheWindowCopiesTheSessionBeforeThePageGoesBack() + { + // Issue #36, S4b (answer 5 of 18 November 2026): the window «Browser di Febe» closed with its X, without + // «Ho finito», copies the session from the site's page into the saved session, under Alberto's lease. + var ct = TestContext.CancellationToken; + await using var bed = await DesktopBed.StartAsync("finestra-copia", autoLogin: false, ct, ["--raccolta", "richieste"]); + var app = bed.App; + await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct); + var connection = app.Connection!; + var browser = bed.Browser; + var savedSession = app.SavedSession ?? throw new AssertFailedException("the test site's catalog has configured operations"); + var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra"); + + // «Accedi» (the welcome page starts the test site's session), then Alberto goes to the home of the site. + await connection.BeginUserDrivingAsync(openLogin: true, ct); + await browser.Cdp.NavigateAsync(bed.Site.Url("/"), ct); + await connection.RefreshAsync(ct); + Assert.AreEqual(ConnectionState.SessionCopyMissing, (await connection.GetStatusAsync(ct)).State, "the cookie alone is not «Collegato» with «richieste»"); + + await bed.Ui.InvokeAsync(() => + { + window.Close(); + return true; + }); + // The saved session is readable before it is written to disk and before the log lines: wait for the last of them. + await bed.WaitUntilAsync(() => Task.FromResult(savedSession.Read() is not null && bed.Lines.Any("Finestra del browser chiusa: sessione copiata")), TimeSpan.FromSeconds(30), "la copia alla chiusura della finestra", ct); + var saved = savedSession.Read()!; + Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]); + Assert.AreEqual(Febe.SitoDiProva.TestSite.EntryNonce, saved.Fields["entry_nonce"]); + Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen)); + Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State); + Assert.IsTrue(bed.Lines.Any("Finestra del browser chiusa: sessione copiata"), bed.Lines.Text); + Assert.IsFalse(bed.Lines.Any(Febe.SitoDiProva.TestSite.Lsd), "no value in the log"); + Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text); + await connection.CancelAsync(ct); + } } diff --git a/tests/Febe.Tests/Browser/SessionCaptureTests.cs b/tests/Febe.Tests/Browser/SessionCaptureTests.cs index 1ccb8c7..0a5e1f0 100644 --- a/tests/Febe.Tests/Browser/SessionCaptureTests.cs +++ b/tests/Febe.Tests/Browser/SessionCaptureTests.cs @@ -279,7 +279,7 @@ public sealed class SessionCaptureTests .CopyAsync(() => true, CancellationToken.None); Assert.AreEqual(1, needed.MissingValues); Assert.AreEqual(0, needed.MissingDocIds); - StringAssert.Contains(log[^1], "mancano app_id, che servono alle operazioni configurate"); + StringAssert.Contains(log[^1], "manca app_id, che serve alle operazioni configurate"); // With the shipped catalog the query is configured: its doc_id counts. var shipped = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, new InMemorySiteSession(null), new VirtualClock(), log.Add) @@ -289,6 +289,154 @@ public sealed class SessionCaptureTests AssertNoSecret(string.Join("\n", log)); } + [TestMethod] + public async Task KeepTheCompleteCopyKeepsTheSavedOneOnlyWhenItIsCompleteAndTheNewOneLacksWhatTheRequestsNeed() + { + // Answer 9 of 18 November 2026: «tieni la completa» is a choice; «sostituisci» stays the default. + var log = new List(); + var store = new InMemorySiteSession(null); + var choice = IncompleteCopyChoice.KeepComplete; + BrowserSessionCopier Copier(JsonObject page) => + new(Page($"http://{SiteHost}/", page: page), Plan, store, new VirtualClock(), log.Add) { IncompleteCopy = _ => Task.FromResult(choice) }; + var lacking = PageValues(); + ((JsonObject)lacking["values"]!).Remove("lsd"); + + // Nothing saved yet: the incomplete copy is saved all the same (there is no complete one to keep). + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status); + var incomplete = store.Read()!; + + // An incomplete saved copy is not one to keep: the next incomplete copy replaces it. + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status); + Assert.AreNotEqual(incomplete.Capture, store.Read()!.Capture); + + // A complete copy, then an incomplete one: the complete one stays, and the outcome says so. + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status); + var complete = store.Read(); + var kept = await Copier(lacking).CopyAsync(() => true, CancellationToken.None); + Assert.AreEqual(SessionCopyStatus.KeptComplete, kept.Status); + Assert.IsFalse(kept.Saved); + Assert.AreEqual(1, kept.MissingValues); + Assert.AreSame(complete, store.Read(), "the saved session stays as it was"); + StringAssert.Contains(log[^1], "resta la copia completa salvata prima"); + StringAssert.Contains(log[^1], "manca lsd, che serve alle operazioni configurate"); + + // A complete new copy always replaces it. + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status); + Assert.AreNotSame(complete, store.Read()); + complete = store.Read(); + + // With «sostituisci» the incomplete copy replaces the complete one, as in S4. + choice = IncompleteCopyChoice.Replace; + Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status); + Assert.AreNotSame(complete, store.Read()); + Assert.IsFalse(store.Read()!.Fields.ContainsKey("lsd"), "missing, never guessed"); + AssertNoSecret(string.Join("\n", log)); + } + + [TestMethod] + public async Task AChoiceThatCannotBeReadIsTheDefaultAndTheCopyGoesOn() + { + // The setting lives in the database: a failure there must not make «Ho finito» fail (the lease would stay held). + var log = new List(); + var store = new InMemorySiteSession(null); + await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), log.Add).CopyAsync(() => true, CancellationToken.None); + var complete = store.Read(); + Assert.IsNotNull(complete); + var lacking = PageValues(); + ((JsonObject)lacking["values"]!).Remove("lsd"); + var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: lacking), Plan, store, new VirtualClock(), log.Add) + { + IncompleteCopy = _ => throw new InvalidOperationException("prova: impostazione illeggibile"), + }; + + var outcome = await copier.CopyAsync(() => true, CancellationToken.None); + + Assert.AreEqual(SessionCopyStatus.Saved, outcome.Status, "«Sostituisci comunque», the default"); + Assert.AreNotSame(complete, store.Read()); + var text = string.Join("\n", log); + StringAssert.Contains(text, "Scelta per la copia incompleta non letta (InvalidOperationException)"); + Assert.DoesNotContain("impostazione illeggibile", text, "the kind of error only (rule 10)"); + AssertNoSecret(text); + } + + [TestMethod] + public async Task ThePageIsLookedAtLastAfterTheChoiceIsRead() + { + // Rule 7: nothing awaited between the last look at whose page it is and the decision on the saved session. Here + // the page goes back to the engine while the choice is read: the copy is thrown away, not kept nor saved. + var store = new InMemorySiteSession(null); + await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), _ => { }).CopyAsync(() => true, CancellationToken.None); + var complete = store.Read(); + var lacking = PageValues(); + ((JsonObject)lacking["values"]!).Remove("lsd"); + var lost = false; + var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: lacking), Plan, store, new VirtualClock(), _ => { }) + { + IncompleteCopy = _ => + { + lost = true; + return Task.FromResult(IncompleteCopyChoice.KeepComplete); + }, + }; + + var outcome = await copier.CopyAsync(() => !lost, CancellationToken.None); + + Assert.IsTrue(lost, "the choice was read"); + Assert.AreEqual(SessionCopyStatus.Discarded, outcome.Status); + Assert.AreSame(complete, store.Read()); + } + + [TestMethod] + public async Task TheReportCountsAndNamesWhatTheSavedSessionHoldsAndNeverAValue() + { + var store = new InMemorySiteSession(null); + var clock = new VirtualClock(); + var page = PageValues(); + ((JsonObject)page["values"]!).Remove("hsi"); + ((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery"); + var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, store, clock, _ => { }); + + var none = copier.Report(); + Assert.AreEqual(SavedSessionState.None, none.State); + Assert.AreEqual(SavedSessionState.None, copier.SavedState); + Assert.IsFalse(none.Complete); + Assert.IsNull(none.CopiedAt); + Assert.AreEqual(Plan.Values.Count, none.ValuesExpected); + Assert.AreEqual(0, none.ValuesPresent); + + await copier.CopyAsync(() => true, CancellationToken.None); + var report = copier.Report(); + Assert.AreEqual(SavedSessionState.Present, report.State); + Assert.AreEqual(SavedSessionState.Present, copier.SavedState); + Assert.AreEqual(clock.Now, report.CopiedAt); + Assert.AreEqual(3, report.Cookies); + Assert.AreEqual(Plan.Values.Count - 1, report.ValuesPresent); + Assert.AreEqual(14, report.ValuesExpected, "the page values of the test catalog, spin_r, spin_b and spin_t among them"); + CollectionAssert.AreEqual(new[] { "hsi" }, report.MissingValues.ToArray()); + Assert.AreEqual(0, report.DocIdsPresent); + CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, report.MissingDocIds.ToArray()); + Assert.AreEqual(2, report.NeededMissing, "the configured GraphQL query sends both"); + Assert.IsFalse(report.Complete); + AssertNoSecret(report.ToString()); + AssertNoSecret(string.Join(",", report.MissingValues.Concat(report.MissingDocIds))); + } + + [TestMethod] + public async Task TheSpinValuesAreCopiedFromTheirModuleLikeTheOtherValuesOfThePage() + { + // Decision of 18 November 2026: __spin_r, __spin_b, __spin_t are a snapshot of the page at «Ho finito». + var store = new InMemorySiteSession(null); + await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), _ => { }).CopyAsync(() => true, CancellationToken.None); + var saved = store.Read()!; + Assert.AreEqual("1001", saved.Fields["spin_r"]); + Assert.AreEqual("ramo", saved.Fields["spin_b"]); + Assert.AreEqual("1700000000", saved.Fields["spin_t"]); + var script = SessionCaptureScript.Build(Plan); + StringAssert.Contains(script, "read(\"GiroProva\", \"revisione\")"); + StringAssert.Contains(script, "read(\"GiroProva\", \"tempo\")"); + Assert.DoesNotContain("SiteData", script, "the test site's own module names, never Instagram's"); + } + [TestMethod] [Timeout(20_000, CooperativeCancellation = true)] public async Task ABrowserThatDoesNotAnswerIsABrowserErrorAfterTheTimeout() @@ -382,6 +530,9 @@ public sealed class SessionCaptureTests ["comet_req"] = "7", ["ccg"] = "BUONA", ["entry_nonce"] = "nonce-segreto", + ["spin_r"] = "1001", + ["spin_b"] = "ramo", + ["spin_t"] = "1700000000", ["estraneo"] = "non chiesto", }, ["docIds"] = new JsonObject { ["ProvaProfiloQuery"] = "9000000000000009", ["AltraQuery"] = "1" }, diff --git a/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs b/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs index b99f8b0..37f45d3 100644 --- a/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs +++ b/tests/Febe.Tests/Collection/HttpSiteRequesterShapeTests.cs @@ -65,7 +65,8 @@ public sealed class HttpSiteRequesterShapeTests Assert.AreEqual(TestSite.ProfileQuery, request.Header("x-fb-friendly-name")); Assert.AreEqual("0", request.Header("x-ig-www-claim")); Assert.AreEqual( - "av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova&dpr=1" + "av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova" + + "&__spin_r=1001&__spin_b=ramo-di-prova&__spin_t=1700000000&dpr=1" + "&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery" + "&variables=%7B%22username%22%3A%22marta.prova%22%2C%22scheda%22%3A%22post%22%2C%22primi%22%3A12%2C%22raccolte%22%3Atrue%7D" + "&doc_id=8000000000000001", @@ -360,6 +361,9 @@ public sealed class HttpSiteRequesterShapeTests [DataRow("ccg", "__ccg")] [DataRow("comet_req", "__comet_req")] [DataRow("entry_nonce", "x-fb-entry-nonce")] + [DataRow("spin_r", "__spin_r")] + [DataRow("spin_b", "__spin_b")] + [DataRow("spin_t", "__spin_t")] public async Task AVersionFieldTheSessionLacksStopsTheQueryBeforeItLeaves(string field, string missing) { using var listener = new OneShotListener("""{"profilo":{}}"""); diff --git a/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs b/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs index 1e448b5..632d307 100644 --- a/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs +++ b/tests/Febe.Tests/Collection/HttpSiteRequesterTests.cs @@ -452,7 +452,7 @@ public sealed class HttpSiteRequesterTests var secrets = new List { Csrf, OtherCookie, SiteControl.InitialSession, "rinnovata-1", "claim-prova-1", TestSite.AppId, TestSite.Lsd, TestSite.Dtsg, AccountId, - TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce, + TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce, TestSite.SpinBranch, TestSite.DocIds[TestSite.ProfileQuery], UserAgent, "Mozilla", "marta.prova", "luca.prova", "c12", "127.0.0.1", "scheda", "primi", "accesso", "next", }; secrets.AddRange(cases.Values.SelectMany(c => c.Values.Values)); @@ -574,6 +574,9 @@ public sealed class HttpSiteRequesterTests ["comet_req"] = TestSite.CometReq, ["ccg"] = TestSite.ConnectionClass, ["entry_nonce"] = TestSite.EntryNonce, + ["spin_r"] = TestSite.SpinRevision, + ["spin_b"] = TestSite.SpinBranch, + ["spin_t"] = TestSite.SpinTime, }; /// A site client for the test site with its session, clock and log. diff --git a/tests/Febe.Tests/Collection/RequestCatalogTests.cs b/tests/Febe.Tests/Collection/RequestCatalogTests.cs index 99e082c..f30f09b 100644 --- a/tests/Febe.Tests/Collection/RequestCatalogTests.cs +++ b/tests/Febe.Tests/Collection/RequestCatalogTests.cs @@ -345,6 +345,9 @@ public sealed partial class RequestCatalogTests Assert.AreEqual(new PageValueSource("SiteData", "comet_env"), instagram.Values["comet_req"]); Assert.AreEqual(new PageValueSource("WebConnectionClassServerGuess", "connectionClass"), instagram.Values["ccg"]); Assert.AreEqual(new PageValueSource("BootloaderConfig", "nonce"), instagram.Values["entry_nonce"]); + Assert.AreEqual(new PageValueSource("SiteData", "__spin_r"), instagram.Values["spin_r"]); + Assert.AreEqual(new PageValueSource("SiteData", "__spin_b"), instagram.Values["spin_b"]); + Assert.AreEqual(new PageValueSource("SiteData", "__spin_t"), instagram.Values["spin_t"]); CollectionAssert.AreEquivalent(SiteSessionValues.PageFields.ToArray(), instagram.Values.Keys.ToArray(), "A place for every page value."); // The test site has its own module names, never Instagram's. @@ -376,9 +379,10 @@ public sealed partial class RequestCatalogTests Assert.AreEqual(new ValueSource(ValueSourceKind.Session, "entry_nonce"), operation.Headers["x-fb-entry-nonce"], operation.Name); Assert.AreEqual(new ValueSource(ValueSourceKind.Constant, "359341"), operation.Headers["x-asbd-id"], "The BDHeaderConfig property is not established."); - foreach (var spin in new[] { "__spin_r", "__spin_b", "__spin_t" }) + // A snapshot of the page at «Ho finito» (decision of 18 November 2026); the operations stay not configured anyway. + foreach (var spin in new[] { "spin_r", "spin_b", "spin_t" }) { - Assert.AreEqual(ValueSourceKind.Pending, operation.Body[spin].Kind, $"{operation.Name} {spin}: who adds it to the request is not shown."); + Assert.AreEqual(new ValueSource(ValueSourceKind.Session, spin), operation.Body["__" + spin], $"{operation.Name} __{spin}"); } } } @@ -387,17 +391,18 @@ public sealed partial class RequestCatalogTests public void EveryPendingLeftIsARuntimeValueABrowserHeaderOrARemovedName() { // A closed list: what the page computes while it runs (__req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, - // __d, __spin_*, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points) + // __d, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points) // and the names the probe removed. Nothing else may stay pending without a decision. var allowed = new HashSet(StringComparer.Ordinal) { - "__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d", "__spin_r", "__spin_b", "__spin_t", + "__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d", "x-web-session-id", "referer", "priority", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "x-ig-max-touch-points", "fb_api_analytics_tags", "qpl_active_flow_ids", RequestCatalog.RemovedName, }; var pending = RequestCatalog.LoadInstagram().Operations.SelectMany(o => o.PendingValues).Distinct(StringComparer.Ordinal).ToList(); CollectionAssert.AreEqual(Array.Empty(), pending.Where(p => !allowed.Contains(p)).ToArray()); Assert.IsFalse(pending.Contains("__rev") || pending.Contains("x-fb-entry-nonce"), "Settled in S4."); + Assert.IsFalse(pending.Contains("__spin_r") || pending.Contains("__spin_b") || pending.Contains("__spin_t"), "Settled in S4b."); Assert.AreEqual(0, RequestCatalog.LoadTestSite().Operations.Sum(o => o.PendingValues.Count)); } @@ -471,7 +476,7 @@ public sealed partial class RequestCatalogTests [TestMethod] public void TheNewSessionFieldsAreAcceptedAndUnknownOnesStillRefused() { - foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce" }) + foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" }) { var operation = Rest("post2", "/dati/post/{code}"); operation["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-prova"] = "session:" + field }; @@ -480,7 +485,7 @@ public sealed partial class RequestCatalogTests Assert.AreEqual(new ValueSource(ValueSourceKind.Session, field), Get(RequestCatalog.Parse(Alone(operation), "richieste.prova.json"), "post2").Headers["x-prova"]); } - foreach (var field in new[] { "password", "spin_r", "cookie", "sessionid" }) + foreach (var field in new[] { "password", "spin", "cookie", "sessionid" }) { var operation = Rest("post2", "/dati/post/{code}"); operation["headers"] = new JsonObject { ["x-prova"] = "session:" + field }; diff --git a/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs b/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs index 401d5af..c7d0bb7 100644 --- a/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs +++ b/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs @@ -91,6 +91,9 @@ public sealed class SessionCaptureIntegrationTests Assert.IsTrue(apiCookie.HostOnly); Assert.AreEqual(TestSite.Lsd, values.Fields["lsd"]); Assert.AreEqual(TestSite.Dpr, values.Fields["dpr"], "a number of the page as text"); + Assert.AreEqual(TestSite.SpinRevision, values.Fields["spin_r"], "S4b: __spin_r from the page, a number as text"); + Assert.AreEqual(TestSite.SpinBranch, values.Fields["spin_b"]); + Assert.AreEqual(TestSite.SpinTime, values.Fields["spin_t"]); Assert.AreEqual(TestSite.DocIds[TestSite.ProfileQuery], values.DocIds[TestSite.ProfileQuery]); lock (site.World.Gate) { diff --git a/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs b/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs index 34f1be8..c5071e4 100644 --- a/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs +++ b/tests/Febe.Tests/Collection/SiteAnswerSignalsTests.cs @@ -405,14 +405,14 @@ public sealed class SiteSessionTests [TestMethod] public void TheNewPageFieldsAreSessionFieldsAndTheVocabularyIsClosed() { - foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "lsd", "fb_dtsg", "app_id", "account_id" }) + foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t", "lsd", "fb_dtsg", "app_id", "account_id" }) { Assert.IsTrue(SiteSessionValues.PageFields.Contains(field), field); Assert.IsTrue(ValueSource.SessionFields.Contains(field), field); } CollectionAssert.AreEquivalent(new[] { "user_agent", "claim", "doc_id" }, ValueSource.SessionFields.Except(SiteSessionValues.PageFields).ToArray()); - Assert.IsFalse(ValueSource.SessionFields.Contains("spin_r"), "__spin_* stay pending: who adds them to the request is not shown."); + Assert.IsFalse(ValueSource.SessionFields.Contains("spin"), "The vocabulary is closed."); } private static SiteCookie Cookie(string name, string value, DateTimeOffset? expires = null) => diff --git a/tests/Febe.Tests/Collection/TestSiteSessionTests.cs b/tests/Febe.Tests/Collection/TestSiteSessionTests.cs index a10b626..c320bf8 100644 --- a/tests/Febe.Tests/Collection/TestSiteSessionTests.cs +++ b/tests/Febe.Tests/Collection/TestSiteSessionTests.cs @@ -111,7 +111,7 @@ public sealed class TestSiteSessionTests } Assert.AreEqual(200, await StatusWith("rev", TestSite.Revision), "the right values pass"); - foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce" }) + foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" }) { Assert.AreEqual(400, await StatusWith(field, "altro-valore"), field); } diff --git a/tests/Febe.Tests/Desktop/IconTests.cs b/tests/Febe.Tests/Desktop/IconTests.cs index 48870b4..9082e1a 100644 --- a/tests/Febe.Tests/Desktop/IconTests.cs +++ b/tests/Febe.Tests/Desktop/IconTests.cs @@ -1,12 +1,12 @@ using System.Buffers.Binary; +using Febe.Core.Codecs.Images; using Febe.Desktop.Core; using Febe.Tests.Desktop.Support; -using SkiaSharp; namespace Febe.Tests.Desktop; /// -/// 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 src/Febe.Desktop/Febe.ico must be /// what the code draws: FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests writes it again. /// @@ -53,28 +53,28 @@ public sealed class IconTests { using var image = IcoWriter.Decode(ico, entry); var s = entry.Size; - Assert.AreEqual(0, image.GetPixel(0, 0).Alpha, $"{s}: transparent corner"); - Assert.AreEqual(0, image.GetPixel(s - 1, s - 1).Alpha, $"{s}: transparent corner"); + Assert.AreEqual(0, image.GetPixel(0, 0).A, $"{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. var accent = image.GetPixel(Scale(4, s), Scale(28, s)); 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. var moon = image.GetPixel(Scale(23.2, s), Scale(8.8, s)); 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. var hole = image.GetPixel(Scale(14.5, s), Scale(17.5, s)); 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] public void TheWriterRefusesImagesThatAreNotSquareOrTooLarge() { - using var wide = new SKBitmap(32, 16); - using var huge = new SKBitmap(512, 512); + using var wide = new RgbaImage(32, 16); + using var huge = new RgbaImage(512, 512); Assert.ThrowsExactly(() => IcoWriter.Write([wide])); Assert.ThrowsExactly(() => IcoWriter.Write([huge])); Assert.ThrowsExactly(() => IcoWriter.Write([])); @@ -106,7 +106,7 @@ public sealed class IconTests var b = IcoWriter.ReadDirectory(fresh); 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++) { 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 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 - && Math.Abs(expected.Green - actual.Green) <= tolerance - && Math.Abs(expected.Blue - actual.Blue) <= tolerance - && Math.Abs(expected.Alpha - actual.Alpha) <= tolerance; + var ok = Math.Abs(expected.R - actual.R) <= tolerance + && Math.Abs(expected.G - actual.G) <= tolerance + && Math.Abs(expected.B - actual.B) <= tolerance + && Math.Abs(expected.A - actual.A) <= tolerance; Assert.IsTrue(ok, $"{what}: atteso {expected}, trovato {actual}"); } } diff --git a/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs b/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs index b5eaa5b..8e53aa5 100644 --- a/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs +++ b/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs @@ -109,7 +109,7 @@ public sealed class SavedSessionConnectionTests [TestMethod] [Timeout(60_000, CooperativeCancellation = true)] - public async Task ALateHoFinitoAfterTheLeaseEndedDoesNotCopy() + public async Task ALateHoFinitoAfterTheLeaseEndedReadsNothingAndSaysTheSessionWasAlreadyCopied() { var ct = TestContext.CancellationToken; await using var bed = await StartAsync(); @@ -118,17 +118,38 @@ public sealed class SavedSessionConnectionTests await BeginAsync(bed); browser.FakeCdp.LoggedIn = true; - - // He closes the window without «Ho finito»: the lease ends by itself, the page is the engine's again. - await browser.HideFromUserAsync(ct); - await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida"); browser.FakeCdp.Navigated(Site + "/"); + // He puts the window away without «Ho finito»: the lease ends by itself, after the copy of S4b (its page is still + // his until then), and the page is the engine's again. + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida"); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied once, before the lease ended"); + var copied = bed.App.SavedSession!.Read(); + Assert.IsNotNull(copied); + + // «Ho finito» pressed late: nothing is read from a page that is not his, and he is not asked to log in again + // for a session copied a moment before. var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); Assert.IsTrue(finish.GetProperty("connected").GetBoolean()); + var message = finish.GetProperty("message").GetString()!; + StringAssert.Contains(message, "era già stata copiata quando il browser è tornato al motore"); + StringAssert.Contains(message, "Non serve rifare l'accesso"); + Assert.DoesNotContain("non è stata copiata", message); + Assert.DoesNotContain("Rifai l'accesso", message); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his"); + Assert.AreSame(copied, bed.App.SavedSession.Read()); + + // A new use of the browser whose end copies nothing (the login page): a late «Ho finito» now says that this time + // the session was not copied, even if an earlier use had copied it. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated(Site + "/accesso/"); + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida sulla pagina di accesso"); + finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); StringAssert.Contains(finish.GetProperty("message").GetString(), "non è stata copiata"); - Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his"); - Assert.IsNull(bed.App.SavedSession!.Read()); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + Assert.AreSame(copied, bed.App.SavedSession.Read()); } [TestMethod] diff --git a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs new file mode 100644 index 0000000..1f5b879 --- /dev/null +++ b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs @@ -0,0 +1,601 @@ +using System.Net; +using Febe.App; +using Febe.Core.Collection.Requests; +using Febe.Tests.Desktop.Support; +using Febe.Web.Connection; + +namespace Febe.Tests.Desktop; + +/// +/// Stage S4b of issue #36 (answers of Alberto of 18 November 2026) in the shared composition, with a fake browser and +/// the test site's catalog: the session is copied also when Alberto closes the browser window and when his driving +/// lease ends by itself — only from a page of the site, before the page goes back to the engine (rule 7) —; with the +/// raccolta «richieste» «Collegato» needs a readable saved session («Serve «Ho finito»» otherwise, the engine waits); +/// an incomplete copy can keep the complete one; the Collegamento page gets counts and names, never values. Never +/// Instagram. +/// +[TestClass] +public sealed class SessionCopyOnLetGoTests +{ + private const string Site = "http://127.0.0.1:8481"; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ClosingTheWindowCopiesTheSessionBeforeThePageGoesBackToTheEngine() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // «Apri il browser»: only the window holds the engine still (no lease of «Accedi»). + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + bool? drivingWhileCopying = null; + bool? sessionWhileCopying = null; + browser.FakeCdp.OnCapture = () => + { + drivingWhileCopying = browser.UserIsDriving; + sessionWhileCopying = bed.App.Engine!.Services.Runtime.CurrentSession is not null; + }; + + await browser.CloseWindowAsync(ct); + + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read"); + Assert.IsFalse(sessionWhileCopying, "no engine session runs meanwhile"); + Assert.IsFalse(browser.UserIsDriving, "then it goes back to the engine"); + var saved = bed.App.SavedSession!.Read(); + Assert.IsNotNull(saved); + Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]); + Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ClosingTheWindowOffTheSiteOrWithoutASessionCopiesNothing() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // Another site's page: the copier refuses before reading the modules. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated("https://altro.example.invalid/pagina"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + Assert.IsNull(bed.App.SavedSession!.Read()); + + // A page of the site without the session cookie: nothing to copy. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = false; + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + Assert.IsNull(bed.App.SavedSession.Read()); + Assert.IsFalse(browser.UserIsDriving); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheEndOfTheLeaseCopiesOnceAndNotAgainAfterTheWindowCopied() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.DrivingGrace = TimeSpan.FromMilliseconds(400); + + // «Usa il browser», then the window is put away without «Ho finito»: the lease ends by itself after the copy. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida"); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied when the lease ended"); + Assert.IsNotNull(bed.App.SavedSession!.Read()); + + // «Usa il browser» again, the window closed (a copy), then the lease ends: no second copy for the same use. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated(Site + "/profilo/marta.prova/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the window's copy"); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la finestra"); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the end of the lease does not copy again"); + + // On the site's login page (a path of its stop rules) the end of the lease copies nothing: the copier refuses it. + var before = bed.App.SavedSession.Read(); + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated(Site + "/accesso/"); + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida sulla pagina di accesso"); + Assert.AreSame(before, bed.App.SavedSession.Read()); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "refused before the modules are read"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ALateHoFinitoFollowsTheLastLettingGoNotAnEarlierOne() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.DrivingGrace = TimeSpan.FromMilliseconds(400); + + // «Usa il browser», the window closed on the site's home: copied. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + + // Same use: the window back in front, then closed again on the login page (perhaps another account): refused. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.Navigated(Site + "/accesso/"); + await browser.CloseWindowAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida"); + + // A late «Ho finito» must not say that the session was already copied: the last letting go copied nothing. + var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + var message = finish.GetProperty("message").GetString()!; + StringAssert.Contains(message, "non è stata copiata"); + Assert.DoesNotContain("era già stata copiata", message); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ALeaseThatCameBackDuringTheCopyIsNotEndedAfterIt() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.DrivingGrace = TimeSpan.FromMilliseconds(400); + + // «Usa il browser», the window put away: the end of the lease copies. While it copies, the remote view (or the + // window) comes back. + IDisposable? back = null; + browser.FakeCdp.OnCapture = () => back ??= browser.UserDriving.Begin(); + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Fine della guida del browser: sessione copiata", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la copia alla fine della guida"); + Assert.IsNotNull(back); + + // Time enough for the look after the copy: the lease of «Usa il browser» must still be there, beside the view's. + await Task.Delay(TimeSpan.FromMilliseconds(300), ct); + Assert.AreEqual(2, browser.UserDriving.Leases, "the lease of «Usa il browser» goes on while the view is back"); + + // The view goes away again: a new letting go, a new copy, and only then the lease ends. + browser.FakeCdp.OnCapture = null; + back.Dispose(); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la vista"); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the second letting go copies again"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task AHoFinitoAfterARefusedHoFinitoDoesNotReportTheCopyOfAnEarlierLettingGo() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // «Usa il browser», the window closed on the site's home: copied, while the lease of «Usa il browser» holds. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + Assert.IsTrue(browser.UserIsDriving, "the lease of «Usa il browser» is still there"); + + // The window back, another login ending on the login page: «Ho finito» copies again and is refused. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.Navigated(Site + "/accesso/"); + var first = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!; + StringAssert.Contains(first, "non è stata copiata"); + + // A second «Ho finito» (a double click, another tab) must not say the session was already copied. + var second = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!; + Assert.DoesNotContain("era già stata copiata", second); + Assert.DoesNotContain("Non serve rifare l'accesso", second); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task WhenTheTimeRunsOutWaitingForThePageTheLogSaysThePageWasBusy() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.LetGoWait = TimeSpan.FromMilliseconds(500); + connection.PageTurnWait = TimeSpan.FromSeconds(30); + + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + + // A step of the profile search holds the page for longer than the window may wait. + using (await bed.App.Engine!.Services.PageTurns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct)) + { + await browser.CloseWindowAsync(ct); + } + + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + Assert.IsFalse(browser.UserIsDriving); + var log = ReadLog(bed); + StringAssert.Contains(log, "Finestra del browser chiusa: sessione non copiata, la pagina era occupata dalla ricerca dei profili."); + Assert.DoesNotContain("il browser non ha risposto in tempo", log, "the browser was not the cause"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task AnErrorDuringTheCopyWhenAlbertoLetsGoStillGivesThePageBackToTheEngine() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.DrivingGrace = TimeSpan.FromMilliseconds(300); + + // An error nobody expects in the middle of the copy (the database busy, say): the end of the lease must still + // come, or the engine would stay in «Stai usando il browser» for ever. + browser.FakeCdp.OnCapture = () => throw new Microsoft.Data.Sqlite.SqliteException("prova: database occupato", 5); + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.HideFromUserAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo un errore della copia"); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + Assert.IsNull(bed.App.SavedSession!.Read()); + await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("il motore può riprendere", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la riga della fine della guida"); + var log = ReadLog(bed); + StringAssert.Contains(log, "Fine della guida del browser: copia della sessione non riuscita per un errore (SqliteException)."); + Assert.DoesNotContain("database occupato", log, "the kind of error only (rule 10)"); + + // The same error when the window is closed: the page goes back all the same. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(2, browser.FakeCdp.CaptureReads); + Assert.IsFalse(browser.UserIsDriving); + StringAssert.Contains(ReadLog(bed), "Finestra del browser chiusa: copia della sessione non riuscita per un errore (SqliteException)."); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheLogSaysWhetherTheWindowWasClosedOrLeftMinimisedTooLong() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct, Febe.App.BrowserWindowLetGo.MinimizedTooLong); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + var log = ReadLog(bed); + StringAssert.Contains(log, "Finestra del browser ridotta a icona troppo a lungo: sessione copiata"); + Assert.DoesNotContain("Finestra del browser chiusa", log, "it was not closed"); + + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct); + StringAssert.Contains(ReadLog(bed), "Finestra del browser chiusa: sessione copiata"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task LeavingTheBrowserPageInDockerCopiesTheSessionOnceNoViewOpensAgain() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.PageLeaveGrace = TimeSpan.FromMilliseconds(400); + + // «Usa il browser» from the Browser page of Docker: no window, the remote view holds the engine still. + var view = await DockerBeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + bool? drivingWhileCopying = null; + browser.FakeCdp.OnCapture = () => drivingWhileCopying = browser.UserIsDriving; + + // The page says it is left; while its view (or another tab's) is still open nothing happens. + await connection.LeavePageAsync(ct); + await Task.Delay(TimeSpan.FromMilliseconds(900), ct); + Assert.IsTrue(browser.UserIsDriving, "a view is still open"); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + + // Its view closes with it and no other opens: the copy while the page is still his, then it goes back to the engine. + view.Dispose(); + connection.RemoteViewClosed(); + await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: nessuna vista del browser riaperta, il motore può riprendere.", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina"); + Assert.IsFalse(browser.UserIsDriving); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read"); + Assert.IsNotNull(bed.App.SavedSession!.Read()); + StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione copiata"); + + // A late «Ho finito» from another tab reads nothing and says that the session was already copied. + var finish = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!; + StringAssert.Contains(finish, "era già stata copiata"); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task AReloadOfTheBrowserPageIsNotLeavingItAndAnnullaStillCopiesNothing() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.PageLeaveGrace = TimeSpan.FromSeconds(1); + var view = await DockerBeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + + // A reload: the old page says it left and its view closes, the new page takes the browser and opens its view. + await connection.LeavePageAsync(ct); + view.Dispose(); + connection.RemoteViewClosed(); + view = await DockerBeginAsync(bed); + await Task.Delay(TimeSpan.FromSeconds(2), ct); + Assert.IsTrue(browser.UserIsDriving, "a reload is not leaving the browser"); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + + // «Annulla» on the reloaded page: the browser goes back to rest, nothing is copied. + view.Dispose(); + using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel")) + { + Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode); + } + + Assert.IsFalse(browser.UserIsDriving); + await Task.Delay(TimeSpan.FromSeconds(1.5), ct); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "«Annulla» never copies"); + Assert.IsNull(bed.App.SavedSession!.Read()); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task LeavingTheBrowserPageOnTheLoginPageCopiesNothingButGivesThePageBack() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300); + var view = await DockerBeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/accesso/"); + + // The tab closed on the site's login page (a path of its stop rules): the copier refuses it. + view.Dispose(); + connection.RemoteViewClosed(); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina di accesso"); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "refused before the modules are read"); + Assert.IsNull(bed.App.SavedSession!.Read()); + await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: sessione non copiata", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la riga della copia rifiutata"); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task WithRichiesteCollegatoNeedsTheSavedSessionAndTheEngineWaitsForIt() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // The session in the browser, but «Annulla» instead of «Ho finito»: no copy. + await BeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel")) + { + Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode); + } + + // As the background look would see it a moment later. + await connection.RefreshAsync(ct); + var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("copyMissing", status.GetProperty("state").GetString()); + var saved = status.GetProperty("savedSession"); + Assert.AreEqual("none", saved.GetProperty("state").GetString()); + Assert.IsTrue(connection.IsConnected); + Assert.IsTrue(connection.SessionCopyMissing); + Assert.IsFalse(connection.IsReadyToCollect, "the engine waits"); + Assert.IsFalse(bed.App.Engine!.Services.Runtime.IsConnected); + Assert.IsTrue(bed.App.Engine.Services.Runtime.SessionCopyMissing); + StringAssert.Contains(ReadLog(bed), "Motore avviato: aspetta il collegamento", "at start-up nothing was connected"); + StringAssert.Contains(FebeApp.StartedMessage(connection), "aspetta la copia della sessione", "the start-up line says what the engine waits for"); + var engine = await bed.JsonAsync(HttpMethod.Get, "/api/engine"); + Assert.AreEqual("copyMissing", engine.GetProperty("connection").GetProperty("state").GetString()); + Assert.AreEqual("Serve «Ho finito»", engine.GetProperty("snapshot").GetProperty("headline").GetString()); + + // «Ho finito»: «Collegato», with counts and names of the copy and never a value. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated(Site + "/"); + await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + using (var answer = await bed.SendAsync(HttpMethod.Get, "/api/connection")) + { + var text = await answer.Content.ReadAsStringAsync(ct); + foreach (var secret in new[] { Febe.SitoDiProva.TestSite.Lsd, Febe.SitoDiProva.TestSite.Dtsg, Febe.SitoDiProva.TestSite.EntryNonce, Febe.SitoDiProva.TestSite.SpinBranch, "sessione-di-prova", "csrf-di-prova", "Finestra di prova" }) + { + Assert.DoesNotContain(secret, text, "counts and names only"); + } + } + + status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("connected", status.GetProperty("state").GetString()); + saved = status.GetProperty("savedSession"); + Assert.AreEqual("present", saved.GetProperty("state").GetString()); + Assert.IsTrue(saved.GetProperty("copiedAt").GetInt64() > 0); + Assert.AreEqual(saved.GetProperty("valuesExpected").GetInt32(), saved.GetProperty("valuesPresent").GetInt32()); + Assert.AreEqual(0, saved.GetProperty("missingValues").GetArrayLength()); + Assert.AreEqual(0, saved.GetProperty("neededMissing").GetInt32()); + Assert.IsTrue(connection.IsReadyToCollect); + Assert.AreEqual("Motore avviato: il browser è collegato.", FebeApp.StartedMessage(connection)); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task WithPagineCollegatoIsTheCookieAloneAndNoSavedSessionIsShown() + { + var ct = TestContext.CancellationToken; + await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]); + await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct); + await BeginAsync(bed); + bed.Browser!.FakeCdp.LoggedIn = true; + await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("connected", status.GetProperty("state").GetString()); + Assert.IsTrue(status.TryGetProperty("savedSession", out var saved) is false || saved.ValueKind == System.Text.Json.JsonValueKind.Null); + Assert.IsFalse(bed.App.Connection!.SessionCopyMissing); + Assert.AreEqual(0, bed.Browser.FakeCdp.CaptureReads); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheIncompleteCopySettingIsStoredAndHeldByTheNextHoFinito() + { + await using var bed = await StartAsync(); + var browser = bed.Browser!; + + // The default: «sostituisci»; an unknown choice is refused. + Assert.AreEqual(SessionCopySettings.ReplaceText, (await bed.JsonAsync(HttpMethod.Get, "/api/connection/settings")).GetProperty("incompleteCopy").GetString()); + using (var wrong = await bed.SendAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"forse"}""")) + { + Assert.AreEqual(HttpStatusCode.BadRequest, wrong.StatusCode); + } + + var keep = await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"tieni-completa"}"""); + Assert.AreEqual(SessionCopySettings.KeepCompleteText, keep.GetProperty("incompleteCopy").GetString()); + Assert.AreEqual(SessionCopySettings.KeepCompleteText, await bed.App.Database.Settings.GetAsync(SessionCopySettings.IncompleteCopyKey)); + + // A complete copy, then one from a page without the nonce: the complete one stays and «Ho finito» says so. + await FinishOnSiteAsync(bed, openLogin: true); + var complete = bed.App.SavedSession!.Read()!; + var page = FakeCdp.DefaultPageCapture(); + ((System.Text.Json.Nodes.JsonObject)page["values"]!).Remove("entry_nonce"); + browser.FakeCdp.PageCapture = page; + var message = await FinishOnSiteAsync(bed, openLogin: false); + StringAssert.Contains(message, "Febe tiene la copia completa salvata prima"); + StringAssert.Contains(message, "«Sostituisci comunque»"); + Assert.AreSame(complete, bed.App.SavedSession.Read()); + + // «Sostituisci comunque»: the next incomplete copy replaces it, as in S4. + await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"sostituisci"}"""); + message = await FinishOnSiteAsync(bed, openLogin: false); + StringAssert.Contains(message, "ha comunque sostituito quella salvata"); + Assert.IsFalse(bed.App.SavedSession.Read()!.Fields.ContainsKey("entry_nonce")); + var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection"); + Assert.AreEqual("connected", status.GetProperty("state").GetString(), "an incomplete copy is still a readable session"); + var saved = status.GetProperty("savedSession"); + Assert.AreEqual("entry_nonce", saved.GetProperty("missingValues")[0].GetString()); + Assert.AreEqual(1, saved.GetProperty("neededMissing").GetInt32()); + } + + [TestMethod] + public void TheMessagesOfTheNewOutcomesSayWhatHappened() + { + var kept = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0)); + StringAssert.Contains(kept, "Alla pagina mancava 1 valore che serve alle richieste"); + StringAssert.Contains(kept, "tiene la copia completa salvata prima"); + StringAssert.Contains(kept, "Riapri il browser dalla pagina Collegamento"); + + Assert.AreEqual("sessione copiata", BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 0))); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 2, 0)), "mancano 2 valori"); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0)), "(1 valore mancante), resta quella completa"); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 2, 1)), "(3 valori mancanti)"); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 1)), ", ma manca 1 valore che serve alle richieste"); + StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Refused, Febe.Browser.Session.CaptureRefusal.CheckpointPage, 0, 0, 0)), "pagina di accesso o di verifica"); + + // A late «Ho finito» after the copy made when the browser went back to the engine. + var before = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 0), earlier: true); + StringAssert.Contains(before, "era già stata copiata quando il browser è tornato al motore"); + StringAssert.Contains(before, "Non serve rifare l'accesso"); + Assert.DoesNotContain("non è stata copiata", before); + var beforeIncomplete = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 2, 0), earlier: true); + StringAssert.Contains(beforeIncomplete, "era già stata copiata"); + StringAssert.Contains(beforeIncomplete, "mancavano 2 valori"); + Assert.DoesNotContain("Non serve rifare l'accesso", beforeIncomplete); + StringAssert.Contains(BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.SavedInMemoryOnly, null, 3, 0, 0), earlier: true), "non ancora scritta su disco"); + StringAssert.Contains(BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0), earlier: true), "Quando il browser è tornato al motore alla pagina mancava 1 valore che serve"); + + // Italian singular and plural (never «1 valori»). + var one = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 0)); + StringAssert.Contains(one, "Alla pagina però mancava 1 valore che serve alle richieste"); + StringAssert.Contains(one, "le richieste che lo usano non partono"); + var two = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 1)); + StringAssert.Contains(two, "Alla pagina però mancavano 2 valori che servono alle richieste"); + StringAssert.Contains(two, "le richieste che li usano non partono"); + foreach (var text in new[] { kept, one, two, before, beforeIncomplete, BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 0)) }) + { + Assert.DoesNotContain("1 valori", text); + } + } + + /// The log files of this start, read while Febe still writes them. + private static string ReadLog(DesktopTestBed bed) + { + var folder = bed.App.Log.Folder; + Assert.IsNotNull(folder, "the log has a folder"); + var text = new System.Text.StringBuilder(); + foreach (var file in Directory.GetFiles(folder)) + { + using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var reader = new StreamReader(stream); + text.Append(reader.ReadToEnd()); + } + + return text.ToString(); + } + + private async Task StartAsync() + { + var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--raccolta", "richieste"]); + await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), TestContext.CancellationToken); + return bed; + } + + private static async Task BeginAsync(DesktopTestBed bed, bool openLogin = true) + { + using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}"""); + Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode); + } + + /// + /// «Usa il browser» as the Browser page of Docker takes it: the lease of the connection and the lease of its remote + /// view (returned), without the window of this composition (put away at once). + /// + private async Task DockerBeginAsync(DesktopTestBed bed) + { + await BeginAsync(bed, openLogin: false); + await bed.Browser!.HideFromUserAsync(TestContext.CancellationToken); + return bed.Browser.UserDriving.Begin(); + } + + /// «Accedi» or «Usa il browser», the site's home with the session, «Ho finito». Returns the message. + private static async Task FinishOnSiteAsync(DesktopTestBed bed, bool openLogin) + { + await BeginAsync(bed, openLogin); + bed.Browser!.FakeCdp.LoggedIn = true; + bed.Browser.FakeCdp.Navigated(Site + "/"); + var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString()); + return finish.GetProperty("message").GetString()!; + } +} diff --git a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs index 181ec77..f4fca2c 100644 --- a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs +++ b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs @@ -196,6 +196,34 @@ internal sealed class FakeBrowser : IFebeBrowser return Task.CompletedTask; } + /// + /// Like Alberto closing the real window «Browser di Febe» (WebView2Host.Done, issue #36, S4b): out of view at once, + /// the copy of the session before the page goes back to the engine (a hold keeps it his meanwhile), then the lease ends. + /// : closed, or left minimised too long. + /// + public async Task CloseWindowAsync(CancellationToken ct, BrowserWindowLetGo how = BrowserWindowLetGo.Closed) + { + Hidden++; + if (_lease is null || _context.CopyOnWindowClosed is not { } copy) + { + _lease?.Dispose(); + _lease = null; + return; + } + + var hold = UserDriving.Begin(); + _lease.Dispose(); + _lease = null; + try + { + await copy(how, ct); + } + finally + { + hold.Dispose(); + } + } + /// The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile. public bool ProfileLocked { get; set; } @@ -244,6 +272,9 @@ internal sealed class FakeCdp : ICdpSession /// public JsonObject? PageCapture { get; set; } = DefaultPageCapture(); + /// Called when the copy's evaluation is asked, before it answers (what the test wants to look at then). + public Action? OnCapture { get; set; } + /// How many times the copy's evaluation (the one that reads navigator.userAgent) was asked. public int CaptureReads => Volatile.Read(ref _captureReads); @@ -267,6 +298,9 @@ internal sealed class FakeCdp : ICdpSession ["comet_req"] = Febe.SitoDiProva.TestSite.CometReq, ["ccg"] = Febe.SitoDiProva.TestSite.ConnectionClass, ["entry_nonce"] = Febe.SitoDiProva.TestSite.EntryNonce, + ["spin_r"] = Febe.SitoDiProva.TestSite.SpinRevision, + ["spin_b"] = Febe.SitoDiProva.TestSite.SpinBranch, + ["spin_t"] = Febe.SitoDiProva.TestSite.SpinTime, }, ["docIds"] = new JsonObject { [Febe.SitoDiProva.TestSite.ProfileQuery] = Febe.SitoDiProva.TestSite.DocIds[Febe.SitoDiProva.TestSite.ProfileQuery] }, }; @@ -366,6 +400,7 @@ internal sealed class FakeCdp : ICdpSession private JsonObject Capture() { Interlocked.Increment(ref _captureReads); + OnCapture?.Invoke(); return PageCapture is { } page ? new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse(page.ToJsonString()) } } : new JsonObject(); diff --git a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs new file mode 100644 index 0000000..f1afa4b --- /dev/null +++ b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs @@ -0,0 +1,323 @@ +using System.Text.RegularExpressions; + +namespace Febe.Tests.Docs; + +/// +/// The documents agree with each other where a review of the 18 November 2026 changes found them apart: the rule on +/// external components allows only gitleaks, Trivy, Xvfb and the Debian packages Chromium needs, and every other +/// component the project still uses says in which stage of 0.3.0 it leaves; no hypothesis of spec §6.6 is called +/// verified without an outcome in docs/sonda/esito.md; the questions Alberto answered are not open any more; and the +/// paragraphs of §2, §3, §4.10, §6.0, §6.1, §6.6, §13.2, §14.1 and §15 that were contradictory or unbounded say what +/// settles them. Since 25 November 2026 also Alberto's answers of that day (the session copied when the browser page is +/// left in Docker, the fonts of the Docker image, damaged images refused without a perceptual hash, HEVC RExt kept) +/// and the features of issue #59 (download order, Dashboard, grouped or per-file mosaic, stage D1). +/// +[TestClass] +public sealed partial class SpecificationConsistencyTests +{ + /// Packages that rule 13 allows for good; any other one must say in which stage it leaves. + private static readonly string[] AllowedPackages = ["Microsoft.Data.Sqlite", "Microsoft.Web.WebView2", "MSTest"]; + + /// The only exceptions the rule allows besides .NET, Microsoft.Data.Sqlite, the browser and MSTest. + private static readonly string[] Exceptions = ["gitleaks e Trivy", "Xvfb", "pacchetti Debian che gli servono"]; + + /// + /// Components still in use that the rule must name, each with the stage of 0.3.0 it leaves with: the first stage + /// named after the last mention of the component. + /// + private static readonly (string Component, string Stage)[] Leaving = + [ + ("SkiaSharp", "C1"), ("ffmpeg", "C3"), ("NSIS", "C6"), ("Node", "C6"), ("Archivo", "C6"), ("Lucide", "C6"), + ]; + + /// Questions of spec §16 that Alberto answered, with the day of the answer: their row must say so. + private static readonly (string Number, string Day)[] AnsweredQuestions = + [ + ("13", "18 novembre 2026"), ("14", "18 novembre 2026"), ("15", "18 novembre 2026"), ("16", "18 novembre 2026"), + ("17", "18 novembre 2026"), ("18", "25 novembre 2026"), + ]; + + /// Phrases that called those answers still open; none may be left in the specification. + private static readonly string[] StaleProposals = + [ + "da confermare con alberto (§16, domande 15 e 16)", + "se alberto lo conferma", + "proposta da confermare con alberto, §16 domanda 14", + "oggi copia solo «ho finito»", + "oggi una copia incompleta sostituisce sempre", + "in docker ci sono solo il primo e l'ultimo", + "proposta da confermare con alberto all'inizio di c4", + "quattro voci (libreria, account, attività, importa)", + "la pagina attività", + "in attività", + "da attività", + "caratteri di sistema compresi quelli per le emoji", + ]; + + /// + /// (point, start of the line in docs/SPECIFICA.md, phrases that line must all contain). Phrases are compared like + /// : no case, no emphasis. + /// + public static IEnumerable SettledPoints => + [ + ["«Collegato» vuole la sessione salvata solo quando si costruisce", "**«Collegato», con «richieste»**", new[] { "almeno un'operazione configurata", "tappa s4b", "serve «ho finito»", "mai i valori" }], + ["la sessione si copia anche lasciando il browser, prima che la pagina torni al motore", "**Quando si copia**", new[] { "tappa s4b", "prima che la pagina torni al motore", "chiude la finestra «browser di febe»", "il permesso di guida finisce da solo", "la presa del permesso di guida e il turno della pagina", "10 secondi" }], + ["il permesso e il turno si tengono per tutta la copia, in ogni momento", "La copia si fa solo da una pagina del sito", new[] { "tiene il permesso e il turno della pagina per tutta la copia", "alla chiusura della finestra e alla fine del permesso", "«quando si copia»" }], + ["la copia incompleta segue l'opzione", "**Copia incompleta**", new[] { "`sessione.copia-incompleta`", "tappa s4b", "«sostituisci comunque»", "le richieste continuano a usarla" }], + ["il comando CDP della copia dice i tre momenti", "| Copiare la sessione", new[] { "a «ho finito»", "alla chiusura della finestra «browser di febe»", "alla fine del permesso di guida", "prima che la pagina torni al motore" }], + ["spin_r, spin_b e spin_t hanno un posto nella tabella dei valori", "| `spin_r`, `spin_b`, `spin_t` |", new[] { "`sitedata.__spin_r`", "h23" }], + ["spin_r, spin_b e spin_t non sono più pending", "- `__spin_r`, `__spin_b`, `__spin_t`", new[] { "non sono più `pending`", "h23" }], + ["H23 sta fra le ipotesi", "| H23 |", new[] { "sitedata", "da verificare da alberto", "graphql/query" }], + ["la regola 11 lascia alla pagina Collegamento solo data, conteggi e nomi", "11. **Segreti fuori dai registri", new[] { "la pagina collegamento ne mostra solo la data della copia, i conteggi e i nomi dei valori che mancano, mai un valore" }], + ["§13.2 lascia alla pagina Collegamento solo data, conteggi e nomi", "- La sessione di Instagram vive nel profilo", new[] { "solo la data della copia, i conteggi", "i nomi di quelli che mancano, mai un valore" }], + ["browser e client mai nello stesso momento", "**Niente browser e client insieme", new[] { "nello stesso momento", "una alla volta" }], + ["H21 e H22 restano da verificare", "- H21 (`require()`", new[] { "restano da verificare", "docs/sonda/esito.md" }], + ["lo stesso post in due account: «Una copia per account» è il predefinito", "- **Lo stesso post in due account**", new[] { "«una copia per account»", "predefinito", "«una copia sola»" }], + ["una copia ha l'account effettivo nella sua identità", "- Una riga per copia (`export_copy`)", new[] { "account effettivo" }], + ["lo stesso SHA-256 due volte nella cartella generale", "- **Una storia entrata in una raccolta in evidenza**", new[] { "per lo stesso account effettivo", "due volte nella cartella generale" }], + ["l'adozione non si fida della sola dimensione", "- **Adozione per percorso**", new[] { "rifà la conversione", "la sola dimensione non basta mai", "nome libero" }], + ["le immagini animate si copiano come originali", "| Foto |", new[] { "immagini animate", "`acTL`", "`anim`/`anmf`" }], + ["il file di prova delle cartelle rifiutate è un .part nella sola candidata", "- Cartelle rifiutate", new[] { "`.febe-prova-*.part`", "solo nella cartella candidata", "mai in dati, libreria, cartelle degli account o `/importa`" }], + ["i decodificatori dicono il loro sottoinsieme", "- decodificatori di immagini:", new[] { "rfc 6386", "codifica aritmetica", "precisione a 12 bit" }], + ["il decodificatore H.264 copre tutto lo standard", "- decodificatore H.264", new[] { "tutto lo standard", "extended", "high 10", "high 4:4:4", "piani di colore separati", "senza perdita", "monocromatico", "paff", "mbaff", "svc", "mvc", "cabac" }], + ["il decodificatore H.265 è dentro la 0.3.0 e tiene RExt", "- decodificatore H.265/HEVC", new[] { "tappa c4", "main 10", "domanda 18", "risposta di alberto del 25 novembre 2026", "estensioni di formato (rext)", "che restano", "fino a 12 bit", "fotogramma non disponibile per questo video" }], + ["VP9 e AV1 hanno la tessera neutra", "- VP9, AV1", new[] { "tessera neutra", "fotogramma non disponibile per questo video" }], + ["i lettori dei contenitori comprendono ASF, FLV e MPEG-PS", "- lettori dei contenitori ASF", new[] { "flv", "mpeg-ps", "13818-1", "durata, dimensioni, codec e data", "tappa c5" }], + ["l'installatore si scrive in casa", "- l'installatore di Windows", new[] { "al posto di nsis", "tappa c6" }], + ["la CI non vuole Node", "- i passi della CI", new[] { "node", "git", "curl verso l'api di gitea", "tappa c6" }], + ["le serie di conformità stanno nel repository con la loro fonte", "- Le serie di conformità ITU-T", new[] { "h.264.1", "h.265.1", "solo i flussi e l'md5 dell'uscita di riferimento", "`leggimi.md` che dice la fonte" }], + ["SkiaSharp esce anche dal disegno", "- ridimensionamento", new[] { "brandicon", "demoimages", "importpreview", "mediafactory", "librarytestsupport", "importtestfiles" }], + ["le prove dei codec con perdita hanno una tolleranza", "- **Codec e video**", new[] { "psnr", "esattamente per png" }], + ["C1 comprende disegno e tolleranze", "| **C1 Codec delle immagini** |", new[] { "disegnatore 2d", "tolleranze di §14.1" }], + ["C3 copre tutto H.264 e tutti i flussi", "| **C3 Decodificatore H.264** |", new[] { "tutto lo standard", "tutti i flussi di itu-t h.264.1", "nessuno saltato", "permesso di alberto", "`leggimi.md`" }], + ["C4 porta HEVC con i flussi H.265.1, RExt compreso", "| **C4 Decodificatore H.265** |", new[] { "itu-t h.265.1", "nessuno saltato", "`leggimi.md`", "rext", "`hevc_v1`" }], + ["C5 porta i lettori ASF, FLV e MPEG-PS", "| **C5 Lettori ASF, FLV e MPEG-PS** |", new[] { "asf", "flv", "13818-1", "file costruiti dalle prove" }], + ["C6 toglie Node, NSIS, Archivo e Lucide", "| **C6 Niente terzi nella CI e nell'interfaccia** |", new[] { "senza node", "al posto di nsis", "al posto di archivo", "al posto di lucide", "gitleaks e trivy" }], + ["le tappe C4–C6 e D1 hanno le loro dipendenze", "Dipendenze: C1", new[] { "c3 → c4", "c5 dopo c2", "c6 indipendente", "d1 indipendente" }], + ["in Docker lasciare la pagina del browser copia la sessione", "**Quando si copia**", new[] { "lasciare la pagina del browser", "risposta di alberto del 25 novembre 2026", "pagina «browser»", "vista remota della pagina collegamento", "chiudere la scheda", "per 5 secondi", "ricaricare la pagina non è lasciarla", "lasciando la pagina in docker e alla fine del permesso la copia ha le stesse garanzie" }], + ["il comando CDP della copia comprende la pagina lasciata in Docker", "| Copiare la sessione", new[] { "25 novembre 2026", "in docker lasciando la pagina del browser o chiudendone la scheda" }], + ["l'immagine Docker tiene le emoji e non Liberation", "- **Immagine.**", new[] { "`fonts-noto-color-emoji`, che resta", "`fonts-liberation` esce", "25 novembre 2026" }], + ["un'immagine troncata non ha impronta e resta", "- **Immagini troncate o rovinate**", new[] { "«file danneggiato o incompleto»", "nessuna impronta visiva", "mai doppione probabile per impronta", "resta in libreria", "25 novembre 2026" }], + ["il visualizzatore dice «File danneggiato o incompleto»", "- **File danneggiato o incompleto**", new[] { "tessera neutra", "visualizzatore", "resta in libreria", "non lo riscarica" }], + ["l'importazione non fa doppioni per impronta di un'immagine troncata", "I doppioni si cercano anche dentro la sorgente stessa", new[] { "mai «doppione probabile» per impronta", "«file danneggiato o incompleto»" }], + ["«Cosa scaricare prima» pesa visite e coda senza cambiare il resto", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine", new[] { "storie, evidenza, post, reel, taggati", "dopo il giro dei seguiti, che resta sempre primo", "visite del motore nella sessione", "coda dei file", "«come le impostazioni generali», il predefinito", "il governatore e i tetti", "le frequenze", "composizione casuale delle sessioni", "non le rende fisse", "§16 domanda 19" }], + ["«Cosa scaricare prima» c'è anche per account", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): «Come", new[] { "«come le impostazioni generali» (predefinito)", "trascinando", "§7.2, §6.5" }], + ["la coda dei file segue «Cosa scaricare prima»", "6. Coda dedicata", new[] { "«cosa scaricare prima»", "prima i file del tipo che viene primo", "le foto del profilo vanno con i post" }], + ["il peso di un tipo ha i suoi numeri", "| Peso di un tipo nella scelta", new[] { "16, 8, 4, 2, 1", "proposta" }], + ["la Dashboard è il cruscotto e la pagina iniziale", "La **Dashboard**", new[] { "cruscotto del motore", "pagina iniziale", "`/dashboard`", "`/attivita`", "la finestra di febe per windows si apre lì", "compatta" }], + ["la Dashboard mostra sempre l'anteprima del browser", "- **l'anteprima del browser, sempre visibile**", new[] { "che scorre", "mai nascosta dietro un clic" }], + ["la cronologia ha le miniature e l'anteprima ingrandita", "- la **cronologia dell'attività**", new[] { "miniature", "anteprima ingrandita", "«apri nella libreria»", "«apri l'account»" }], + ["la Dashboard è la prima voce della barra laterale", "Barra laterale fissa", new[] { "quattro voci (dashboard, libreria, account, importa)", "prima voce e la pagina iniziale" }], + ["«Raggruppa i post» o «Tutte le foto», ricordato per pagina", "- **«Raggruppa i post» o «Tutte le foto»**", new[] { "libreria e della vista dei contenuti della scheda account", "il predefinito", "una tessera per file", "una per la libreria e una per le viste degli account", "dentro un `try`", "vale «raggruppa i post»", "200.000 elementi" }], + ["la Dashboard è composta dai mockup", "- **Dashboard** (§7.9), dai mockup 06 e 11", new[] { "mockup 01", "dialogo leggero" }], + ["D1 ha le sue prove", "| **D1 Dashboard e ordine** |", new[] { "issue #59", "«cosa scaricare prima»", "`/dashboard`", "«raggruppa i post» / «tutte le foto»", "simulazione di 30 giorni", "il giro resta primo" }], + ["la domanda sulle raccolte in evidenza propone il loro posto", "| 19 |", new[] { "storie, evidenza, post, reel, taggati" }], + ["il glossario ha la Dashboard", "| Dashboard |", new[] { "`dashboard`", "attività" }], + ["il glossario ha «Cosa scaricare prima»", "| Cosa scaricare prima |", new[] { "`downloadorder`" }], + ["il glossario ha «Raggruppa i post»", "| Raggruppa i post |", new[] { "tessera per elemento" }], + ["il glossario ha «Tutte le foto»", "| Tutte le foto |", new[] { "tessera per file" }], + ]; + + private static string Root() => Directory.GetParent(GuideTests.GuideFolder())!.Parent!.FullName; + + private static string Read(params string[] parts) => File.ReadAllText(Path.Combine([Root(), .. parts])); + + [TestMethod] + [DynamicData(nameof(SettledPoints))] + public void TheSpecificationSettlesThePoint(string point, string start, string[] phrases) + { + var line = Read("docs", "SPECIFICA.md").Split('\n').FirstOrDefault(l => l.StartsWith(start, StringComparison.Ordinal)); + Assert.IsNotNull(line, $"«{point}»: nessuna riga di SPECIFICA.md comincia con «{start}»"); + var text = GuideTests.Normalize(line); + var missing = phrases.Where(p => !text.Contains(GuideTests.Normalize(p), StringComparison.Ordinal)).ToList(); + Assert.IsEmpty(missing, $"«{point}»: mancano: {string.Join(" | ", missing)}"); + } + + [TestMethod] + public void TheRuleOnExternalComponentsIsTheSameEverywhereAndSaysWhenEachComponentLeaves() + { + var claude = RuleLine(Read("CLAUDE.md"), "12. Niente componenti esterni"); + var appendix = RuleLine(Read("docs", "SPECIFICA.md")[Read("docs", "SPECIFICA.md").IndexOf("## Appendice A", StringComparison.Ordinal)..], "12. Niente componenti esterni"); + Assert.AreEqual(claude, appendix, "la regola 12 di CLAUDE.md e la sua copia nell'appendice A della specifica differiscono"); + + var spec = Read("docs", "SPECIFICA.md"); + var rule13 = RuleLine(spec, "13. **Niente componenti esterni**"); + var guide = Read("docs", "guida", "Sviluppo.md"); + var guideRule = guide[guide.IndexOf("- **Niente componenti esterni**", StringComparison.Ordinal)..]; + guideRule = guideRule[..guideRule.IndexOf("\n-", StringComparison.Ordinal)]; + var problems = new List(); + foreach (var (name, raw) in new[] { ("CLAUDE.md, regola 12", claude), ("SPECIFICA §2, regola 13", rule13), ("guida/Sviluppo.md", guideRule) }) + { + var text = GuideTests.Normalize(raw); + problems.AddRange(Exceptions.Where(e => !text.Contains(GuideTests.Normalize(e), StringComparison.Ordinal)).Select(e => $"{name} non ammette per nome «{e}»")); + if (text.Contains("da confermare", StringComparison.Ordinal)) + { + problems.Add($"{name} lascia ancora qualcosa «da confermare»: Alberto ha risposto (§16, domanda 17)"); + } + + foreach (var (component, stage) in Leaving) + { + var last = text.LastIndexOf(component.ToLowerInvariant(), StringComparison.Ordinal); + if (last < 0) + { + problems.Add($"{name} non nomina {component}"); + continue; + } + + var next = Stage().Match(text, last); + if (!next.Success || !string.Equals(next.Value, stage.ToLowerInvariant(), StringComparison.Ordinal)) + { + problems.Add($"{name}: {component} esce con la tappa {stage}, il testo dice «{(next.Success ? next.Value : "nessuna tappa")}»"); + } + } + } + + Assert.IsEmpty(problems, string.Join("\n", problems)); + } + + [TestMethod] + public void TheAnsweredQuestionsAreNotOpenAnyMore() + { + var spec = Read("docs", "SPECIFICA.md"); + var start = spec.IndexOf("## 16. Domande aperte per Alberto", StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, start, "la specifica non ha §16"); + var lines = spec[start..spec.IndexOf("## Appendice A", start, StringComparison.Ordinal)].Split('\n'); + var problems = new List(); + foreach (var (number, day) in AnsweredQuestions) + { + var row = lines.FirstOrDefault(l => l.StartsWith($"| {number} |", StringComparison.Ordinal)); + if (row is null) + { + problems.Add($"§16 non ha la domanda {number}"); + continue; + } + + var text = GuideTests.Normalize(row); + if (!text.Contains($"risposta di alberto del {day}", StringComparison.Ordinal) && !text.Contains($"risposte di alberto del {day}", StringComparison.Ordinal)) + { + problems.Add($"la domanda {number} di §16 non dice la risposta di Alberto del {day}"); + } + } + + var normalized = GuideTests.Normalize(spec); + problems.AddRange(StaleProposals.Where(p => normalized.Contains(p, StringComparison.Ordinal)).Select(p => $"la specifica dice ancora «{p}», ma Alberto ha risposto")); + Assert.IsEmpty(problems, string.Join("\n", problems)); + } + + [TestMethod] + public void EveryMentionOfFfmpegSaysThatItLeavesWithStageC3() + { + var problems = new List(); + foreach (var file in new[] { "CLAUDE.md", "docs/docker.md", "docs/processo.md", "docs/guida/Sviluppo.md" }) + { + var lines = Read(file.Split('/')).Split('\n'); + for (var i = 0; i < lines.Length; i++) + { + var line = lines[i]; + if (!line.Contains("ffmpeg", StringComparison.OrdinalIgnoreCase) || line.Contains("niente ffmpeg", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (!line.Contains("C3", StringComparison.Ordinal)) + { + problems.Add($"{file}:{i + 1}: ffmpeg senza la tappa C3 in cui esce"); + } + + if (line.Contains("C2–C3", StringComparison.Ordinal) || line.Contains("C2-C3", StringComparison.Ordinal)) + { + problems.Add($"{file}:{i + 1}: ffmpeg esce con la tappa C3, non con C2–C3"); + } + } + } + + Assert.IsEmpty(problems, string.Join("\n", problems)); + } + + [TestMethod] + public void EveryPackageIsAllowedOrSaysInWhichStageItLeaves() + { + var lines = Read("Directory.Packages.props").Split('\n'); + Assert.IsTrue(lines.Any(l => l.Contains(" + diff --git a/tests/Febe.Tests/Imaging/BmpDecoderTests.cs b/tests/Febe.Tests/Imaging/BmpDecoderTests.cs new file mode 100644 index 0000000..aaf7bea --- /dev/null +++ b/tests/Febe.Tests/Imaging/BmpDecoderTests.cs @@ -0,0 +1,189 @@ +using Febe.Core.Codecs.Images; +using static Febe.Tests.Imaging.TestImages; + +namespace Febe.Tests.Imaging; + +/// The in-house BMP decoder on files built by hand: variants the reference set lacks, and damage. +[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 + { + ["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(() => BmpDecoder.Decode(bytes), name); + } + else + { + Assert.Throws(() => BmpDecoder.Decode(bytes), name); + } + } + } + + [TestMethod] + public void AnImageBeyondTheLimitsIsRefusedButStillIdentified() + { + var bmp = Bmp(40, 100_000, 1, 24, BiRgb, [], new byte[4]); + Assert.ThrowsExactly(() => 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; + } +} diff --git a/tests/Febe.Tests/Imaging/GifDecoderTests.cs b/tests/Febe.Tests/Imaging/GifDecoderTests.cs new file mode 100644 index 0000000..43e61d3 --- /dev/null +++ b/tests/Febe.Tests/Imaging/GifDecoderTests.cs @@ -0,0 +1,192 @@ +using Febe.Core.Codecs.Images; +using static Febe.Tests.Imaging.TestImages; + +namespace Febe.Tests.Imaging; + +/// The in-house GIF decoder on files built from GIF89a: palettes, transparency, clipping, damage. +[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 + { + ["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(() => GifDecoder.Decode(bytes), name); + } + } + + [TestMethod] + public void ACanvasBeyondTheLimitsIsRefusedButStillIdentified() + { + var gif = Gif(60000, 60000, Palette4, GifFrame(0, 0, 1, 1, [1], 2)); + Assert.ThrowsExactly(() => GifDecoder.Decode(gif)); + Assert.AreEqual((60000, 60000), (GifDecoder.Identify(gif).Width, GifDecoder.Identify(gif).Height)); + } +} diff --git a/tests/Febe.Tests/Imaging/ImageAssert.cs b/tests/Febe.Tests/Imaging/ImageAssert.cs new file mode 100644 index 0000000..c2cbf4b --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageAssert.cs @@ -0,0 +1,43 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// Comparisons of decoded images that say where they differ. +internal static class ImageAssert +{ + /// Same size and the same bytes in every pixel. + 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); + } + + /// The same RGBA bytes, for images of the given width. + public static void AreEqual(int width, ReadOnlySpan expected, ReadOnlySpan 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 rgba) => $"({rgba[0]}, {rgba[1]}, {rgba[2]}, {rgba[3]})"; +} diff --git a/tests/Febe.Tests/Imaging/ImageFuzzTests.cs b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs new file mode 100644 index 0000000..3e732ea --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageFuzzTests.cs @@ -0,0 +1,129 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// Damaged files from the reference set, changed at random with fixed seeds: a decoder either reads them or throws +/// , never anything else (no index out of range, no overflow, no huge allocation). +/// +[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 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; + } + } +} diff --git a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs new file mode 100644 index 0000000..17ec59b --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs @@ -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; + +/// +/// 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 . +/// +[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 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 = ""; + 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 = ""; + 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(() => ImageConverter.Convert(png, ImageFormat.Gif)); + Assert.ThrowsExactly(() => 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(() => 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}"); + } + } + } + } + + /// Pixels covered by what paints on a transparent canvas: the sum of alpha / 255. + private static double Coverage(int width, int height, Action 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; + } + + /// A small big-endian TIFF block with one Orientation entry and one ASCII Make entry. + 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; + } + + /// Bytes standing in for an ICC profile (the codecs carry it without reading it). + /// A stand-in ICC profile: arbitrary bytes with the data colour space of its header (bytes 16-19) set. + 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; + } + + /// A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI. + 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)]; + } +} diff --git a/tests/Febe.Tests/Imaging/ImageQuality.cs b/tests/Febe.Tests/Imaging/ImageQuality.cs new file mode 100644 index 0000000..9c14b81 --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageQuality.cs @@ -0,0 +1,106 @@ +using System.Globalization; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// How close a lossy decode is to its reference: PSNR per channel and the share of pixels far off. +/// PSNR of the red channel, dB (infinity when identical). +/// PSNR of the green channel, dB. +/// PSNR of the blue channel, dB. +/// PSNR of the alpha channel, dB. +/// Share (0-1) of pixels with some channel off by more than . +/// Largest difference of any channel. +internal sealed record ImageQualityResult(double PsnrRed, double PsnrGreen, double PsnrBlue, double PsnrAlpha, double FarOff, int MaxDifference) +{ + /// The smallest PSNR of the colour channels. + 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}"); +} + +/// Measures and orientation helpers for comparing decoded images. +internal static class ImageQuality +{ + /// A pixel counts as far off when one of its channels differs by more than this. + public const int FarThreshold = 16; + + /// Lossy decodes must reach this PSNR on every colour channel (SPECIFICA §14.1, proposal of C1). + public const double MinimumPsnr = 40; + + /// Lossy decodes may have at most this share of pixels far off. + 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 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); + } + + /// Asserts the thresholds of a lossy decode. + 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)); + + /// + /// The image as it should be shown for EXIF orientation (1-8): mirrored, rotated + /// or transposed from the stored pixels. + /// + 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; + } +} diff --git a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs new file mode 100644 index 0000000..61e94a4 --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs @@ -0,0 +1,131 @@ +using System.Text; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// The common pieces of the in-house image codecs: format recognition, the RGBA image, the limits. +[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(""), 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(() => image.GetRow(2).Length.ToString(System.Globalization.CultureInfo.InvariantCulture)); + Assert.ThrowsExactly(() => image.GetPixel(3, 0)); + + Assert.ThrowsExactly(() => new RgbaImage(0, 1)); + Assert.ThrowsExactly(() => new RgbaImage(50_000, 50_000)); + Assert.ThrowsExactly(() => 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(() => 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(() => 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(1000); + Assert.AreEqual(1024, small.Length); + Assert.IsTrue(ImageBuffers.IsPooled(small)); + ImageBuffers.Return(small); + + var limit = ImageBuffers.Rent(ImageBuffers.PooledBytes); + Assert.AreEqual(ImageBuffers.PooledBytes, limit.Length); + Assert.IsTrue(ImageBuffers.IsPooled(limit)); + ImageBuffers.Return(limit); + + var large = ImageBuffers.Rent(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((ImageBuffers.PooledBytes / 2) + 1); + Assert.AreEqual((ImageBuffers.PooledBytes / 2) + 1, shorts.Length); + ImageBuffers.Return(shorts); + var words = ImageBuffers.Rent(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(() => ImageDecoder.Decode(tiff)); + Assert.Contains("TIFF", error.Message); + Assert.ThrowsExactly(() => 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)); + } +} diff --git a/tests/Febe.Tests/Imaging/JpegCodingTests.cs b/tests/Febe.Tests/Imaging/JpegCodingTests.cs new file mode 100644 index 0000000..e5f7385 --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegCodingTests.cs @@ -0,0 +1,549 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// 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. +/// +[TestClass] +public sealed class JpegCodingTests +{ + public TestContext TestContext { get; set; } = null!; + + /// Images and encoder settings the cross-checks run on. + public static IEnumerable 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 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 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 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 SpectralOnly(int count) + { + var all = Enumerable.Range(0, count).ToArray(); + var scans = new List { 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 ManyApproximations(int count) + { + var all = Enumerable.Range(0, count).ToArray(); + var scans = new List { 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); + } + + /// A full-resolution plane averaged down to a component with factors (h, v) of a frame with maxima (maxH, maxV). + 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; + } +} diff --git a/tests/Febe.Tests/Imaging/JpegEncoderTests.cs b/tests/Febe.Tests/Imaging/JpegEncoderTests.cs new file mode 100644 index 0000000..d9d60d7 --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegEncoderTests.cs @@ -0,0 +1,275 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// 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. +/// +[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 { 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 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 = ""; + 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(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Quality = quality }), $"qualità {quality}"); + } + + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = -1 })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { RestartInterval = 65536 })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = "non TIFF"u8.ToArray() })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Exif = Tiff(1, padding: 70_000) })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { Xmp = new string('x', 70_000) })); + Assert.Throws(() => JpegEncoder.Encode(source, new JpegEncoderOptions { IccProfile = new byte[256 * 65519] })); + Assert.Throws(() => 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 counts) + { + var sum = 0; + foreach (var c in counts) + { + sum += c; + } + + return sum; + } + + /// The image with alpha 255 (JPEG has none) and, for grey, R = G = B. + 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); + } +} diff --git a/tests/Febe.Tests/Imaging/JpegMalformedTests.cs b/tests/Febe.Tests/Imaging/JpegMalformedTests.cs new file mode 100644 index 0000000..f5d948f --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegMalformedTests.cs @@ -0,0 +1,444 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// 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. +/// +[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(() => JpegDecoder.Decode(cut), $"ripristino {restart}, {length} di {file.Length} byte"); + if (length < frameEnd) + { + Assert.Throws(() => 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(() => 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(() => 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(() => 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(() => 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(() => 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(() => 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(() => JpegDecoder.Decode(file, new ImageLimits { MaxPixels = 10_000 })); + Assert.ThrowsExactly(() => JpegDecoder.Decode(file, new ImageLimits { MaxWidth = 100 })); + Assert.ThrowsExactly(() => 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(() => 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(() => 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(() => JpegDecoder.Decode(file), what); + Assert.IsNotInstanceOfType(error, what); + Assert.IsFalse(string.IsNullOrWhiteSpace(error.Message), what); + } + + private static void AssertOversubscribed(byte[] file, string what) + { + var error = Assert.ThrowsExactly(() => JpegDecoder.Decode(file), what); + StringAssert.Contains(error.Message, "non stanno nella loro lunghezza", what); + } + + /// Offset of the first marker segment of type (the 0xFF byte). + private static int SegmentOffset(byte[] file, int marker) => SegmentOffsets(file, marker)[0]; + + private static List SegmentOffsets(byte[] file, int marker) + { + var found = new List(); + 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(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]; + } +} diff --git a/tests/Febe.Tests/Imaging/JpegReferenceTests.cs b/tests/Febe.Tests/Imaging/JpegReferenceTests.cs new file mode 100644 index 0000000..35e1158 --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegReferenceTests.cs @@ -0,0 +1,56 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// 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 dB and at most +/// of the pixels off by more than . +/// +[TestClass] +public sealed class JpegReferenceTests +{ + public TestContext TestContext { get; set; } = null!; + + public static IEnumerable 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); + } + } + } +} diff --git a/tests/Febe.Tests/Imaging/JpegTestEncoder.cs b/tests/Febe.Tests/Imaging/JpegTestEncoder.cs new file mode 100644 index 0000000..73c8f9e --- /dev/null +++ b/tests/Febe.Tests/Imaging/JpegTestEncoder.cs @@ -0,0 +1,1186 @@ +using System.Numerics; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// Entropy coding of the test encoder. +public enum JpegTestCoding +{ + Huffman, + Arithmetic, +} + +/// One scan of a progressive script: components (frame indices), band and approximation. +internal sealed record JpegTestScan(int[] Components, int Ss, int Se, int Ah, int Al); + +/// What the test encoder writes around the coefficients it is given. +internal sealed record JpegTestOptions +{ + public JpegTestCoding Coding { get; init; } = JpegTestCoding.Huffman; + + public bool Progressive { get; init; } + + /// The progressive script; null for . + public IReadOnlyList? Script { get; init; } + + /// Sequential only: one scan per component instead of one interleaved scan. + public bool SeparateScans { get; init; } + + public int RestartInterval { get; init; } + + /// Write height 0 in the frame and give it in a DNL segment after the first scan. + public bool HeightInDnl { get; init; } + + public bool Jfif { get; init; } = true; + + /// Adobe APP14 transform to write (0 none/RGB/CMYK, 1 YCbCr, 2 YCCK), or -1 for no segment. + public int AdobeTransform { get; init; } = -1; + + /// Arithmetic DC conditioning (L, U) and AC conditioning Kx, written in DAC when not the defaults. + public (int L, int U) DcConditioning { get; init; } = (0, 1); + + public int AcConditioning { get; init; } = 5; +} + +/// +/// A JPEG writer for the tests only, from quantized coefficients (, +/// ): extended sequential and progressive DCT (T.81 Annex G: spectral +/// selection and successive approximation, EOB runs, correction bits), Huffman with tables built from the symbol counts +/// of each scan (Annex K.2) or arithmetic coding (Annex D, F.1.4, G.1.3), restart intervals, DNL, Adobe APP14; and +/// lossless (Annex H) from samples. It exists to make files the reference set lacks; the tests then check that the +/// decoder gets back exactly the coefficients (or samples) that went in. +/// +internal static class JpegTestEncoder +{ + private const int DcStatistics = 64; + private const int AcStatistics = 256; + private const int LosslessStatistics = 158; + + /// A script like the usual ones: DC first with Al 1, AC bands with Al 2 then 1, refinements down to 0. + public static IReadOnlyList DefaultScript(int componentCount) + { + var all = Enumerable.Range(0, componentCount).ToArray(); + var scans = new List { new(all, 0, 0, 0, 1) }; + for (var c = 0; c < componentCount; c++) + { + scans.Add(new([c], 1, 5, 0, 2)); + scans.Add(new([c], 6, 63, 0, 2)); + } + + for (var c = componentCount - 1; c >= 0; c--) + { + scans.Add(new([c], 1, 63, 2, 1)); + } + + scans.Add(new(all, 0, 0, 1, 0)); + for (var c = 0; c < componentCount; c++) + { + scans.Add(new([c], 1, 63, 1, 0)); + } + + return scans; + } + + /// Writes a DCT-based file holding exactly 's coefficients. + public static byte[] Write(JpegCoefficients image, JpegTestOptions options) + { + var output = new JpegOutput(); + output.Marker(0xD8); + WriteHeaders(output, options); + var tables = new List(); + foreach (var c in image.Components) + { + while (tables.Count <= c.QuantizationTable) + { + tables.Add(new ushort[64]); + } + + tables[c.QuantizationTable] = c.Quantization; + } + + JpegSegments.WriteQuantization(output, tables); + var marker = (options.Coding, options.Progressive) switch + { + (JpegTestCoding.Huffman, false) => 0xC1, + (JpegTestCoding.Huffman, true) => 0xC2, + (JpegTestCoding.Arithmetic, false) => 0xC9, + _ => 0xCA, + }; + JpegSegments.WriteFrame(output, marker, image.Precision, image.Width, options.HeightInDnl ? 0 : image.Height, image.Components.Select(c => (c.Id, c.H, c.V, c.QuantizationTable)).ToList()); + if (options.RestartInterval > 0) + { + JpegSegments.WriteRestartInterval(output, options.RestartInterval); + } + + if (options.Coding == JpegTestCoding.Arithmetic) + { + WriteConditioning(output, options, image.Components.Count); + } + + var all = Enumerable.Range(0, image.Components.Count).ToArray(); + IReadOnlyList script = options.Progressive + ? options.Script ?? DefaultScript(image.Components.Count) + : options.SeparateScans ? all.Select(c => new JpegTestScan([c], 0, 63, 0, 0)).ToList() : [new JpegTestScan(all, 0, 63, 0, 0)]; + var layout = new Layout(image.Width, image.Height, image.Components.Select(c => (c.H, c.V)).ToList(), 8); + var first = true; + foreach (var scan in script) + { + if (options.Coding == JpegTestCoding.Huffman) + { + WriteHuffmanScan(output, image, layout, scan, options); + } + else + { + WriteArithmeticScan(output, image, layout, scan, options); + } + + if (first && options.HeightInDnl) + { + JpegSegments.WriteSegment(output, 0xDC, [(byte)(image.Height >> 8), (byte)image.Height]); + } + + first = false; + } + + output.Marker(0xD9); + return output.ToArray(); + } + + /// + /// Writes a lossless file (SOF3 or SOF11) of the given samples: one plane per component at its own size, values + /// below 2^precision; 1-7, point transform . + /// + public static byte[] WriteLossless( + int width, + int height, + int precision, + IReadOnlyList<(int Id, int H, int V, int[] Samples)> planes, + int predictor, + int pointTransform, + JpegTestOptions options) + { + var output = new JpegOutput(); + output.Marker(0xD8); + WriteHeaders(output, options); + JpegSegments.WriteFrame(output, options.Coding == JpegTestCoding.Huffman ? 0xC3 : 0xCB, precision, width, height, planes.Select(p => (p.Id, p.H, p.V, 0)).ToList()); + if (options.RestartInterval > 0) + { + JpegSegments.WriteRestartInterval(output, options.RestartInterval); + } + + if (options.Coding == JpegTestCoding.Arithmetic) + { + WriteConditioning(output, options, planes.Count); + } + + var layout = new Layout(width, height, planes.Select(p => (p.H, p.V)).ToList(), 1); + var all = Enumerable.Range(0, planes.Count).ToArray(); + var scans = options.SeparateScans ? all.Select(c => new[] { c }).ToList() : [all]; + foreach (var components in scans) + { + var model = new LosslessModel(layout, planes, components, precision, predictor, pointTransform); + if (options.Coding == JpegTestCoding.Huffman) + { + var counter = new CountingSink(); + model.EncodeHuffman(counter, options.RestartInterval); + var tables = counter.BuildTables(output, components.Length); + JpegSegments.WriteScan(output, components.Select((c, j) => (planes[c].Id, j, 0)).ToList(), predictor, 0, 0, pointTransform); + var writer = new WritingSink(output, tables); + model.EncodeHuffman(writer, options.RestartInterval); + writer.Finish(); + } + else + { + JpegSegments.WriteScan(output, components.Select((c, j) => (planes[c].Id, j, 0)).ToList(), predictor, 0, 0, pointTransform); + var encoder = new ArithmeticEncoder(output); + model.EncodeArithmetic(encoder, options); + encoder.Flush(); + } + } + + output.Marker(0xD9); + return output.ToArray(); + } + + private static void WriteHeaders(JpegOutput output, JpegTestOptions options) + { + if (options.Jfif) + { + JpegSegments.WriteJfif(output); + } + + if (options.AdobeTransform >= 0) + { + JpegSegments.WriteSegment(output, 0xEE, [(byte)'A', (byte)'d', (byte)'o', (byte)'b', (byte)'e', 0, 100, 0, 0, 0, 0, (byte)options.AdobeTransform]); + } + } + + private static void WriteConditioning(JpegOutput output, JpegTestOptions options, int tables) + { + if (options.DcConditioning == (0, 1) && options.AcConditioning == 5) + { + return; + } + + var payload = new List(); + for (var t = 0; t < Math.Min(tables, 4); t++) + { + payload.Add((byte)t); + payload.Add((byte)((options.DcConditioning.U << 4) | options.DcConditioning.L)); + payload.Add((byte)(0x10 | t)); + payload.Add((byte)options.AcConditioning); + } + + JpegSegments.WriteSegment(output, 0xCC, payload.ToArray()); + } + + /// MCU geometry, the same rules as the decoder (T.81 A.2). + private sealed class Layout + { + public Layout(int width, int height, IReadOnlyList<(int H, int V)> sampling, int unit) + { + var maxH = sampling.Max(s => s.H); + var maxV = sampling.Max(s => s.V); + McusWide = (width + (unit * maxH) - 1) / (unit * maxH); + McusHigh = (height + (unit * maxV) - 1) / (unit * maxV); + Sampling = sampling; + Wide = new int[sampling.Count]; + High = new int[sampling.Count]; + Stride = new int[sampling.Count]; + for (var i = 0; i < sampling.Count; i++) + { + var cw = ((width * sampling[i].H) + maxH - 1) / maxH; + var ch = ((height * sampling[i].V) + maxV - 1) / maxV; + Wide[i] = (cw + unit - 1) / unit; + High[i] = (ch + unit - 1) / unit; + Stride[i] = sampling.Count == 1 ? Wide[i] : McusWide * sampling[i].H; + } + } + + public int McusWide { get; } + + public int McusHigh { get; } + + public IReadOnlyList<(int H, int V)> Sampling { get; } + + /// Units covering each component (a non-interleaved scan). + public int[] Wide { get; } + + public int[] High { get; } + + /// Units per row of each component's storage. + public int[] Stride { get; } + + /// Calls (position in scan, component, x, y) for every data unit, and () between intervals. + public void Walk(int[] components, int restartInterval, Action unit, Action restart) + { + var single = components.Length == 1; + var perRow = single ? Wide[components[0]] : McusWide; + var total = single ? Wide[components[0]] * High[components[0]] : McusWide * McusHigh; + for (var mcu = 0; mcu < total; mcu++) + { + if (restartInterval > 0 && mcu > 0 && mcu % restartInterval == 0) + { + restart(); + } + + var mx = mcu % perRow; + var my = mcu / perRow; + for (var j = 0; j < components.Length; j++) + { + var c = components[j]; + var (h, v) = single ? (1, 1) : Sampling[c]; + for (var yy = 0; yy < v; yy++) + { + for (var xx = 0; xx < h; xx++) + { + unit(j, c, single ? mx : (mx * h) + xx, single ? my : (my * v) + yy); + } + } + } + } + } + } + + /// Receives Huffman symbols (tables 0-3 DC, 4-7 AC) and raw bits. + private interface ISink + { + void Symbol(int table, int symbol); + + void Bits(int value, int count); + + void Restart(); + } + + private sealed class CountingSink : ISink + { + private readonly long[][] _counts = Enumerable.Range(0, 8).Select(_ => new long[256]).ToArray(); + + public void Symbol(int table, int symbol) => _counts[table][symbol]++; + + public void Bits(int value, int count) + { + } + + public void Restart() + { + } + + /// Optimal tables for the counted symbols (T.81 K.2), written as DHT segments. + public JpegHuffmanTable?[] BuildTables(JpegOutput output, int count) + { + var tables = new JpegHuffmanTable?[8]; + for (var t = 0; t < 8; t++) + { + if (_counts[t].All(c => c == 0)) + { + continue; + } + + var (counts, values) = OptimalTable(_counts[t]); + tables[t] = JpegHuffmanTable.Build(counts, values); + JpegSegments.WriteHuffman(output, t >= 4 ? 1 : 0, t & 3, counts, values); + } + + return tables; + } + } + + private sealed class WritingSink : ISink + { + private readonly JpegOutput _output; + private readonly JpegHuffmanTable?[] _tables; + private readonly JpegBitWriter _writer; + private int _restart; + + public WritingSink(JpegOutput output, JpegHuffmanTable?[] tables) + { + _output = output; + _tables = tables; + _writer = new JpegBitWriter(output); + } + + public void Symbol(int table, int symbol) => _writer.WriteSymbol(_tables[table]!, symbol); + + public void Bits(int value, int count) + { + if (count > 0) + { + _writer.WriteBits(value, count); + } + } + + public void Restart() + { + _writer.Flush(); + _output.Marker(0xD0 + (_restart++ & 7)); + } + + public void Finish() => _writer.Flush(); + } + + /// Code lengths from symbol counts (Figures K.1-K.3), limited to 16 bits, no all-ones code. + private static (byte[] Counts, byte[] Values) OptimalTable(long[] frequencies) + { + var freq = new long[257]; + Array.Copy(frequencies, freq, 256); + freq[256] = 1; + var codeSize = new int[257]; + var others = Enumerable.Repeat(-1, 257).ToArray(); + while (true) + { + var v1 = -1; + var v2 = -1; + for (var i = 0; i <= 256; i++) + { + if (freq[i] > 0 && (v1 < 0 || freq[i] <= freq[v1])) + { + v1 = i; + } + } + + for (var i = 0; i <= 256; i++) + { + if (freq[i] > 0 && i != v1 && (v2 < 0 || freq[i] <= freq[v2])) + { + v2 = i; + } + } + + if (v2 < 0) + { + break; + } + + freq[v1] += freq[v2]; + freq[v2] = 0; + codeSize[v1]++; + while (others[v1] >= 0) + { + v1 = others[v1]; + codeSize[v1]++; + } + + others[v1] = v2; + codeSize[v2]++; + while (others[v2] >= 0) + { + v2 = others[v2]; + codeSize[v2]++; + } + } + + var bits = new int[33]; + for (var i = 0; i <= 256; i++) + { + if (codeSize[i] > 0) + { + bits[codeSize[i]]++; + } + } + + for (var i = 32; i > 16; i--) + { + while (bits[i] > 0) + { + var j = i - 2; + while (bits[j] == 0) + { + j--; + } + + bits[i] -= 2; + bits[i - 1]++; + bits[j + 1] += 2; + bits[j]--; + } + } + + var longest = 16; + while (bits[longest] == 0) + { + longest--; + } + + bits[longest]--; + var values = new List(); + for (var size = 1; size <= 32; size++) + { + for (var s = 0; s < 256; s++) + { + if (codeSize[s] == size) + { + values.Add((byte)s); + } + } + } + + return (bits.Skip(1).Take(16).Select(b => (byte)b).ToArray(), values.ToArray()); + } + + private static int Category(int value) => value == 0 ? 0 : BitOperations.Log2((uint)Math.Abs(value)) + 1; + + private static void Value(ISink sink, int table, int run, int value) + { + var category = Category(value); + sink.Symbol(table, (run << 4) | category); + sink.Bits(value < 0 ? value - 1 : value, category); + } + + /// Point transform of an AC coefficient: the magnitude shifted, the sign kept (G.1.2.3). + private static int Shifted(int coefficient, int al) => coefficient >= 0 ? coefficient >> al : -(-coefficient >> al); + + private static void WriteHuffmanScan(JpegOutput output, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) + { + var counter = new CountingSink(); + EncodeHuffmanScan(counter, image, layout, scan, options); + var tables = counter.BuildTables(output, scan.Components.Length); + JpegSegments.WriteScan(output, scan.Components.Select((c, j) => (image.Components[c].Id, j, j)).ToList(), scan.Ss, scan.Se, scan.Ah, scan.Al); + var writer = new WritingSink(output, tables); + EncodeHuffmanScan(writer, image, layout, scan, options); + writer.Finish(); + } + + private static void EncodeHuffmanScan(ISink sink, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) + { + var zigzag = JpegTables.ZigZag; + var predictors = new int[scan.Components.Length]; + var eobRun = 0; + var pendingBits = new List(); + var progressive = options.Progressive; + var refineAc = progressive && scan.Ss > 0 && scan.Ah > 0; + + void EmitEobRun() + { + if (eobRun > 0) + { + var bits = BitOperations.Log2((uint)eobRun); + sink.Symbol(4, bits << 4); + sink.Bits(eobRun, bits); + eobRun = 0; + } + + foreach (var bit in pendingBits) + { + sink.Bits(bit, 1); + } + + pendingBits.Clear(); + } + + layout.Walk( + scan.Components, + options.RestartInterval, + (j, c, x, y) => + { + var component = image.Components[c]; + var block = component.Block(x, y); + if (!progressive) + { + var difference = block[0] - predictors[j]; + predictors[j] = block[0]; + Value(sink, j, 0, difference); + var run = 0; + for (var k = 1; k < 64; k++) + { + int value = block[zigzag[k]]; + if (value == 0) + { + run++; + continue; + } + + for (; run > 15; run -= 16) + { + sink.Symbol(4 + j, 0xF0); + } + + Value(sink, 4 + j, run, value); + run = 0; + } + + if (run > 0) + { + sink.Symbol(4 + j, 0x00); + } + } + else if (scan.Ss == 0 && scan.Ah == 0) + { + var dc = block[0] >> scan.Al; + Value(sink, j, 0, dc - predictors[j]); + predictors[j] = dc; + } + else if (scan.Ss == 0) + { + sink.Bits((block[0] >> scan.Al) & 1, 1); + } + else if (!refineAc) + { + var run = 0; + for (var k = scan.Ss; k <= scan.Se; k++) + { + var value = Shifted(block[zigzag[k]], scan.Al); + if (value == 0) + { + run++; + continue; + } + + EmitEobRun(); + for (; run > 15; run -= 16) + { + sink.Symbol(4, 0xF0); + } + + Value(sink, 4, run, value); + run = 0; + } + + if (run > 0 && ++eobRun == 0x7FFF) + { + EmitEobRun(); + } + } + else + { + var end = scan.Ss - 1; + for (var k = scan.Ss; k <= scan.Se; k++) + { + if (Math.Abs(block[zigzag[k]]) >> scan.Al == 1) + { + end = k; + } + } + + var run = 0; + var corrections = new List(); + for (var k = scan.Ss; k <= scan.Se; k++) + { + var coefficient = block[zigzag[k]]; + var magnitude = Math.Abs(coefficient) >> scan.Al; + if (magnitude == 0) + { + run++; + continue; + } + + while (run > 15 && k <= end) + { + EmitEobRun(); + sink.Symbol(4, 0xF0); + run -= 16; + foreach (var bit in corrections) + { + sink.Bits(bit, 1); + } + + corrections.Clear(); + } + + if (magnitude > 1) + { + corrections.Add(magnitude & 1); + continue; + } + + EmitEobRun(); + sink.Symbol(4, (run << 4) | 1); + sink.Bits(coefficient < 0 ? 0 : 1, 1); + foreach (var bit in corrections) + { + sink.Bits(bit, 1); + } + + corrections.Clear(); + run = 0; + } + + if (run > 0 || corrections.Count > 0) + { + eobRun++; + pendingBits.AddRange(corrections); + if (eobRun == 0x7FFF || pendingBits.Count > 900) + { + EmitEobRun(); + } + } + } + }, + () => + { + EmitEobRun(); + sink.Restart(); + Array.Clear(predictors); + }); + EmitEobRun(); + } + + /// The QM coder of T.81 D.1 (Initenc, Code_0/Code_1, Renorm_e, Byte_out with carry, Flush). + private sealed class ArithmeticEncoder + { + private readonly JpegOutput _output; + private long _c; + private int _a; + private int _ct; + private int _buffer; + private int _stack; + private int _start; + private int _restart; + + public ArithmeticEncoder(JpegOutput output) + { + _output = output; + Initialize(); + } + + public void Encode(ref byte state, int bit) + { + var s = state; + int qe = JpegArithmeticTable.Qe[s & 0x7F]; + var mps = s >> 7; + _a -= qe; + if (bit != mps) + { + if (_a >= qe) + { + _c += _a; + _a = qe; + } + + state = JpegArithmeticTable.AfterLps(s); + } + else + { + if (_a >= 0x8000) + { + return; + } + + if (_a < qe) + { + _c += _a; + _a = qe; + } + + state = JpegArithmeticTable.AfterMps(s); + } + + do + { + _a <<= 1; + _c <<= 1; + _ct--; + if (_ct == 0) + { + ByteOut(); + _ct = 8; + } + } + while (_a < 0x8000); + } + + public void EncodeFixed(int bit) + { + var state = JpegArithmeticTable.FixedState; + Encode(ref state, bit); + } + + public void Flush() + { + var t = (_c + _a - 1) & 0xFFFF0000L; + if (t < _c) + { + t += 0x8000; + } + + _c = t << _ct; + ByteOut(); + _c <<= 8; + ByteOut(); + EmitBuffer(); + for (; _stack > 0; _stack--) + { + _output.Add(0xFF); + _output.Add(0); + } + + // Discard_final_zeros: the decoder supplies zeros at the marker anyway; stuffed zeros stay. + while (_output.Length > _start && _output[_output.Length - 1] == 0 && (_output.Length - 1 == _start || _output[_output.Length - 2] != 0xFF)) + { + _output.Truncate(_output.Length - 1); + } + } + + public void Restart() + { + Flush(); + _output.Marker(0xD0 + (_restart++ & 7)); + Initialize(); + } + + private void Initialize() + { + _c = 0; + _a = 0x10000; + _ct = 11; + _buffer = -1; + _stack = 0; + _start = _output.Length; + } + + private void ByteOut() + { + var t = _c >> 19; + if (t > 0xFF) + { + _buffer++; + EmitBuffer(); + for (; _stack > 0; _stack--) + { + _output.Add(0); + } + + _buffer = (int)(t & 0xFF); + } + else if (t == 0xFF) + { + _stack++; + } + else + { + EmitBuffer(); + for (; _stack > 0; _stack--) + { + _output.Add(0xFF); + _output.Add(0); + } + + _buffer = (int)t; + } + + _c &= 0x7FFFF; + } + + private void EmitBuffer() + { + if (_buffer >= 0) + { + _output.Add((byte)_buffer); + if (_buffer == 0xFF) + { + _output.Add(0); + } + } + + _buffer = -1; + } + } + + private static int Classify(int difference, int low, int high) + { + var magnitude = Math.Abs(difference); + if (magnitude <= (low == 0 ? 0 : 1 << (low - 1))) + { + return 0; + } + + var negative = difference < 0 ? 1 : 0; + return magnitude <= 1 << high ? 1 + negative : 3 + negative; + } + + /// Encode_V of a DC-model value (Figures F.4, F.6-F.9; Tables F.4, H.3). + private static void EncodeValue(ArithmeticEncoder encoder, byte[] statistics, int offset, int s0, int x1, int value) + { + if (value == 0) + { + encoder.Encode(ref statistics[offset + s0], 0); + return; + } + + encoder.Encode(ref statistics[offset + s0], 1); + var sign = value < 0 ? 1 : 0; + encoder.Encode(ref statistics[offset + s0 + 1], sign); + var s = s0 + 2 + sign; + var sz = Math.Abs(value) - 1; + if (sz == 0) + { + encoder.Encode(ref statistics[offset + s], 0); + return; + } + + encoder.Encode(ref statistics[offset + s], 1); + var m = 1; + s = x1; + while (sz >= m << 1) + { + encoder.Encode(ref statistics[offset + s], 1); + m <<= 1; + s++; + } + + encoder.Encode(ref statistics[offset + s], 0); + for (var bit = m >> 1; bit != 0; bit >>= 1) + { + encoder.Encode(ref statistics[offset + s + 14], (sz & bit) != 0 ? 1 : 0); + } + } + + private static void EncodeAc(ArithmeticEncoder encoder, byte[] statistics, int offset, int kx, int ss, int se, int al, ReadOnlySpan block) + { + var zigzag = JpegTables.ZigZag; + var last = ss - 1; + for (var k = ss; k <= se; k++) + { + if (Shifted(block[zigzag[k]], al) != 0) + { + last = k; + } + } + + for (var k = ss; k <= se; k++) + { + var se3 = 3 * (k - 1); + if (k > last) + { + encoder.Encode(ref statistics[offset + se3], 1); + return; + } + + encoder.Encode(ref statistics[offset + se3], 0); + while (Shifted(block[zigzag[k]], al) == 0) + { + encoder.Encode(ref statistics[offset + se3 + 1], 0); + se3 += 3; + k++; + } + + encoder.Encode(ref statistics[offset + se3 + 1], 1); + var value = Shifted(block[zigzag[k]], al); + encoder.EncodeFixed(value < 0 ? 1 : 0); + var s = se3 + 2; + var sz = Math.Abs(value) - 1; + if (sz == 0) + { + encoder.Encode(ref statistics[offset + s], 0); + continue; + } + + encoder.Encode(ref statistics[offset + s], 1); + var m = 1; + if (sz < 2) + { + encoder.Encode(ref statistics[offset + s], 0); + } + else + { + encoder.Encode(ref statistics[offset + s], 1); + m = 2; + s = k <= kx ? 189 : 217; + while (sz >= m << 1) + { + encoder.Encode(ref statistics[offset + s], 1); + m <<= 1; + s++; + } + + encoder.Encode(ref statistics[offset + s], 0); + } + + for (var bit = m >> 1; bit != 0; bit >>= 1) + { + encoder.Encode(ref statistics[offset + s + 14], (sz & bit) != 0 ? 1 : 0); + } + } + } + + private static void EncodeAcRefine(ArithmeticEncoder encoder, byte[] statistics, int offset, int ss, int se, int al, ReadOnlySpan block) + { + var zigzag = JpegTables.ZigZag; + var endOfBand = 0; + for (var k = 1; k <= se; k++) + { + if (Math.Abs(block[zigzag[k]]) >> (al + 1) != 0) + { + endOfBand = k; + } + } + + var last = ss - 1; + for (var k = ss; k <= se; k++) + { + if (Math.Abs(block[zigzag[k]]) >> al != 0) + { + last = k; + } + } + + for (var k = ss; k <= se; k++) + { + var se3 = 3 * (k - 1); + if (k > endOfBand) + { + if (k > last) + { + encoder.Encode(ref statistics[offset + se3], 1); + return; + } + + encoder.Encode(ref statistics[offset + se3], 0); + } + + while (true) + { + var coefficient = block[zigzag[k]]; + var magnitude = Math.Abs(coefficient) >> al; + if (magnitude > 1) + { + encoder.Encode(ref statistics[offset + se3 + 2], magnitude & 1); + break; + } + + if (magnitude == 1) + { + encoder.Encode(ref statistics[offset + se3 + 1], 1); + encoder.EncodeFixed(coefficient < 0 ? 1 : 0); + break; + } + + encoder.Encode(ref statistics[offset + se3 + 1], 0); + se3 += 3; + k++; + } + } + } + + private static void WriteArithmeticScan(JpegOutput output, JpegCoefficients image, Layout layout, JpegTestScan scan, JpegTestOptions options) + { + JpegSegments.WriteScan(output, scan.Components.Select((c, j) => (image.Components[c].Id, j, j)).ToList(), scan.Ss, scan.Se, scan.Ah, scan.Al); + var encoder = new ArithmeticEncoder(output); + var dc = new byte[4 * DcStatistics]; + var ac = new byte[4 * AcStatistics]; + var predictors = new int[scan.Components.Length]; + var contexts = new int[scan.Components.Length]; + var (low, high) = options.DcConditioning; + var kx = options.AcConditioning; + layout.Walk( + scan.Components, + options.RestartInterval, + (j, c, x, y) => + { + var block = image.Components[c].Block(x, y); + if (!options.Progressive || (scan.Ss == 0 && scan.Ah == 0)) + { + var value = options.Progressive ? block[0] >> scan.Al : block[0]; + var difference = value - predictors[j]; + predictors[j] = value; + EncodeValue(encoder, dc, j * DcStatistics, contexts[j], 20, difference); + contexts[j] = Classify(difference, low, high) * 4; + if (!options.Progressive) + { + EncodeAc(encoder, ac, j * AcStatistics, kx, 1, 63, 0, block); + } + } + else if (scan.Ss == 0) + { + encoder.EncodeFixed((block[0] >> scan.Al) & 1); + } + else if (scan.Ah == 0) + { + EncodeAc(encoder, ac, 0, kx, scan.Ss, scan.Se, scan.Al, block); + } + else + { + EncodeAcRefine(encoder, ac, 0, scan.Ss, scan.Se, scan.Al, block); + } + }, + () => + { + encoder.Restart(); + Array.Clear(dc); + Array.Clear(ac); + Array.Clear(predictors); + Array.Clear(contexts); + }); + encoder.Flush(); + } + + /// Predictions and differences of a lossless scan (H.1.2), the inverse of the decoder. + private sealed class LosslessModel + { + private readonly Layout _layout; + private readonly IReadOnlyList<(int Id, int H, int V, int[] Samples)> _planes; + private readonly int[] _components; + private readonly int _precision; + private readonly int _predictor; + private readonly int _pt; + private readonly int[] _widths; + private readonly int[] _heights; + + public LosslessModel(Layout layout, IReadOnlyList<(int Id, int H, int V, int[] Samples)> planes, int[] components, int precision, int predictor, int pt) + { + _layout = layout; + _planes = planes; + _components = components; + _precision = precision; + _predictor = predictor; + _pt = pt; + _widths = layout.Wide; + _heights = layout.High; + } + + /// The sample (x, y) of component c after the point transform, edges repeated beyond the plane. + private int Sample(int c, int x, int y) => + _planes[c].Samples[(Math.Min(y, _heights[c] - 1) * _widths[c]) + Math.Min(x, _widths[c] - 1)] >> _pt; + + private int Predict(int c, int x, int y, int firstRow) + { + if (y == firstRow) + { + return x == 0 ? 1 << (_precision - _pt - 1) : Sample(c, x - 1, y); + } + + if (x == 0) + { + return Sample(c, x, y - 1); + } + + var a = Sample(c, x - 1, y); + var b = Sample(c, x, y - 1); + var cc = Sample(c, x - 1, y - 1); + return _predictor switch + { + 1 => a, + 2 => b, + 3 => cc, + 4 => a + b - cc, + 5 => a + ((b - cc) >> 1), + 6 => b + ((a - cc) >> 1), + _ => (a + b) >> 1, + }; + } + + /// The difference modulo 2^16, as a value in -32767..32768. + private static int Difference(int sample, int prediction) + { + var d = (sample - prediction) & 0xFFFF; + return d > 32768 ? d - 65536 : d; + } + + private IEnumerable<(int J, int C, int X, int Y, int FirstRow)> Units(int restartInterval, Action restart) + { + // The walk is recorded first, restart points as J = -1; the first line of an interval is the first sample + // row of its first MCU row. + var list = new List<(int J, int C, int X, int Y)>(); + _layout.Walk(_components, restartInterval, (j, c, x, y) => list.Add((j, c, x, y)), () => list.Add((-1, 0, 0, 0))); + var single = _components.Length == 1; + var perRow = single ? _layout.Wide[_components[0]] : _layout.McusWide; + var unitsPerMcu = single ? 1 : _components.Sum(c => _layout.Sampling[c].H * _layout.Sampling[c].V); + var units = 0; + var firstMcuRow = 0; + foreach (var (j, c, x, y) in list) + { + if (j < 0) + { + restart(); + firstMcuRow = units / unitsPerMcu / perRow; + continue; + } + + units++; + yield return (j, c, x, y, firstMcuRow * (single ? 1 : _layout.Sampling[c].V)); + } + } + public void EncodeHuffman(ISink sink, int restartInterval) + { + foreach (var (j, c, x, y, firstRow) in Units(restartInterval, sink.Restart)) + { + var difference = Difference(Sample(c, x, y), Predict(c, x, y, firstRow)); + var category = difference == 32768 ? 16 : Category(difference); + sink.Symbol(j, category); + if (category < 16) + { + sink.Bits(difference < 0 ? difference - 1 : difference, category); + } + } + } + + public void EncodeArithmetic(ArithmeticEncoder encoder, JpegTestOptions options) + { + var statistics = new byte[4 * LosslessStatistics]; + var classes = new Dictionary<(int C, int X, int Y), int>(); + var (low, high) = options.DcConditioning; + foreach (var (j, c, x, y, firstRow) in Units(options.RestartInterval, () => + { + encoder.Restart(); + Array.Clear(statistics); + })) + { + var classA = x == 0 ? 0 : classes[(c, x - 1, y)]; + var classB = y == firstRow ? 0 : classes[(c, x, y - 1)]; + var difference = Difference(Sample(c, x, y), Predict(c, x, y, firstRow)); + EncodeValue(encoder, statistics, j * LosslessStatistics, (20 * classB) + (4 * classA), classB >= 3 ? 129 : 100, difference); + classes[(c, x, y)] = Classify(difference, low, high); + } + } + } +} diff --git a/tests/Febe.Tests/Imaging/PngCodecTests.cs b/tests/Febe.Tests/Imaging/PngCodecTests.cs new file mode 100644 index 0000000..32ad6cf --- /dev/null +++ b/tests/Febe.Tests/Imaging/PngCodecTests.cs @@ -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; + +/// The in-house PNG decoder and encoder, beyond the reference set: round trips, metadata, damaged files. +[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 = "Città è più"; + 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(() => PngEncoder.Encode(image, new PngEncoderOptions { Exif = [1, 2, 3, 4, 5, 6, 7, 8] })); + Assert.ThrowsExactly(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = "" })); + Assert.ThrowsExactly(() => PngEncoder.Encode(image, new PngEncoderOptions { IccProfile = [1], IccProfileName = new string('a', 80) })); + Assert.ThrowsExactly(() => 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(() => 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()); + var cases = new Dictionary + { + ["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(() => 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(() => 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(); + 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(() => 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(() => PngDecoder.Decode(png, new ImageLimits { MaxPixels = 2499 })); + Assert.ThrowsExactly(() => 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(() => pooled.Pixels.Length.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + + private static uint BitwiseCrc(ReadOnlySpan 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(); + } +} diff --git a/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs b/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs new file mode 100644 index 0000000..e889f00 --- /dev/null +++ b/tests/Febe.Tests/Imaging/ReferenceDecodeTests.cs @@ -0,0 +1,155 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// 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. +/// +[TestClass] +public sealed class ReferenceDecodeTests +{ + public static IEnumerable PngCases => ReferenceImages.NamesOf(ReferenceFormat.Png); + + public static IEnumerable GifCases => ReferenceImages.NamesOf(ReferenceFormat.Gif); + + public static IEnumerable 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(() => 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 decode) + { + var reference = ReferenceImages.Get(name); + using var expected = PngDecoder.Decode(reference.ReadExpectedPng()); + using var actual = decode(reference.ReadInput()); + ImageAssert.AreEqual(expected, actual, name); + } + + /// + /// 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 . + /// + 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; + } +} diff --git a/tests/Febe.Tests/Imaging/ReferenceImages.cs b/tests/Febe.Tests/Imaging/ReferenceImages.cs new file mode 100644 index 0000000..e07f48e --- /dev/null +++ b/tests/Febe.Tests/Imaging/ReferenceImages.cs @@ -0,0 +1,170 @@ +namespace Febe.Tests.Imaging; + +/// The format of a reference case's input file, from its extension. +public enum ReferenceFormat +{ + Png, + Jpeg, + WebP, + Gif, + Bmp, +} + +/// +/// One case of the reference set in Imaging/Riferimenti (see LEGGIMI.md there): an input file and, beside it, +/// «.atteso.png», SkiaSharp's straight (unpremultiplied) RGBA8 decode of it, upright. +/// +/// The folder of the set. +/// The case name, as elenco.txt lists it. +/// The format of the input file. +/// The input file name, inside . +/// Width of the expected image (after the EXIF orientation, for a JPEG that has one). +/// Height of the expected image (after the EXIF orientation, for a JPEG that has one). +public sealed record ReferenceCase(string Folder, string Name, ReferenceFormat Format, string InputFileName, int Width, int Height) +{ + /// Full path of the input file. + public string InputPath => Path.Combine(Folder, InputFileName); + + /// Full path of the expected image («.atteso.png»). + public string ExpectedPath => Path.Combine(Folder, Name + ReferenceImages.ExpectedSuffix); + + /// + /// 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. + /// + public int Orientation => + Name.StartsWith(ReferenceImages.OrientationPrefix, StringComparison.Ordinal) + ? int.Parse(Name.AsSpan(ReferenceImages.OrientationPrefix.Length), System.Globalization.CultureInfo.InvariantCulture) + : 1; + + /// Width of the image as stored in the input file (orientations 5-8 swap the two sides). + public int StoredWidth => Orientation >= 5 ? Height : Width; + + /// Height of the image as stored in the input file (orientations 5-8 swap the two sides). + public int StoredHeight => Orientation >= 5 ? Width : Height; + + /// The bytes of the input file. + public byte[] ReadInput() => File.ReadAllBytes(InputPath); + + /// + /// 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. + /// + public byte[] ReadExpectedPng() => File.ReadAllBytes(ExpectedPath); + + /// + public override string ToString() => Name; +} + +/// Loads the reference set of the in-house image codecs from the test output folder. +public static class ReferenceImages +{ + /// Suffix of the expected images. + public const string ExpectedSuffix = ".atteso.png"; + + /// The list of the cases, one «name WxH» per line. + public const string ListFileName = "elenco.txt"; + + /// The description of the set. + public const string ReadmeFileName = "LEGGIMI.md"; + + /// Name prefix of the JPEG cases with an EXIF orientation. + 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), + ]; + + /// The folder of the set in the test output (copied there by Febe.Tests.csproj). + public static string Folder { get; } = Path.Combine(AppContext.BaseDirectory, "Imaging", "Riferimenti"); + + private static readonly Lazy> Cases = new(() => Load(Folder)); + + /// Every case, in the order of elenco.txt. + public static IReadOnlyList All => Cases.Value; + + /// The case with that name. + 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}."); + } + + /// The cases whose input has that format. + public static IEnumerable Of(ReferenceFormat format) => All.Where(c => c.Format == format); + + /// + /// The case names of a format, for [DynamicData]: the test receives the name and calls , + /// so each case shows up as its own row in the results. + /// + public static IEnumerable NamesOf(ReferenceFormat format) => Of(format).Select(c => new object[] { c.Name }); + + /// The input formats, with their extensions. + public static IReadOnlyList<(string Extension, ReferenceFormat Format)> Extensions => InputExtensions; + + /// Reads elenco.txt in and finds the input file of every case. + public static IReadOnlyList Load(string folder) + { + var list = new List(); + var seen = new HashSet(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; + } +} diff --git a/tests/Febe.Tests/Imaging/ReferenceSetTests.cs b/tests/Febe.Tests/Imaging/ReferenceSetTests.cs new file mode 100644 index 0000000..0605eea --- /dev/null +++ b/tests/Febe.Tests/Imaging/ReferenceSetTests.cs @@ -0,0 +1,329 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Tests.Imaging; + +/// +/// 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: reads them with Febe's own PNG decoder +/// (step 2 of track C1), without SkiaSharp. +/// +[TestClass] +public sealed class ReferenceSetTests +{ + /// The number of cases SkiaSharp's references were made for (LEGGIMI.md lists them). + private const int CaseCount = 57; + + [TestMethod] + public void TheListNamesEveryFileOfTheFolderAndNothingElse() + { + var cases = ReferenceImages.All; + Assert.HasCount(CaseCount, cases); + + var expectedFiles = new HashSet(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..])); + } + + /// Walks the chunks of a PNG, checking signature, lengths, CRCs and that IEND ends the file. + private static List<(string Type, int Offset, int Length)> PngChunks(string name, byte[] bytes) + { + ReadOnlySpan 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."); + } + + /// The marker segments of a JPEG up to the start of scan: marker, offset and length of the payload. + 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; + } + } + + /// The Orientation tag (0x0112) of IFD0 of an EXIF TIFF block, 1 when absent. + private static int ExifOrientation(string name, ReadOnlySpan tiff) + { + var bigEndian = tiff.StartsWith("MM"u8); + Assert.IsTrue(bigEndian || tiff.StartsWith("II"u8), $"{name}: TIFF byte order."); + int U16(ReadOnlySpan 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)[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 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 type, ReadOnlySpan 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; + } +} diff --git a/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md b/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md new file mode 100644 index 0000000..75df413 --- /dev/null +++ b/tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md @@ -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. diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-1.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-1.atteso.png new file mode 100644 index 0000000..aca8f6f Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-1.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-1.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-1.bmp new file mode 100644 index 0000000..7b858cd Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-1.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-555.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-555.atteso.png new file mode 100644 index 0000000..1e749b2 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-555.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-555.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-555.bmp new file mode 100644 index 0000000..894c7b8 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-555.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-565.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-565.atteso.png new file mode 100644 index 0000000..c4264a5 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-565.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-565.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-565.bmp new file mode 100644 index 0000000..2c3e342 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-16-565.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-24-dall-alto.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24-dall-alto.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24-dall-alto.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-24-dall-alto.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24-dall-alto.bmp new file mode 100644 index 0000000..00018a0 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24-dall-alto.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-24.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-24.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24.bmp new file mode 100644 index 0000000..ee6c37a Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-24.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-campi-v5.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-campi-v5.atteso.png new file mode 100644 index 0000000..f6f33f9 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-campi-v5.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-campi-v5.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-campi-v5.bmp new file mode 100644 index 0000000..1d5c92a Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-campi-v5.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-senza-alfa.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-senza-alfa.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-senza-alfa.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-senza-alfa.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-senza-alfa.bmp new file mode 100644 index 0000000..5be0953 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-32-senza-alfa.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-4.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-4.atteso.png new file mode 100644 index 0000000..589d6c9 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-4.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-4.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-4.bmp new file mode 100644 index 0000000..62aba83 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-4.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-8.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-8.atteso.png new file mode 100644 index 0000000..97baf36 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-8.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-8.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-8.bmp new file mode 100644 index 0000000..ad5d7c5 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-8.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle4.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle4.atteso.png new file mode 100644 index 0000000..5fca05b Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle4.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle4.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle4.bmp new file mode 100644 index 0000000..9544677 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle4.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle8.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle8.atteso.png new file mode 100644 index 0000000..8d7cf3b Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle8.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle8.bmp b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle8.bmp new file mode 100644 index 0000000..9ea6e07 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/bmp-rle8.bmp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/elenco.txt b/tests/Febe.Tests/Imaging/Riferimenti/elenco.txt new file mode 100644 index 0000000..9c030b1 --- /dev/null +++ b/tests/Febe.Tests/Imaging/Riferimenti/elenco.txt @@ -0,0 +1,57 @@ +png-tav-1 101x67 +png-tav-2 101x67 +png-tav-4-trns 101x67 +png-tav-8-trns 101x67 +png-tav-4-adam7 101x67 +png-grigio-1 101x67 +png-grigio-2 101x67 +png-grigio-4 101x67 +png-grigio-8 101x67 +png-grigio-16 101x67 +png-grigio-16-adam7 101x67 +png-grigio-8-trns 101x67 +png-grigioalfa-8 101x67 +png-grigioalfa-16 101x67 +png-rgb-8 101x67 +png-rgb-8-trns 101x67 +png-rgb-16 101x67 +png-rgba-8 101x67 +png-rgba-16 101x67 +png-rgba-8-adam7 101x67 +png-skia-rgba 101x67 +png-skia-rgb 101x67 +jpeg-420-q90 101x67 +jpeg-422-q75 101x67 +jpeg-444-q95 101x67 +jpeg-420-q40 101x67 +jpeg-grigio-q85 101x67 +webp-perdita-q80 101x67 +webp-perdita-q30 101x67 +webp-perdita-alfa-q80 101x67 +webp-senza-perdita 101x67 +webp-senza-perdita-opaco 101x67 +webp-senza-perdita-rapido 101x67 +jpeg-grande-420-q85 333x250 +webp-grande-perdita-q75 333x250 +webp-grande-senza-perdita 333x250 +jpeg-orientamento-2 101x67 +jpeg-orientamento-3 101x67 +jpeg-orientamento-5 67x101 +jpeg-orientamento-6 67x101 +jpeg-orientamento-7 67x101 +jpeg-orientamento-8 67x101 +gif-globale 101x67 +gif-locale-interlacciata 101x67 +gif-animata 101x67 +gif-2-colori 101x67 +bmp-24 101x67 +bmp-24-dall-alto 101x67 +bmp-32-campi-v5 101x67 +bmp-32-senza-alfa 101x67 +bmp-16-565 101x67 +bmp-16-555 101x67 +bmp-8 101x67 +bmp-4 101x67 +bmp-1 101x67 +bmp-rle8 101x67 +bmp-rle4 101x67 diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-2-colori.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/gif-2-colori.atteso.png new file mode 100644 index 0000000..b5be7a2 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-2-colori.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-2-colori.gif b/tests/Febe.Tests/Imaging/Riferimenti/gif-2-colori.gif new file mode 100644 index 0000000..9fe6393 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-2-colori.gif differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-animata.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/gif-animata.atteso.png new file mode 100644 index 0000000..7600b12 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-animata.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-animata.gif b/tests/Febe.Tests/Imaging/Riferimenti/gif-animata.gif new file mode 100644 index 0000000..b01f82e Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-animata.gif differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-globale.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/gif-globale.atteso.png new file mode 100644 index 0000000..effcc8a Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-globale.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-globale.gif b/tests/Febe.Tests/Imaging/Riferimenti/gif-globale.gif new file mode 100644 index 0000000..d962a6b Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-globale.gif differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-locale-interlacciata.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/gif-locale-interlacciata.atteso.png new file mode 100644 index 0000000..a4f9c32 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-locale-interlacciata.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/gif-locale-interlacciata.gif b/tests/Febe.Tests/Imaging/Riferimenti/gif-locale-interlacciata.gif new file mode 100644 index 0000000..092990f Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/gif-locale-interlacciata.gif differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q40.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q40.atteso.png new file mode 100644 index 0000000..1acc924 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q40.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q40.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q40.jpg new file mode 100644 index 0000000..c6d7af4 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q40.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q90.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q90.atteso.png new file mode 100644 index 0000000..0b1ac26 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q90.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q90.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q90.jpg new file mode 100644 index 0000000..65affc5 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-420-q90.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-422-q75.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-422-q75.atteso.png new file mode 100644 index 0000000..bb2ee67 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-422-q75.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-422-q75.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-422-q75.jpg new file mode 100644 index 0000000..4fd3033 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-422-q75.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-444-q95.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-444-q95.atteso.png new file mode 100644 index 0000000..323e7db Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-444-q95.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-444-q95.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-444-q95.jpg new file mode 100644 index 0000000..93174cc Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-444-q95.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grande-420-q85.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grande-420-q85.atteso.png new file mode 100644 index 0000000..0eb3199 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grande-420-q85.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grande-420-q85.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grande-420-q85.jpg new file mode 100644 index 0000000..cc13998 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grande-420-q85.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grigio-q85.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grigio-q85.atteso.png new file mode 100644 index 0000000..254ee31 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grigio-q85.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grigio-q85.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grigio-q85.jpg new file mode 100644 index 0000000..0e401ce Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-grigio-q85.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-2.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-2.atteso.png new file mode 100644 index 0000000..56e4889 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-2.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-2.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-2.jpg new file mode 100644 index 0000000..356d8a7 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-2.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-3.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-3.atteso.png new file mode 100644 index 0000000..af79b7f Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-3.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-3.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-3.jpg new file mode 100644 index 0000000..0f4f3ce Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-3.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-5.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-5.atteso.png new file mode 100644 index 0000000..e4bec63 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-5.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-5.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-5.jpg new file mode 100644 index 0000000..8b1d492 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-5.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-6.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-6.atteso.png new file mode 100644 index 0000000..010b057 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-6.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-6.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-6.jpg new file mode 100644 index 0000000..7464f5d Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-6.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-7.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-7.atteso.png new file mode 100644 index 0000000..790de9c Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-7.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-7.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-7.jpg new file mode 100644 index 0000000..ac05575 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-7.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-8.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-8.atteso.png new file mode 100644 index 0000000..a475f43 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-8.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-8.jpg b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-8.jpg new file mode 100644 index 0000000..82941f3 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/jpeg-orientamento-8.jpg differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-1.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-1.atteso.png new file mode 100644 index 0000000..c34dc9a Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-1.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-1.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-1.png new file mode 100644 index 0000000..29c44bb Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-1.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16-adam7.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16-adam7.atteso.png new file mode 100644 index 0000000..cda3084 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16-adam7.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16-adam7.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16-adam7.png new file mode 100644 index 0000000..ed568ef Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16-adam7.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16.atteso.png new file mode 100644 index 0000000..cda3084 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16.png new file mode 100644 index 0000000..03e2b92 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-16.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-2.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-2.atteso.png new file mode 100644 index 0000000..7e3e01b Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-2.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-2.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-2.png new file mode 100644 index 0000000..529b2a2 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-2.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-4.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-4.atteso.png new file mode 100644 index 0000000..047ce6b Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-4.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-4.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-4.png new file mode 100644 index 0000000..b94ef90 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-4.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8-trns.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8-trns.atteso.png new file mode 100644 index 0000000..f11ce4e Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8-trns.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8-trns.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8-trns.png new file mode 100644 index 0000000..0a3a5d0 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8-trns.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8.atteso.png new file mode 100644 index 0000000..cda3084 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8.png new file mode 100644 index 0000000..0ff8fd2 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigio-8.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-16.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-16.atteso.png new file mode 100644 index 0000000..c5e64a3 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-16.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-16.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-16.png new file mode 100644 index 0000000..8a837bf Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-16.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-8.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-8.atteso.png new file mode 100644 index 0000000..c5e64a3 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-8.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-8.png b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-8.png new file mode 100644 index 0000000..2f00d62 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-grigioalfa-8.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-16.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-16.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-16.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-16.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-16.png new file mode 100644 index 0000000..6cba0da Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-16.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8-trns.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8-trns.atteso.png new file mode 100644 index 0000000..a9142ef Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8-trns.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8-trns.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8-trns.png new file mode 100644 index 0000000..d3b08c2 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8-trns.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8.png new file mode 100644 index 0000000..528a566 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgb-8.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-16.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-16.atteso.png new file mode 100644 index 0000000..f6f33f9 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-16.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-16.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-16.png new file mode 100644 index 0000000..e70ebc3 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-16.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8-adam7.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8-adam7.atteso.png new file mode 100644 index 0000000..f6f33f9 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8-adam7.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8-adam7.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8-adam7.png new file mode 100644 index 0000000..e2dd5ee Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8-adam7.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8.atteso.png new file mode 100644 index 0000000..f6f33f9 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8.png b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8.png new file mode 100644 index 0000000..db0ec31 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-rgba-8.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgb.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgb.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgb.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgb.png b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgb.png new file mode 100644 index 0000000..223633a Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgb.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgba.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgba.atteso.png new file mode 100644 index 0000000..f6f33f9 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgba.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgba.png b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgba.png new file mode 100644 index 0000000..440b672 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-skia-rgba.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-1.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-1.atteso.png new file mode 100644 index 0000000..124885f Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-1.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-1.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-1.png new file mode 100644 index 0000000..cf2febd Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-1.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-2.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-2.atteso.png new file mode 100644 index 0000000..21b5d92 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-2.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-2.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-2.png new file mode 100644 index 0000000..432142e Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-2.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-adam7.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-adam7.atteso.png new file mode 100644 index 0000000..3a6a42c Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-adam7.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-adam7.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-adam7.png new file mode 100644 index 0000000..378b1f2 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-adam7.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-trns.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-trns.atteso.png new file mode 100644 index 0000000..d4dab7f Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-trns.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-trns.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-trns.png new file mode 100644 index 0000000..d45c39a Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-4-trns.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-8-trns.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-8-trns.atteso.png new file mode 100644 index 0000000..355b80b Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-8-trns.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/png-tav-8-trns.png b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-8-trns.png new file mode 100644 index 0000000..b4283d4 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/png-tav-8-trns.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-perdita-q75.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-perdita-q75.atteso.png new file mode 100644 index 0000000..e983c99 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-perdita-q75.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-perdita-q75.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-perdita-q75.webp new file mode 100644 index 0000000..704d6e7 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-perdita-q75.webp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-senza-perdita.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-senza-perdita.atteso.png new file mode 100644 index 0000000..ba1593d Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-senza-perdita.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-senza-perdita.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-senza-perdita.webp new file mode 100644 index 0000000..d56d0fd Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-grande-senza-perdita.webp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-alfa-q80.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-alfa-q80.atteso.png new file mode 100644 index 0000000..aced703 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-alfa-q80.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-alfa-q80.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-alfa-q80.webp new file mode 100644 index 0000000..0540625 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-alfa-q80.webp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q30.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q30.atteso.png new file mode 100644 index 0000000..3f51143 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q30.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q30.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q30.webp new file mode 100644 index 0000000..1838d6d Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q30.webp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q80.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q80.atteso.png new file mode 100644 index 0000000..bff5807 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q80.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q80.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q80.webp new file mode 100644 index 0000000..f59fa30 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-perdita-q80.webp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-opaco.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-opaco.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-opaco.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-opaco.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-opaco.webp new file mode 100644 index 0000000..50c396b Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-opaco.webp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-rapido.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-rapido.atteso.png new file mode 100644 index 0000000..0e37bb6 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-rapido.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-rapido.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-rapido.webp new file mode 100644 index 0000000..142c7a0 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita-rapido.webp differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita.atteso.png b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita.atteso.png new file mode 100644 index 0000000..3da4f78 Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita.atteso.png differ diff --git a/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita.webp b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita.webp new file mode 100644 index 0000000..12d9c6c Binary files /dev/null and b/tests/Febe.Tests/Imaging/Riferimenti/webp-senza-perdita.webp differ diff --git a/tests/Febe.Tests/Imaging/TestImages.cs b/tests/Febe.Tests/Imaging/TestImages.cs new file mode 100644 index 0000000..de61153 --- /dev/null +++ b/tests/Febe.Tests/Imaging/TestImages.cs @@ -0,0 +1,301 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using System.Text; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// Small images and files built by the tests: random RGBA images from a fixed seed, and PNG, GIF and BMP files written +/// byte by byte from the specifications, to reach the cases the reference set does not have (damaged files above all). +/// +internal static class TestImages +{ + /// An image of random pixels; forces alpha 255. + public static RgbaImage Random(int width, int height, int seed, bool opaque = false) + { + var random = new Random(seed); + var pixels = new byte[width * height * 4]; + random.NextBytes(pixels); + if (opaque) + { + for (var i = 3; i < pixels.Length; i += 4) + { + pixels[i] = 255; + } + } + + return new RgbaImage(width, height, pixels); + } + + /// A smooth image (gradients and a little noise), the kind adaptive filtering is for. + public static RgbaImage Gradient(int width, int height, int seed) + { + var random = new Random(seed); + var image = new RgbaImage(width, height); + for (var y = 0; y < height; y++) + { + var row = image.GetRow(y); + for (var x = 0; x < width; x++) + { + row[x * 4] = (byte)(x * 255 / Math.Max(1, width - 1)); + row[(x * 4) + 1] = (byte)(y * 255 / Math.Max(1, height - 1)); + row[(x * 4) + 2] = (byte)((x + y + random.Next(3)) & 0xFF); + row[(x * 4) + 3] = (byte)(255 - (x & 0x3F)); + } + } + + return image; + } + + /// The chunks of a PNG: type and payload, in order (the CRC is checked). + public static List<(string Type, byte[] Payload)> PngChunks(byte[] png) + { + var chunks = new List<(string, byte[])>(); + var pos = 8; + while (pos < png.Length) + { + var length = (int)BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos)); + var type = Encoding.ASCII.GetString(png, pos + 4, 4); + Assert.AreEqual(Crc32.Compute(png.AsSpan(pos + 4, length + 4)), BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos + 8 + length)), $"CRC di {type}"); + chunks.Add((type, png.AsSpan(pos + 8, length).ToArray())); + pos += length + 12; + } + + return chunks; + } + + /// Writes a PNG from its chunks (signature and CRCs added). + public static byte[] Png(params (string Type, byte[] Payload)[] chunks) + { + using var output = new MemoryStream(); + output.Write([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + foreach (var (type, payload) in chunks) + { + output.Write(Chunk(type, payload)); + } + + return output.ToArray(); + } + + /// One chunk: length, type, payload, CRC. + public static byte[] Chunk(string type, byte[] payload) + { + var chunk = new byte[payload.Length + 12]; + BinaryPrimitives.WriteUInt32BigEndian(chunk, (uint)payload.Length); + Encoding.ASCII.GetBytes(type, chunk.AsSpan(4)); + payload.CopyTo(chunk, 8); + BinaryPrimitives.WriteUInt32BigEndian(chunk.AsSpan(8 + payload.Length), Crc32.Compute(chunk.AsSpan(4, payload.Length + 4))); + return chunk; + } + + /// An IHDR payload. + public static byte[] Ihdr(int width, int height, int depth, int colorType, int interlace = 0) + { + var payload = new byte[13]; + BinaryPrimitives.WriteUInt32BigEndian(payload, (uint)width); + BinaryPrimitives.WriteUInt32BigEndian(payload.AsSpan(4), (uint)height); + payload[8] = (byte)depth; + payload[9] = (byte)colorType; + payload[12] = (byte)interlace; + return payload; + } + + /// The zlib stream of . + public static byte[] Zlib(byte[] data) + { + using var output = new MemoryStream(); + using (var zlib = new ZLibStream(output, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(data); + } + + return output.ToArray(); + } + + /// Latin-1 bytes of a keyword or text. + public static byte[] Latin1(string text) => Encoding.Latin1.GetBytes(text); + + /// Concatenation of byte arrays. + public static byte[] Join(params byte[][] parts) => parts.SelectMany(p => p).ToArray(); + + /// Recomputes the CRC of every chunk of a PNG whose bytes were changed (stops at the first broken length). + public static void FixPngCrcs(byte[] png) + { + var pos = 8; + while (pos + 12 <= png.Length) + { + var length = BinaryPrimitives.ReadUInt32BigEndian(png.AsSpan(pos)); + if (length > png.Length - pos - 12) + { + return; + } + + BinaryPrimitives.WriteUInt32BigEndian(png.AsSpan(pos + 8 + (int)length), Crc32.Compute(png.AsSpan(pos + 4, (int)length + 4))); + pos += (int)length + 12; + } + } + + /// + /// GIF LZW data sub-blocks for that use only literal codes: a clear code every few + /// literals keeps the code size at + 1. Ends with the end code and the terminator. + /// + public static byte[] GifLiteralLzw(ReadOnlySpan indices, int minCodeSize) + { + var clear = 1 << minCodeSize; + var codeSize = minCodeSize + 1; + var perGroup = Math.Max(1, clear - 2); + var bits = new List(); + ulong accumulator = 0; + var count = 0; + void Emit(int code) + { + accumulator |= (ulong)code << count; + count += codeSize; + while (count >= 8) + { + bits.Add((byte)accumulator); + accumulator >>= 8; + count -= 8; + } + } + + for (var i = 0; i < indices.Length; i++) + { + if (i % perGroup == 0) + { + Emit(clear); + } + + Emit(indices[i]); + } + + Emit(clear + 1); + if (count > 0) + { + bits.Add((byte)accumulator); + } + + var output = new List(); + for (var i = 0; i < bits.Count; i += 255) + { + var n = Math.Min(255, bits.Count - i); + output.Add((byte)n); + output.AddRange(bits.GetRange(i, n)); + } + + output.Add(0); + return output.ToArray(); + } + + /// A GIF89a file: header, logical screen, optional global palette, then the given blocks and the trailer. + public static byte[] Gif(int width, int height, byte[]? globalPalette, params byte[][] blocks) + { + var output = new List(); + output.AddRange("GIF89a"u8.ToArray()); + output.AddRange(BitConverter.GetBytes((ushort)width)); + output.AddRange(BitConverter.GetBytes((ushort)height)); + output.Add(globalPalette is null ? (byte)0 : (byte)(0x80 | PaletteSizeBits(globalPalette))); + output.Add(0); + output.Add(0); + if (globalPalette is not null) + { + output.AddRange(globalPalette); + } + + foreach (var block in blocks) + { + output.AddRange(block); + } + + output.Add(0x3B); + return output.ToArray(); + } + + /// A graphic control extension with a transparent index (or none with -1). + public static byte[] GifControl(int transparent) => + [0x21, 0xF9, 4, transparent >= 0 ? (byte)1 : (byte)0, 0, 0, transparent >= 0 ? (byte)transparent : (byte)0, 0]; + + /// An image block: descriptor, optional local palette, LZW data of . + public static byte[] GifFrame(int left, int top, int width, int height, ReadOnlySpan indices, int minCodeSize, byte[]? localPalette = null, bool interlaced = false) + { + var output = new List { 0x2C }; + output.AddRange(BitConverter.GetBytes((ushort)left)); + output.AddRange(BitConverter.GetBytes((ushort)top)); + output.AddRange(BitConverter.GetBytes((ushort)width)); + output.AddRange(BitConverter.GetBytes((ushort)height)); + var packed = interlaced ? 0x40 : 0; + if (localPalette is not null) + { + packed |= 0x80 | PaletteSizeBits(localPalette); + } + + output.Add((byte)packed); + if (localPalette is not null) + { + output.AddRange(localPalette); + } + + output.Add((byte)minCodeSize); + output.AddRange(GifLiteralLzw(indices, minCodeSize)); + return output.ToArray(); + } + + private static int PaletteSizeBits(byte[] palette) + { + var entries = palette.Length / 3; + var bits = 0; + while ((2 << bits) < entries) + { + bits++; + } + + Assert.AreEqual(2 << bits, entries, "la tavolozza di un GIF ha 2, 4, 8... voci"); + return bits; + } + + /// + /// A BMP with an information header of bytes (40, 108, 124...; 12 for a core header), + /// then (masks, palette) and the pixel data. + /// + public static byte[] Bmp(int headerSize, int width, int height, int bitsPerPixel, uint compression, byte[] afterHeader, byte[] pixels, uint colorsUsed = 0, uint[]? masks = null) + { + var info = new byte[headerSize]; + BinaryPrimitives.WriteUInt32LittleEndian(info, (uint)headerSize); + if (headerSize == 12) + { + BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(4), (ushort)width); + BinaryPrimitives.WriteInt16LittleEndian(info.AsSpan(6), (short)height); + BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(8), 1); + BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(10), (ushort)bitsPerPixel); + } + else + { + BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(4), width); + BinaryPrimitives.WriteInt32LittleEndian(info.AsSpan(8), height); + BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(12), 1); + BinaryPrimitives.WriteUInt16LittleEndian(info.AsSpan(14), (ushort)bitsPerPixel); + BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(16), compression); + BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(20), (uint)pixels.Length); + BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(32), colorsUsed); + if (masks is not null) + { + for (var i = 0; i < masks.Length; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(info.AsSpan(40 + (i * 4)), masks[i]); + } + } + } + + var offset = 14 + headerSize + afterHeader.Length; + var file = new byte[offset + pixels.Length]; + file[0] = (byte)'B'; + file[1] = (byte)'M'; + BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(2), (uint)file.Length); + BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(10), (uint)offset); + info.CopyTo(file, 14); + afterHeader.CopyTo(file, 14 + headerSize); + pixels.CopyTo(file, offset); + return file; + } +} diff --git a/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs b/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs new file mode 100644 index 0000000..4dbbfbd --- /dev/null +++ b/tests/Febe.Tests/Imaging/Vp8BitstreamTests.cs @@ -0,0 +1,378 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The VP8 decoder on frames written by , for what the libwebp references do not reach: +/// the border rules of intra prediction, the token categories, several partitions, the skip flag, segment maps, +/// filter deltas and the simple loop filter (checked against a separate implementation of RFC 6386 §15.2). +/// +[TestClass] +public sealed class Vp8BitstreamTests +{ + [TestMethod] + public void TheBooleanCoderRoundTrips() + { + var random = new Random(21); + for (var round = 0; round < 20; round++) + { + var count = random.Next(1, 4000); + var probs = new int[count]; + var bits = new bool[count]; + var encoder = new Vp8BoolEncoder(); + for (var i = 0; i < count; i++) + { + probs[i] = random.Next(1, 256); + bits[i] = random.Next(256) >= probs[i]; + encoder.Write(probs[i], bits[i]); + } + + var data = encoder.Finish(); + var decoder = new Vp8BoolDecoder(data, 0, data.Length); + for (var i = 0; i < count; i++) + { + Assert.AreEqual(bits[i] ? 1 : 0, decoder.GetBit(probs[i]), $"giro {round}, bit {i}"); + } + + Assert.IsFalse(decoder.Overrun); + } + + // Reading on past the end is noticed. + var empty = new Vp8BoolDecoder([], 0, 0); + for (var i = 0; i < 40; i++) + { + empty.GetBit(128); + } + + Assert.IsTrue(empty.Overrun); + } + + [TestMethod] + public void PredictionFollowsTheBorderRules() + { + // 3×2 macroblocks, no residual, no loop filter: the pixels are the prediction alone. + Assert.AreEqual(128, Uniform(Vp8Tables.DcPred, Vp8Tables.DcPred).Y.Distinct().Single(), "DC senza vicini"); + Assert.AreEqual(127, Uniform(Vp8Tables.VPred, Vp8Tables.VPred).Y.Distinct().Single(), "sopra il fotogramma 127"); + Assert.AreEqual(129, Uniform(Vp8Tables.HPred, Vp8Tables.HPred).Y.Distinct().Single(), "a sinistra del fotogramma 129"); + Assert.AreEqual(129, Uniform(Vp8Tables.TmPred, Vp8Tables.TmPred).Y.Distinct().Single(), "TM: 129 + 127 − 127"); + var vertical = Uniform(Vp8Tables.VPred, Vp8Tables.VPred); + Assert.AreEqual(127, vertical.U.Distinct().Single()); + + // B_VE smooths the row above with the pixel above-left, which is 127 above the frame and 129 left of it: + // column 0 is avg3(127, 127, 127) in the first four rows and avg3(129, 127, 127) = 128 below. + var subVertical = Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BVe); + for (var y = 0; y < 32; y++) + { + Assert.AreEqual(y < 4 ? 127 : 128, subVertical.Y[y * 48], $"riga {y}"); + Assert.AreEqual(127, subVertical.Y[(y * 48) + 1], $"riga {y}"); + } + + // B_DC of the first subblock: (4·127 + 4·129 + 4) >> 3; B_HE and B_TM next to the left border: 129. + Assert.AreEqual(128, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BDc).Y[0]); + Assert.AreEqual(129, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BHe).Y[0]); + Assert.AreEqual(129, Uniform(Vp8Tables.BPred, Vp8Tables.DcPred, Vp8Tables.BTm).Y[0]); + } + + [TestMethod] + public void TokenCategoriesCarryTheirValues() + { + // Base quantizer 0: Y DC step 4, Y2 DC step 8. A DC-only block adds (level·4 + 4) >> 3 to the prediction 128. + foreach (var level in (int[])[1, -1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 18, 19, 34, 35, 66, 67, 300, -2114, 2114]) + { + var mbs = Vp8TestWriter.Uniform(1, Vp8Tables.BPred, Vp8Tables.DcPred); + mbs[0].Skip = false; + mbs[0].Levels[0][0] = level; + var planes = Planes(new Vp8TestWriter { Width = 16, Height = 16, BaseQ = 0 }.Write(mbs)); + var expected = Math.Clamp(128 + (((level * 4) + 4) >> 3), 0, 255); + Assert.AreEqual(expected, planes.Y[0], $"livello {level}"); + Assert.AreEqual(expected, planes.Y[(3 * 16) + 3], $"livello {level}"); + } + + // Y2: the inverse WHT of a DC of 8·16 gives 16 to every luma block, which adds (16 + 4) >> 3 = 2. + var whole = Vp8TestWriter.Uniform(1, Vp8Tables.DcPred, Vp8Tables.DcPred); + whole[0].Skip = false; + whole[0].Levels[24][0] = 16; + Assert.AreEqual(130, Planes(new Vp8TestWriter { Width = 16, Height = 16, BaseQ = 0 }.Write(whole)).Y.Distinct().Single()); + } + + [TestMethod] + public void PartitionsDoNotChangeThePicture() + { + var mbs = Vp8TestWriter.Random(7 * 5, seed: 31); + var expected = Planes(new Vp8TestWriter { Width = 100, Height = 70, FilterLevel = 20, Sharpness = 2 }.Write(mbs)); + for (var log2 = 1; log2 <= 3; log2++) + { + var actual = Planes(new Vp8TestWriter { Width = 100, Height = 70, FilterLevel = 20, Sharpness = 2, Log2Partitions = log2 }.Write(mbs)); + AssertSamePlanes(expected, actual, $"{1 << log2} partizioni"); + } + } + + [TestMethod] + public void TheSkipFlagAndEmptyBlocksAgree() + { + var mbs = Vp8TestWriter.Random(6 * 4, seed: 32, skips: false); + for (var i = 0; i < mbs.Length; i += 3) + { + foreach (var block in mbs[i].Levels) + { + Array.Clear(block); + } + + mbs[i].Skip = true; + } + + var skipped = Planes(new Vp8TestWriter { Width = 90, Height = 60, FilterLevel = 30 }.Write(mbs)); + var explicitEmpty = Planes(new Vp8TestWriter { Width = 90, Height = 60, FilterLevel = 30, UseSkipProb = false }.Write(mbs)); + AssertSamePlanes(skipped, explicitEmpty, "salto contro blocchi vuoti"); + } + + [TestMethod] + public void SegmentsWithTheBaseValuesChangeNothing() + { + var mbs = Vp8TestWriter.Random(5 * 5, seed: 33); + var plain = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50 }.Write(mbs)); + var deltas = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50, Segmentation = true, UpdateMap = true, SegmentProbs = [90, 140, 200] }.Write(mbs)); + AssertSamePlanes(plain, deltas, "segmenti con differenze nulle"); + var absolute = Planes(new Vp8TestWriter + { + Width = 80, + Height = 80, + FilterLevel = 25, + BaseQ = 50, + Segmentation = true, + UpdateMap = true, + AbsoluteDeltas = true, + SegmentQuant = [50, 50, 50, 50], + SegmentFilter = [25, 25, 25, 25], + }.Write(mbs)); + AssertSamePlanes(plain, absolute, "segmenti con valori assoluti uguali"); + + // Different quantizers per segment do change the picture. + var different = Planes(new Vp8TestWriter { Width = 80, Height = 80, FilterLevel = 25, BaseQ = 50, Segmentation = true, UpdateMap = true, SegmentQuant = [0, 10, -20, 30] }.Write(mbs)); + Assert.IsFalse(plain.Y.AsSpan().SequenceEqual(different.Y)); + } + + [TestMethod] + public void AFrameLevelOfZeroTurnsTheFilterOffWhateverSegmentsAndDeltasSay() + { + var mbs = Vp8TestWriter.Random(5 * 4, seed: 36); + var none = Planes(new Vp8TestWriter { Width = 80, Height = 64 }.Write(mbs)); + + // Absolute segment strengths above zero, relative ones above zero, and positive ref/mode deltas: with + // loop_filter_level 0 the reference decoders filter nothing. + var absolute = new Vp8TestWriter + { + Width = 80, + Height = 64, + Segmentation = true, + UpdateMap = true, + AbsoluteDeltas = true, + SegmentQuant = [40, 40, 40, 40], // the base quantizer, as absolute values + SegmentFilter = [20, 35, 50, 63], + }; + var relative = new Vp8TestWriter { Width = 80, Height = 64, Segmentation = true, UpdateMap = true, SegmentFilter = [20, 35, 50, 63] }; + var deltas = new Vp8TestWriter { Width = 80, Height = 64, RefLfDelta = [30, 0, 0, 0], ModeLfDelta = [30, 0, 0, 0] }; + foreach (var (writer, what) in new[] { (absolute, "segmenti assoluti"), (relative, "segmenti relativi"), (deltas, "differenze") }) + { + AssertSamePlanes(none, Planes(writer.Write(mbs)), what); + } + + // The same segment strengths with a frame level above zero do filter. + var filtered = Planes(new Vp8TestWriter + { + Width = 80, + Height = 64, + FilterLevel = 1, + Segmentation = true, + UpdateMap = true, + AbsoluteDeltas = true, + SegmentQuant = [40, 40, 40, 40], + SegmentFilter = [20, 35, 50, 63], + }.Write(mbs)); + Assert.IsFalse(none.Y.AsSpan().SequenceEqual(filtered.Y), "con un livello del fotogramma il filtro lavora"); + } + + [TestMethod] + public void FilterDeltasMoveTheLevel() + { + var unfiltered = Vp8TestWriter.Random(4 * 3, seed: 34); + var none = Planes(new Vp8TestWriter { Width = 64, Height = 48 }.Write(unfiltered)); + var cancelled = Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, RefLfDelta = [-30, 5, 5, 5] }.Write(unfiltered)); + AssertSamePlanes(none, cancelled, "livello annullato dalla differenza del riferimento intra"); + + // The mode delta of B_PRED: on a frame of B_PRED macroblocks it cancels the level, on 16×16 ones it does not. + var subblocks = Vp8TestWriter.Random(4 * 3, seed: 35); + var sixteen = Vp8TestWriter.Random(4 * 3, seed: 35); + foreach (var mb in subblocks) + { + mb.YMode = Vp8Tables.BPred; + } + + foreach (var mb in sixteen) + { + mb.YMode = Vp8Tables.TmPred; + } + + AssertSamePlanes( + Planes(new Vp8TestWriter { Width = 64, Height = 48 }.Write(subblocks)), + Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, ModeLfDelta = [-30, 0, 0, 0] }.Write(subblocks)), + "B_PRED"); + AssertSamePlanes( + Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30 }.Write(sixteen)), + Planes(new Vp8TestWriter { Width = 64, Height = 48, FilterLevel = 30, ModeLfDelta = [-30, 0, 0, 0] }.Write(sixteen)), + "16×16"); + } + + [TestMethod] + public void TheSimpleFilterMatchesASeparateImplementation() + { + foreach (var (level, sharpness, seed) in new[] { (10, 0, 40), (32, 3, 41), (63, 7, 42), (45, 5, 43) }) + { + var mbs = Vp8TestWriter.Random(6 * 4, seed); + var raw = Planes(new Vp8TestWriter { Width = 96, Height = 64 }.Write(mbs)); + var filtered = Planes(new Vp8TestWriter { Width = 96, Height = 64, SimpleFilter = true, FilterLevel = level, Sharpness = sharpness }.Write(mbs)); + var expected = raw.Y.ToArray(); + SimpleFilter(expected, raw.YStride, 6, 4, mbs, level, sharpness); + CollectionAssert.AreEqual(expected, filtered.Y, $"livello {level}, nitidezza {sharpness}"); + CollectionAssert.AreEqual(raw.U, filtered.U, "il filtro semplice non tocca la crominanza"); + CollectionAssert.AreEqual(raw.V, filtered.V); + Assert.IsFalse(raw.Y.AsSpan().SequenceEqual(filtered.Y), "il filtro deve aver cambiato qualcosa"); + } + } + + [TestMethod] + public void RandomFramesDecodeThroughTheContainer() + { + for (var seed = 50; seed < 60; seed++) + { + var random = new Random(seed); + var width = random.Next(1, 120); + var height = random.Next(1, 90); + var writer = new Vp8TestWriter + { + Width = width, + Height = height, + FilterLevel = random.Next(64), + Sharpness = random.Next(8), + SimpleFilter = random.Next(2) == 0, + Log2Partitions = random.Next(4), + BaseQ = random.Next(128), + QDeltas = [random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16), random.Next(-15, 16)], + Segmentation = random.Next(2) == 0, + UpdateMap = true, + SegmentQuant = [random.Next(-30, 30), random.Next(-30, 30), random.Next(-30, 30), random.Next(-30, 30)], + SegmentFilter = [random.Next(-20, 20), random.Next(-20, 20), random.Next(-20, 20), random.Next(-20, 20)], + }; + var frame = writer.Write(Vp8TestWriter.Random(writer.MbWidth * writer.MbHeight, seed, maxLevel: 2114)); + var file = WebPTestFiles.Riff(("VP8 ", frame)); + using var image = WebPDecoder.Decode(file); + Assert.AreEqual((width, height), (image.Width, image.Height)); + Assert.IsTrue(image.IsOpaque()); + } + } + + // RFC 6386 §15.2 and §15.1, written apart from the decoder: the simple filter over the luma plane, macroblock + // after macroblock, left edge, inner vertical edges, top edge, inner horizontal edges. + private static void SimpleFilter(byte[] y, int stride, int mbWidth, int mbHeight, Vp8TestMacroblock[] mbs, int level, int sharpness) + { + var interior = level; + if (sharpness > 0) + { + interior >>= sharpness > 4 ? 2 : 1; + interior = Math.Min(interior, 9 - sharpness); + } + + interior = Math.Max(interior, 1); + var mbLimit = ((level + 2) * 2) + interior; + var subLimit = (level * 2) + interior; + for (var mbY = 0; mbY < mbHeight; mbY++) + { + for (var mbX = 0; mbX < mbWidth; mbX++) + { + var mb = mbs[(mbY * mbWidth) + mbX]; + var inner = mb.YMode == Vp8Tables.BPred || HasCoefficients(mb); + var x0 = mbX * 16; + var y0 = mbY * 16; + for (var edge = 0; edge < 16; edge += 4) + { + if ((edge == 0 && mbX > 0) || (edge > 0 && inner)) + { + for (var r = 0; r < 16; r++) + { + Segment(y, ((y0 + r) * stride) + x0 + edge, 1, edge == 0 ? mbLimit : subLimit); + } + } + } + + for (var edge = 0; edge < 16; edge += 4) + { + if ((edge == 0 && mbY > 0) || (edge > 0 && inner)) + { + for (var c = 0; c < 16; c++) + { + Segment(y, ((y0 + edge) * stride) + x0 + c, stride, edge == 0 ? mbLimit : subLimit); + } + } + } + } + } + } + + private static void Segment(byte[] y, int q0At, int step, int edgeLimit) + { + int p1 = y[q0At - (2 * step)] - 128, p0 = y[q0At - step] - 128, q0 = y[q0At] - 128, q1 = y[q0At + step] - 128; + if ((Math.Abs(p0 - q0) * 2) + (Math.Abs(p1 - q1) >> 1) > edgeLimit) + { + return; + } + + static int C(int v) => Math.Clamp(v, -128, 127); + var a = C(C(p1 - q1) + (3 * (q0 - p0))); + var b = C(a + 3) >> 3; + a = C(a + 4) >> 3; + y[q0At] = (byte)(C(q0 - a) + 128); + y[q0At - step] = (byte)(C(p0 + b) + 128); + } + + private static bool HasCoefficients(Vp8TestMacroblock mb) + { + if (mb.Skip) + { + return false; + } + + var i16 = mb.YMode != Vp8Tables.BPred; + for (var b = 0; b < 25; b++) + { + var levels = mb.Levels[b]; + var first = i16 && b < 16 ? 1 : 0; + if (b == 24 && !i16) + { + continue; + } + + for (var n = first; n < 16; n++) + { + if (levels[n] != 0) + { + return true; + } + } + } + + return false; + } + + private static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) Uniform(int yMode, int uvMode, int bMode = Vp8Tables.BDc) => + Planes(new Vp8TestWriter { Width = 48, Height = 32 }.Write(Vp8TestWriter.Uniform(6, yMode, uvMode, bMode))); + + private static (byte[] Y, byte[] U, byte[] V, int YStride, int UvStride) Planes(byte[] frame) => + Vp8Decoder.DecodePlanes(frame, 0, frame.Length, ImageLimits.Default); + + private static void AssertSamePlanes((byte[] Y, byte[] U, byte[] V, int, int) expected, (byte[] Y, byte[] U, byte[] V, int, int) actual, string what) + { + CollectionAssert.AreEqual(expected.Y, actual.Y, $"{what}: Y"); + CollectionAssert.AreEqual(expected.U, actual.U, $"{what}: U"); + CollectionAssert.AreEqual(expected.V, actual.V, $"{what}: V"); + } +} diff --git a/tests/Febe.Tests/Imaging/Vp8TestWriter.cs b/tests/Febe.Tests/Imaging/Vp8TestWriter.cs new file mode 100644 index 0000000..c25edd8 --- /dev/null +++ b/tests/Febe.Tests/Imaging/Vp8TestWriter.cs @@ -0,0 +1,596 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The boolean entropy encoder of RFC 6386 §7.3 (write_bool, add_one_to_output, flush_bool_encoder), for the tests. +/// +internal sealed class Vp8BoolEncoder +{ + private readonly List _output = []; + private uint _range = 255; + private uint _bottom; + private int _bitCount = 24; + + public void Write(int prob, bool value) + { + var split = 1 + (((_range - 1) * (uint)prob) >> 8); + if (value) + { + _bottom += split; + _range -= split; + } + else + { + _range = split; + } + + while (_range < 128) + { + _range <<= 1; + if ((_bottom & (1u << 31)) != 0) + { + AddOne(); + } + + _bottom <<= 1; + if (--_bitCount == 0) + { + _output.Add((byte)(_bottom >> 24)); + _bottom &= (1 << 24) - 1; + _bitCount = 8; + } + } + } + + public void Write(int prob, int value) => Write(prob, value != 0); + + public void Literal(int value, int bits) + { + for (var b = bits - 1; b >= 0; b--) + { + Write(128, (value >> b) & 1); + } + } + + /// A flag, then (when the value is not 0) magnitude and sign, as the frame header writes deltas. + public void OptionalSigned(int value, int bits) + { + Write(128, value != 0); + if (value != 0) + { + Literal(Math.Abs(value), bits); + Write(128, value < 0); + } + } + + public void Tree(ReadOnlySpan tree, ReadOnlySpan probs, int offset, int leaf) + { + Span path = stackalloc int[16]; + var depth = FindPath(tree, 0, leaf, path, 0); + Assert.IsGreaterThan(0, depth, $"foglia {leaf} assente"); + var node = 0; + for (var i = 0; i < depth; i++) + { + Write(probs[offset + (node >> 1)], path[i]); + node = tree[node + path[i]]; + } + } + + public byte[] Finish() + { + var c = _bitCount; + var v = _bottom; + if ((v & (1u << (32 - c))) != 0) + { + AddOne(); + } + + v <<= c & 7; + c >>= 3; + while (--c >= 0) + { + v <<= 8; + } + + for (c = 0; c < 4; c++) + { + _output.Add((byte)(v >> 24)); + v <<= 8; + } + + return [.. _output]; + } + + private static int FindPath(ReadOnlySpan tree, int node, int leaf, Span path, int depth) + { + for (var bit = 0; bit < 2; bit++) + { + var child = tree[node + bit]; + path[depth] = bit; + if (child <= 0) + { + if (-child == leaf) + { + return depth + 1; + } + } + else + { + var found = FindPath(tree, child, leaf, path, depth + 1); + if (found > 0) + { + return found; + } + } + } + + return 0; + } + + private void AddOne() + { + var i = _output.Count - 1; + while (_output[i] == 255) + { + _output[i] = 0; + i--; + } + + _output[i]++; + } +} + +/// What a test macroblock holds. +internal sealed class Vp8TestMacroblock +{ + public int Segment { get; set; } + + public bool Skip { get; set; } + + /// DC_PRED, V_PRED, H_PRED, TM_PRED or B_PRED (Vp8Tables). + public int YMode { get; set; } + + /// The sixteen subblock modes for B_PRED. + public int[] BModes { get; } = new int[16]; + + public int UvMode { get; set; } + + /// Quantized levels of the 25 blocks (16 Y, 4 U, 4 V, Y2), in zigzag order. + public int[][] Levels { get; } = [.. Enumerable.Range(0, 25).Select(_ => new int[16])]; +} + +/// +/// A VP8 key frame writer for the tests (RFC 6386 §9, §19): any header the decoder reads, given modes and quantized +/// levels of every macroblock, tokens with the same contexts and default probabilities as the decoder. +/// +internal sealed class Vp8TestWriter +{ + public int Width { get; init; } + + public int Height { get; init; } + + public bool Segmentation { get; init; } + + public bool UpdateMap { get; init; } + + public bool AbsoluteDeltas { get; init; } + + public int[] SegmentQuant { get; init; } = new int[4]; + + public int[] SegmentFilter { get; init; } = new int[4]; + + public byte[] SegmentProbs { get; init; } = [128, 128, 128]; + + public bool SimpleFilter { get; init; } + + public int FilterLevel { get; init; } + + public int Sharpness { get; init; } + + public int[]? RefLfDelta { get; init; } + + public int[]? ModeLfDelta { get; init; } + + public int Log2Partitions { get; init; } + + public int BaseQ { get; init; } = 40; + + public int[] QDeltas { get; init; } = new int[5]; + + public bool UseSkipProb { get; init; } = true; + + public int SkipProb { get; init; } = 100; + + public int MbWidth => (Width + 15) / 16; + + public int MbHeight => (Height + 15) / 16; + + /// The VP8 frame (the payload of a «VP8 » chunk). + public byte[] Write(Vp8TestMacroblock[] macroblocks) + { + Assert.HasCount(MbWidth * MbHeight, macroblocks); + var first = new Vp8BoolEncoder(); + WriteHeader(first); + var partitions = Enumerable.Range(0, 1 << Log2Partitions).Select(_ => new Vp8BoolEncoder()).ToArray(); + var intraTop = Enumerable.Repeat(Vp8Tables.BDc, MbWidth * 4).ToArray(); + var nzTop = new int[MbWidth * 9]; + for (var mbY = 0; mbY < MbHeight; mbY++) + { + var intraLeft = new int[] { Vp8Tables.BDc, Vp8Tables.BDc, Vp8Tables.BDc, Vp8Tables.BDc }; + var nzLeft = new int[9]; + var tokens = partitions[mbY % partitions.Length]; + for (var mbX = 0; mbX < MbWidth; mbX++) + { + var mb = macroblocks[(mbY * MbWidth) + mbX]; + WriteModes(first, mb, intraTop.AsSpan(mbX * 4, 4), intraLeft); + var top = nzTop.AsSpan(mbX * 9, 9); + if (UseSkipProb && mb.Skip) + { + top[..8].Clear(); + nzLeft.AsSpan(0, 8).Clear(); + if (mb.YMode != Vp8Tables.BPred) + { + top[8] = nzLeft[8] = 0; + } + + continue; + } + + WriteResiduals(tokens, mb, top, nzLeft); + } + } + + var firstBytes = first.Finish(); + var partitionBytes = partitions.Select(p => p.Finish()).ToArray(); + using var frame = new MemoryStream(); + var tag = (firstBytes.Length << 5) | (1 << 4); // key frame, version 0, shown + frame.Write([(byte)tag, (byte)(tag >> 8), (byte)(tag >> 16), 0x9D, 0x01, 0x2A, (byte)Width, (byte)(Width >> 8), (byte)Height, (byte)(Height >> 8)]); + frame.Write(firstBytes); + for (var i = 0; i < partitionBytes.Length - 1; i++) + { + var size = partitionBytes[i].Length; + frame.Write([(byte)size, (byte)(size >> 8), (byte)(size >> 16)]); + } + + foreach (var p in partitionBytes) + { + frame.Write(p); + } + + return frame.ToArray(); + } + + /// A frame of empty macroblocks with the given modes (skip set, so no tokens). + public static Vp8TestMacroblock[] Uniform(int count, int yMode, int uvMode, int bMode = Vp8Tables.BDc) + { + var mbs = new Vp8TestMacroblock[count]; + for (var i = 0; i < count; i++) + { + mbs[i] = new Vp8TestMacroblock { YMode = yMode, UvMode = uvMode, Skip = true }; + Array.Fill(mbs[i].BModes, bMode); + } + + return mbs; + } + + /// Random modes, segments and levels from a fixed seed; about a third of the blocks empty. + public static Vp8TestMacroblock[] Random(int count, int seed, int maxLevel = 40, bool skips = true) + { + var random = new Random(seed); + var mbs = new Vp8TestMacroblock[count]; + for (var i = 0; i < count; i++) + { + var mb = new Vp8TestMacroblock + { + Segment = random.Next(4), + YMode = random.Next(5), + UvMode = random.Next(4), + Skip = skips && random.Next(6) == 0, + }; + for (var b = 0; b < 16; b++) + { + mb.BModes[b] = random.Next(Vp8Tables.NumBModes); + } + + foreach (var block in mb.Levels) + { + if (random.Next(3) == 0) + { + continue; + } + + var count2 = random.Next(1, 17); + for (var k = 0; k < count2; k++) + { + var position = random.Next(k < 3 ? 4 : 16); + var magnitude = random.Next(8) == 0 ? random.Next(1, maxLevel + 1) : random.Next(1, 4); + block[position] = random.Next(2) == 0 ? magnitude : -magnitude; + } + } + + mbs[i] = mb; + } + + return mbs; + } + + private void WriteHeader(Vp8BoolEncoder e) + { + e.Literal(0, 1); // colour space + e.Literal(0, 1); // clamping type + e.Write(128, Segmentation); + if (Segmentation) + { + e.Write(128, UpdateMap); + e.Write(128, true); // update segment feature data + e.Write(128, AbsoluteDeltas); + foreach (var q in SegmentQuant) + { + e.OptionalSigned(q, 7); + } + + foreach (var f in SegmentFilter) + { + e.OptionalSigned(f, 6); + } + + if (UpdateMap) + { + foreach (var p in SegmentProbs) + { + e.Write(128, true); + e.Literal(p, 8); + } + } + } + + e.Write(128, SimpleFilter); + e.Literal(FilterLevel, 6); + e.Literal(Sharpness, 3); + var deltas = RefLfDelta is not null || ModeLfDelta is not null; + e.Write(128, deltas); + if (deltas) + { + e.Write(128, true); + foreach (var d in RefLfDelta ?? new int[4]) + { + e.OptionalSigned(d, 6); + } + + foreach (var d in ModeLfDelta ?? new int[4]) + { + e.OptionalSigned(d, 6); + } + } + + e.Literal(Log2Partitions, 2); + e.Literal(BaseQ, 7); + foreach (var d in QDeltas) + { + e.OptionalSigned(d, 4); + } + + e.Write(128, false); // refresh entropy probs + foreach (var p in Vp8Tables.CoefficientUpdateProbs) + { + e.Write(p, false); // no probability updated + } + + e.Write(128, UseSkipProb); + if (UseSkipProb) + { + e.Literal(SkipProb, 8); + } + } + + private void WriteModes(Vp8BoolEncoder e, Vp8TestMacroblock mb, Span top, int[] left) + { + if (UpdateMap) + { + var s = mb.Segment; + e.Write(SegmentProbs[0], s >= 2); + e.Write(SegmentProbs[s >= 2 ? 2 : 1], s & 1); + } + + if (UseSkipProb) + { + e.Write(SkipProb, mb.Skip); + } + + if (mb.YMode == Vp8Tables.BPred) + { + e.Write(145, false); + for (var row = 0; row < 4; row++) + { + for (var col = 0; col < 4; col++) + { + var mode = mb.BModes[(row * 4) + col]; + e.Tree(Vp8Tables.BModeTree, Vp8Tables.KeyFrameBModeProbs, ((top[col] * Vp8Tables.NumBModes) + left[row]) * 9, mode); + top[col] = left[row] = mode; + } + } + } + else + { + e.Write(145, true); + var y = mb.YMode; + e.Write(156, y is Vp8Tables.HPred or Vp8Tables.TmPred); + if (y is Vp8Tables.HPred or Vp8Tables.TmPred) + { + e.Write(128, y == Vp8Tables.TmPred); + } + else + { + e.Write(163, y == Vp8Tables.VPred); + } + + var implied = y switch { Vp8Tables.VPred => Vp8Tables.BVe, Vp8Tables.HPred => Vp8Tables.BHe, Vp8Tables.TmPred => Vp8Tables.BTm, _ => Vp8Tables.BDc }; + top.Fill(implied); + Array.Fill(left, implied); + } + + var uv = mb.UvMode; + e.Write(142, uv != Vp8Tables.DcPred); + if (uv != Vp8Tables.DcPred) + { + e.Write(114, uv != Vp8Tables.VPred); + if (uv != Vp8Tables.VPred) + { + e.Write(183, uv == Vp8Tables.TmPred); + } + } + } + + private static void WriteResiduals(Vp8BoolEncoder e, Vp8TestMacroblock mb, Span top, int[] left) + { + int first; + int yType; + if (mb.YMode != Vp8Tables.BPred) + { + var flag = WriteBlock(e, 1, top[8] + left[8], 0, mb.Levels[24]); + top[8] = left[8] = flag; + first = 1; + yType = 0; + } + else + { + first = 0; + yType = 3; + } + + for (var row = 0; row < 4; row++) + { + for (var col = 0; col < 4; col++) + { + var flag = WriteBlock(e, yType, top[col] + left[row], first, mb.Levels[(row * 4) + col]); + top[col] = left[row] = flag; + } + } + + for (var plane = 0; plane < 2; plane++) + { + for (var row = 0; row < 2; row++) + { + for (var col = 0; col < 2; col++) + { + var t = 4 + (plane * 2) + col; + var l = 4 + (plane * 2) + row; + var flag = WriteBlock(e, 2, top[t] + left[l], 0, mb.Levels[16 + (plane * 4) + (row * 2) + col]); + top[t] = left[l] = flag; + } + } + } + } + + // RFC 6386 §13: the tokens of one block from position `first`; returns the context flag (any token not EOB). + private static int WriteBlock(Vp8BoolEncoder e, int type, int context, int first, int[] levels) + { + var probs = Vp8Tables.DefaultCoefficientProbs; + var bands = Vp8Tables.Bands; + var last = -1; + for (var n = first; n < 16; n++) + { + if (levels[n] != 0) + { + last = n; + } + } + + var p = Index(type, bands[first], context); + if (last < 0) + { + e.Write(probs[p], false); + return 0; + } + + var afterZero = false; + for (var n = first; n <= last; n++) + { + if (!afterZero) + { + e.Write(probs[p], true); // not the end of the block + } + + var v = Math.Abs(levels[n]); + if (v == 0) + { + e.Write(probs[p + 1], false); + p = Index(type, bands[n + 1], 0); + afterZero = true; + continue; + } + + e.Write(probs[p + 1], true); + int context2; + if (v == 1) + { + e.Write(probs[p + 2], false); + context2 = 1; + } + else + { + e.Write(probs[p + 2], true); + WriteLarge(e, probs.Slice(p, 11), v); + context2 = 2; + } + + e.Write(128, levels[n] < 0); + p = Index(type, bands[n + 1], context2); + afterZero = false; + } + + if (last < 15) + { + e.Write(probs[p], false); // end of block + } + + return 1; + } + + private static void WriteLarge(Vp8BoolEncoder e, ReadOnlySpan p, int v) + { + if (v <= 4) + { + e.Write(p[3], false); + e.Write(p[4], v != 2); + if (v != 2) + { + e.Write(p[5], v == 4); + } + + return; + } + + e.Write(p[3], true); + if (v <= 10) + { + e.Write(p[6], false); + e.Write(p[7], v > 6); + if (v <= 6) + { + e.Write(159, v - 5); + } + else + { + e.Write(165, (v - 7) >> 1); + e.Write(145, (v - 7) & 1); + } + + return; + } + + e.Write(p[6], true); + var category = v <= 18 ? 0 : v <= 34 ? 1 : v <= 66 ? 2 : 3; + e.Write(p[8], category >> 1); + e.Write(p[9 + (category >> 1)], category & 1); + var extra = category switch { 0 => Vp8Tables.Cat3, 1 => Vp8Tables.Cat4, 2 => Vp8Tables.Cat5, _ => Vp8Tables.Cat6 }; + var value = v - 3 - (8 << category); + for (var i = 0; i < extra.Length; i++) + { + e.Write(extra[i], (value >> (extra.Length - 1 - i)) & 1); + } + } + + private static int Index(int type, int band, int context) => (((type * 8) + band) * 3 + context) * 11; +} diff --git a/tests/Febe.Tests/Imaging/WebPContainerTests.cs b/tests/Febe.Tests/Imaging/WebPContainerTests.cs new file mode 100644 index 0000000..4d462c6 --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPContainerTests.cs @@ -0,0 +1,596 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The WebP container (RFC 9649 §2): the extended format with ALPH in every variant, ICCP, EXIF and XMP; the first +/// frame of an animation on its canvas; limits; and files that are damaged or cut short. +/// +[TestClass] +public sealed class WebPContainerTests +{ + private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 }; + + [TestMethod] + public void EveryAlphaVariantGivesTheSamePicture() + { + var reference = ReferenceImages.Get("webp-perdita-alfa-q80"); + var original = reference.ReadInput(); + using var expected = WebPDecoder.Decode(original); + var vp8 = WebPTestFiles.Payload(original, "VP8 "); + var alpha = WebPTestFiles.AlphaOf(expected); + var (w, h) = (expected.Width, expected.Height); + Assert.IsTrue(alpha.Distinct().Count() > 2, "il riferimento ha un'alfa vera"); + + for (var filter = 0; filter < 4; filter++) + { + var filtered = WebPTestFiles.FilterAlpha(alpha, w, h, filter); + foreach (var preprocessed in (bool[])[false, true]) + { + var flags = (filter << 2) | (preprocessed ? 0x10 : 0); + var raw = File((byte)flags, filtered); + var compressed = File((byte)(flags | 1), WebPEncoder.EncodeAlphaStream(filtered, w, h, Vp8LEncoderSettings.Default)); + using var fromRaw = WebPDecoder.Decode(raw); + using var fromCompressed = WebPDecoder.Decode(compressed); + ImageAssert.AreEqual(expected, fromRaw, $"grezza, filtro {filter}"); + ImageAssert.AreEqual(expected, fromCompressed, $"compressa, filtro {filter}"); + } + } + + // A raw plane with bytes to spare is fine; a short one, an unknown method or reserved bits are not. + using (var longer = WebPDecoder.Decode(File(0, [.. alpha, 1, 2, 3]))) + { + ImageAssert.AreEqual(expected, longer, "byte in più"); + } + + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0, alpha[..^1]))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(2, alpha))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0x40, alpha))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(0x20, alpha))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(File(1, [1, 2, 3]))); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, w, h)), ("ALPH", []), ("VP8 ", vp8)))); + + byte[] File(byte header, byte[] plane) => + WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, w, h)), ("ALPH", [header, .. plane]), ("VP8 ", vp8)); + } + + [TestMethod] + public void TheAlphaFilterIsUndoneForEveryMethod() + { + var random = new Random(61); + foreach (var (w, h) in new[] { (1, 1), (1, 7), (9, 1), (13, 11) }) + { + var alpha = new byte[w * h]; + random.NextBytes(alpha); + for (var filter = 0; filter < 4; filter++) + { + var plane = WebPTestFiles.FilterAlpha(alpha, w, h, filter); + WebPAlpha.Unfilter(plane, w, h, filter); + CollectionAssert.AreEqual(alpha, plane, $"{w}×{h}, filtro {filter}"); + } + } + } + + [TestMethod] + public void TheExtendedFormatCarriesMetadataAroundAStillPicture() + { + var lossy = ReferenceImages.Get("webp-perdita-q80").ReadInput(); + using var expected = WebPDecoder.Decode(lossy); + var vp8 = WebPTestFiles.Payload(lossy, "VP8 "); + var tiff = WebPTestFiles.Tiff(8); + var icc = new byte[77]; + new Random(62).NextBytes(icc); + var file = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x20 | 0x08 | 0x04, 101, 67)), + ("ICCP", icc), + ("VP8 ", vp8), + ("ABCD", [1, 2, 3]), + ("EXIF", [.. "Exif\0\0"u8, .. tiff]), + ("XMP ", ""u8.ToArray())); + using var image = WebPDecoder.Decode(file, out var info); + ImageAssert.AreEqual(expected, image, "VP8 dentro VP8X"); + Assert.AreEqual((101, 67, 1, false), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); + CollectionAssert.AreEqual(tiff, info.Metadata.Exif, "il prefisso «Exif» si toglie"); + Assert.AreEqual(8, info.Metadata.Orientation); + CollectionAssert.AreEqual(icc, info.Metadata.IccProfile); + Assert.AreEqual("", info.Metadata.Xmp); + Assert.AreEqual(8, WebPDecoder.Identify(file).Metadata.Orientation); + + // Metadata beyond the budget is skipped, the picture is still read. + var tight = WebPDecoder.Identify(file, ImageLimits.Default with { MaxMetadataBytes = 50 }); + Assert.IsNull(tight.Metadata.IccProfile); + CollectionAssert.AreEqual(tiff, tight.Metadata.Exif); + + // VP8L inside VP8X; a canvas of another size is refused. + var lossless = ReferenceImages.Get("webp-senza-perdita").ReadInput(); + var vp8l = WebPTestFiles.Payload(lossless, "VP8L"); + using var simple = WebPDecoder.Decode(lossless); + using var extended = WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, 101, 67)), ("VP8L", vp8l))); + ImageAssert.AreEqual(simple, extended, "VP8L dentro VP8X"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x10, 102, 67)), ("VP8L", vp8l)))); + Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0, 101, 67))))); + Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("VP8X", new byte[9]), ("VP8L", vp8l)))); + Assert.ThrowsExactly(() => WebPDecoder.Identify(WebPTestFiles.Riff(("ABCD", vp8l)))); + } + + [TestMethod] + public void TheFirstFrameOfAnAnimationIsPlacedAndBlendedOnTheCanvas() + { + using var frame = TestImages.Random(20, 10, 63); // random alpha, some 0 and some 255 + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(frame), "VP8L"); + using var second = TestImages.Random(8, 8, 64, opaque: true); + var secondFrame = WebPTestFiles.Anmf(0, 0, 8, 8, 0, ("VP8L", WebPTestFiles.Payload(WebPEncoder.Encode(second), "VP8L"))); + + foreach (var blend in (bool[])[true, false]) + { + var file = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 40, 30)), + ("ANIM", WebPTestFiles.Anim(0xFF0000FF, 0)), + ("ANMF", WebPTestFiles.Anmf(4, 6, 20, 10, blend ? 0 : 2, ("VP8L", vp8l))), + ("ANMF", secondFrame)); + using var canvas = WebPDecoder.Decode(file, out var info); + Assert.AreEqual((40, 30, 2, true), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); + for (var y = 0; y < 30; y++) + { + for (var x = 0; x < 40; x++) + { + var inside = x >= 4 && x < 24 && y >= 6 && y < 16; + var actual = canvas.GetPixel(x, y); + if (!inside) + { + Assert.AreEqual(((byte)0, (byte)0, (byte)0, (byte)0), actual, $"fuori dal fotogramma ({x}, {y})"); + continue; + } + + var source = frame.GetPixel(x - 4, y - 6); + + // On a transparent canvas blending gives the source, and transparent black where it is transparent. + var expected = blend && source.A == 0 ? ((byte)0, (byte)0, (byte)0, (byte)0) : source; + Assert.AreEqual(expected, actual, $"fondere {blend}, ({x}, {y})"); + } + } + + Assert.AreEqual(2, ImageDecoder.Identify(file).FrameCount); + } + + // A lossy frame with alpha that covers the canvas reads as the still picture. + var lossy = ReferenceImages.Get("webp-perdita-alfa-q80").ReadInput(); + using var still = WebPDecoder.Decode(lossy); + var animated = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 101, 67)), + ("ANIM", WebPTestFiles.Anim()), + ("ANMF", WebPTestFiles.Anmf(0, 0, 101, 67, 2, ("ALPH", WebPTestFiles.Payload(lossy, "ALPH")), ("VP8 ", WebPTestFiles.Payload(lossy, "VP8 "))))); + using var first = WebPDecoder.Decode(animated); + ImageAssert.AreEqual(still, first, "fotogramma VP8 con ALPH"); + } + + [TestMethod] + public void BrokenAnimationsAreRefused() + { + using var frame = TestImages.Random(20, 10, 65); + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(frame), "VP8L"); + byte[] Animation(params (string, byte[])[] chunks) => WebPTestFiles.Riff([("VP8X", WebPTestFiles.Vp8X(0x02, 40, 30)), ("ANIM", WebPTestFiles.Anim()), .. chunks]); + + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(22, 0, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 22, 20, 10, 0, ("VP8L", vp8l))))), "fuori dalla tela in basso"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 21, 10, 0, ("VP8L", vp8l))))), "misura diversa dall'immagine"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", WebPTestFiles.Anmf(0, 0, 20, 10, 0)))), "senza immagine"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(Animation(("ANMF", new byte[15]))), "ANMF corto"); + Assert.ThrowsExactly(() => WebPDecoder.Identify(Animation()), "nessun fotogramma"); + } + + [TestMethod] + public void BlendingFollowsTheFormulaOfTheSpecification() + { + // A = As + Ad·(1 − As), RGB = (RGBs·As + RGBd·Ad·(1 − As)) / A. + var destination = new byte[] { 200, 100, 0, 128 }; + WebPDecoder.Blend([0, 50, 250, 64], destination); + var sa = 64 / 255.0; + var da = 128 / 255.0 * (1 - sa); + var a = sa + da; + Assert.AreEqual((int)Math.Round(a * 255), destination[3]); + Assert.AreEqual((int)Math.Round(((0 * sa) + (200 * da)) / a), destination[0]); + Assert.AreEqual((int)Math.Round(((50 * sa) + (100 * da)) / a), destination[1]); + Assert.AreEqual((int)Math.Round(((250 * sa) + (0 * da)) / a), destination[2]); + + var opaque = new byte[] { 1, 2, 3, 4 }; + WebPDecoder.Blend([9, 8, 7, 255], opaque); + CollectionAssert.AreEqual(new byte[] { 9, 8, 7, 255 }, opaque); + var keep = new byte[] { 1, 2, 3, 40 }; + WebPDecoder.Blend([9, 8, 7, 0], keep); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 40 }, keep); + } + + [TestMethod] + public void LimitsAreCheckedBeforeDecoding() + { + using var image = TestImages.Random(4, 4, 66); + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(image), "VP8L"); + + // A canvas of 16384×16384 announced by VP8X for an animation: Identify tells its size, Decode refuses it. + var big = WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x02, 16384, 16384)), ("ANIM", WebPTestFiles.Anim()), ("ANMF", WebPTestFiles.Anmf(0, 0, 4, 4, 0, ("VP8L", vp8l)))); + var info = WebPDecoder.Identify(big, Small); + Assert.AreEqual((16384, 16384), (info.Width, info.Height)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(big, Small)); + + // A VP8L header claiming 4000×4000 with nothing behind it: over the small limits it is refused for its + // size, within the default ones for the missing data. + var writer = new Vp8LBitWriter(); + writer.WriteBits(0x2F, 8); + writer.WriteBits(3999, 14); + writer.WriteBits(3999, 14); + writer.WriteBits(0, 4); + writer.WriteBits(0, 16); + var empty = WebPTestFiles.Riff(("VP8L", writer.ToArray())); + Assert.AreEqual((4000, 4000), (WebPDecoder.Identify(empty, Small).Width, WebPDecoder.Identify(empty, Small).Height)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(empty, Small)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(empty)); + } + + [TestMethod] + public void DamagedHeadersAreRefused() + { + var lossy = ReferenceImages.Get("webp-perdita-q30").ReadInput(); + var vp8 = WebPTestFiles.Payload(lossy, "VP8 "); + Assert.ThrowsExactly(() => WebPDecoder.Decode("RIFF\0\0\0\0WEBQ"u8.ToArray())); + Assert.ThrowsExactly(() => WebPDecoder.Decode((byte[])[.. "RIFF"u8, 3, 0, 0, 0, .. "WEBP"u8])); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff())); + + // RIFF size beyond the file; a chunk beyond the RIFF size. + var longer = lossy.ToArray(); + BinaryPrimitives.WriteUInt32LittleEndian(longer.AsSpan(4), (uint)(lossy.Length - 8 + 2)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(longer)); + var chunk = lossy.ToArray(); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(16), (uint)(vp8.Length + 3)); + Assert.ThrowsExactly(() => WebPDecoder.Decode(chunk)); + + // Trailing bytes after the RIFF size are ignored. + using (var trailing = WebPDecoder.Decode((byte[])[.. lossy, 1, 2, 3, 4, 5])) + using (var plain = WebPDecoder.Decode(lossy)) + { + ImageAssert.AreEqual(plain, trailing, "byte dopo il RIFF"); + } + + // VP8 frame header: inter frame, unknown version, not shown, start code, zero size, first partition too long. + foreach (var (at, value, what) in new[] { (0, vp8[0] | 1, "interfotogramma"), (0, (vp8[0] & 0xF1) | 0x08, "versione 4"), (0, vp8[0] & 0xEF, "da non mostrare"), (3, 0x9C, "codice d'inizio"), (6, 0, "larghezza nulla") }) + { + var bad = vp8.ToArray(); + bad[at] = (byte)value; + if (what == "larghezza nulla") + { + bad[7] &= 0xC0; + } + + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", bad))), what); + } + + var huge = vp8.ToArray(); + huge[2] = 0xFF; + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", huge))), "prima partizione troppo lunga"); + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8 ", vp8[..9])))); + + // VP8L header: signature, version. + var vp8l = WebPTestFiles.Payload(ReferenceImages.Get("webp-senza-perdita").ReadInput(), "VP8L"); + var signature = vp8l.ToArray(); + signature[0] = 0x2E; + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8L", signature)))); + var version = vp8l.ToArray(); + version[4] |= 0x20; + Assert.ThrowsExactly(() => WebPDecoder.Decode(WebPTestFiles.Riff(("VP8L", version)))); + } + + [TestMethod] + public void DamagedLosslessStreamsAreRefused() + { + // Built bit by bit: header of a 4×4 image, then what follows. + byte[] Stream(Action body) + { + var writer = new Vp8LBitWriter(); + writer.WriteBits(0x2F, 8); + writer.WriteBits(3, 14); + writer.WriteBits(3, 14); + writer.WriteBits(0, 4); + body(writer); + writer.WriteBits(0, 32); + return WebPTestFiles.Riff(("VP8L", writer.ToArray())); + } + + void SimpleCode(Vp8LBitWriter w, int symbol) + { + w.WriteBits(1, 1); // simple + w.WriteBits(0, 1); // one symbol + w.WriteBits(1, 1); // eight bits + w.WriteBits((uint)symbol, 8); + } + + void NoTransformNoCache(Vp8LBitWriter w) + { + w.WriteBits(0, 1); // no transform + w.WriteBits(0, 1); // no colour cache + w.WriteBits(0, 1); // no meta codes + } + + // A valid stream: every pixel the literal (green 7, red 1, blue 2, alpha 3). + var valid = Stream(w => + { + NoTransformNoCache(w); + SimpleCode(w, 7); + SimpleCode(w, 1); + SimpleCode(w, 2); + SimpleCode(w, 3); + SimpleCode(w, 0); + }); + using (var image = WebPDecoder.Decode(valid)) + { + Assert.AreEqual(((byte)1, (byte)7, (byte)2, (byte)3), image.GetPixel(3, 3)); + } + + // The same transform twice. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + w.WriteBits(1, 1); + w.WriteBits(2, 2); + w.WriteBits(1, 1); + w.WriteBits(2, 2); + }))); + + // Colour cache of 0 and 12 bits. + foreach (var bits in (uint[])[0, 12]) + { + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + w.WriteBits(0, 1); + w.WriteBits(1, 1); + w.WriteBits(bits, 4); + })), $"cache {bits}"); + } + + // An incomplete normal code: code length code with two lengths of 2 (half the space unused). + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + NoTransformNoCache(w); + w.WriteBits(0, 1); + w.WriteBits(0, 4); // four code length codes: 17, 18, 0, 1 + w.WriteBits(0, 3); + w.WriteBits(0, 3); + w.WriteBits(2, 3); + w.WriteBits(2, 3); + }))); + + // A simple code naming a symbol outside a distance alphabet of 40. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + NoTransformNoCache(w); + SimpleCode(w, 7); + SimpleCode(w, 1); + SimpleCode(w, 2); + SimpleCode(w, 3); + SimpleCode(w, 45); + }))); + + // A backward reference before the first pixel: the green code has only symbol 256 + 0 (length 1)... which + // needs a normal code since it is above 255; here a two-symbol simple code cannot reach it, so use the cache + // index instead: a cache symbol with no cache is damage. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + w.WriteBits(0, 1); + w.WriteBits(1, 1); + w.WriteBits(1, 4); // cache of 2 entries: green alphabet 282 + w.WriteBits(0, 1); + Normal(w, 282, 256); + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 0); + }))); + + // A distance past the start of the image. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(w => + { + NoTransformNoCache(w); + Normal(w, 280, 256 + 3); // only length symbol 3: length 4 + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 0); + SimpleCode(w, 39); // the largest distance + w.WriteBits(0, 18); + }))); + } + + [TestMethod] + public void OnlyTheGroupsTheMetaImageNamesAreBuilt() + { + // An 8×8 image with meta codes of 4×4 blocks: a 2×2 meta image whose pixels name groups 5, 2, 2 and 5 (in + // green; red 0). The stream holds the codes of groups 0 to 5; only 2 and 5 paint. + static byte[] Stream(int groups, (int Meta0, int Meta1) names, Action unused) + { + var w = new Vp8LBitWriter(); + w.WriteBits(0x2F, 8); + w.WriteBits(7, 14); + w.WriteBits(7, 14); + w.WriteBits(0, 4); + w.WriteBits(0, 1); // no transform + w.WriteBits(0, 1); // no colour cache + w.WriteBits(1, 1); // meta codes + w.WriteBits(0, 3); // meta bits 2: blocks of 4×4, a 2×2 meta image + + // The meta image: no cache, green a two-symbol code (bit 0 → the smaller name, 1 → the larger), the rest + // single symbols; the pixel bits pick larger, smaller, smaller, larger. + w.WriteBits(0, 1); + var (small, large) = names; + w.WriteBits(1, 1); + w.WriteBits(small == large ? 0u : 1u, 1); + w.WriteBits(1, 1); + w.WriteBits((uint)(small & 0xFF), 8); + if (small != large) + { + w.WriteBits((uint)(large & 0xFF), 8); + } + + Single(w, small >> 8); // red: the high byte of the group + Single(w, 0); + Single(w, 0); + Single(w, 0); + foreach (var bit in (uint[])[1, 0, 0, 1]) + { + if (small != large) + { + w.WriteBits(bit, 1); + } + } + + for (var g = 0; g < groups; g++) + { + if (g == small || g == large) + { + // Green g + 1, red g, blue 2·g, alpha 255. + Single(w, g + 1); + Single(w, g); + Single(w, 2 * g); + Single(w, 255); + Single(w, 0); + } + else + { + unused(w, g); + } + } + + w.WriteBits(0, 32); + return WebPTestFiles.Riff(("VP8L", w.ToArray())); + } + + static void Single(Vp8LBitWriter w, int symbol) + { + w.WriteBits(1, 1); + w.WriteBits(0, 1); + w.WriteBits(1, 1); + w.WriteBits((uint)(symbol & 0xFF), 8); + } + + static void Cheap(Vp8LBitWriter w, int g) + { + for (var k = 0; k < 5; k++) + { + w.WriteBits(1, 1); // simple + w.WriteBits(0, 1); // one symbol + w.WriteBits(0, 1); // of one bit + w.WriteBits(0, 1); // symbol 0 + } + } + + using (var image = WebPDecoder.Decode(Stream(6, (2, 5), Cheap))) + { + Assert.AreEqual(((byte)5, (byte)6, (byte)10, (byte)255), image.GetPixel(1, 1), "gruppo 5 in alto a sinistra"); + Assert.AreEqual(((byte)2, (byte)3, (byte)4, (byte)255), image.GetPixel(6, 1), "gruppo 2 in alto a destra"); + Assert.AreEqual(((byte)2, (byte)3, (byte)4, (byte)255), image.GetPixel(1, 6), "gruppo 2 in basso a sinistra"); + Assert.AreEqual(((byte)5, (byte)6, (byte)10, (byte)255), image.GetPixel(7, 7), "gruppo 5 in basso a destra"); + } + + // A single meta pixel naming group 65535: 65,536 groups in the stream (about 160 KB of codes). Building all + // of them took about 335 MB of tables; only one is built now, so a working budget of 4 MiB is enough. + var huge = Stream(65536, (65535, 65535), Cheap); + Assert.IsLessThan(200_000, huge.Length); + using (var image = WebPDecoder.Decode(huge, new ImageLimits { MaxWorkingBytes = 4 * 1024 * 1024 })) + { + Assert.AreEqual(((byte)255, (byte)0, (byte)254, (byte)255), image.GetPixel(4, 4)); + } + + // The codes of unused groups are still read and checked: three symbols of length 1 are no prefix code. + Assert.ThrowsExactly(() => WebPDecoder.Decode(Stream(6, (2, 5), (w, g) => + { + if (g != 3) + { + Cheap(w, g); + return; + } + + w.WriteBits(0, 1); // normal code + w.WriteBits(0, 4); // four code length codes: 17, 18, 0, 1 + w.WriteBits(0, 3); + w.WriteBits(0, 3); + w.WriteBits(1, 3); // length code 0 has length 1 + w.WriteBits(1, 3); // length code 1 has length 1 + w.WriteBits(1, 1); // max_symbol present + w.WriteBits(0, 3); // length_nbits = 2 + w.WriteBits(1, 2); // max_symbol = 3 + w.WriteBits(7, 3); // three lengths of 1 + for (var k = 1; k < 5; k++) + { + Single(w, 0); + } + }))); + } + + [TestMethod] + public void StreamsCutShortAreRefusedOrReadWhole() + { + foreach (var name in (string[])["webp-senza-perdita", "webp-senza-perdita-rapido", "webp-perdita-q30", "webp-perdita-alfa-q80"]) + { + var input = ReferenceImages.Get(name).ReadInput(); + using var whole = WebPDecoder.Decode(input); + var chunks = WebPTestFiles.Chunks(input); + var last = chunks[^1]; + var lossless = last.Type == "VP8L"; + for (var cut = 1; cut < last.Payload.Length - 1; cut++) + { + // Cut the image chunk, and keep the RIFF consistent so only the bitstream is short. + var shorter = last.Payload[..^cut]; + var file = WebPTestFiles.Riff([.. chunks.Take(chunks.Count - 1), (last.Type, shorter)]); + RgbaImage? image = null; + try + { + image = WebPDecoder.Decode(file); + } + catch (ImageDecodeException) + { + } + + using (image) + { + if (image is null) + { + continue; + } + + // What is read is read whole. The boolean coder ends with flush bytes the decoder may never + // need (measured: up to 3 on these files), so a lossy stream can lose only those. + ImageAssert.AreEqual(whole, image, $"{name} senza gli ultimi {cut} byte"); + if (!lossless) + { + Assert.IsLessThanOrEqualTo(4, cut, $"{name}: senza gli ultimi {cut} byte la lettura doveva fermarsi"); + } + } + } + + // Plainly cut files (RIFF size beyond the end) are refused at every length. + for (var length = 0; length < input.Length; length += Math.Max(1, input.Length / 200)) + { + Assert.ThrowsExactly(() => WebPDecoder.Decode(input[..length]), $"{name} tagliato a {length}"); + } + } + } + + // A normal code over `alphabet` symbols in which only `symbol` has a length (a code of zero bits): code length + // code with the single symbol 1 (zero bits too), then max_symbol so only the lengths up to `symbol` are read. + private static void Normal(Vp8LBitWriter w, int alphabet, int symbol) + { + w.WriteBits(0, 1); + w.WriteBits(0, 4); // four code length codes: 17, 18, 0, 1 + w.WriteBits(0, 3); + w.WriteBits(0, 3); + w.WriteBits(1, 3); // length code 0 has length 1 + w.WriteBits(1, 3); // length code 1 has length 1 + w.WriteBits(1, 1); // max_symbol present + w.WriteBits(4, 3); // length_nbits = 2 + 2·4 = 10 + w.WriteBits((uint)(symbol + 1 - 2), 10); + for (var s = 0; s < symbol; s++) + { + w.WriteBits(0, 1); // length 0 (code 0) + } + + w.WriteBits(1, 1); // length 1 (code 1) + Assert.IsGreaterThan(symbol, alphabet); + } +} diff --git a/tests/Febe.Tests/Imaging/WebPEncoderTests.cs b/tests/Febe.Tests/Imaging/WebPEncoderTests.cs new file mode 100644 index 0000000..9286f7d --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPEncoderTests.cs @@ -0,0 +1,227 @@ +using System.Globalization; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The in-house lossless WebP encoder: every image comes back exactly with each tool alone and with all of them, +/// metadata goes into a VP8X file in the order of RFC 9649, and what cannot be written is refused. +/// +[TestClass] +public sealed class WebPEncoderTests +{ + private static readonly Vp8LEncoderSettings Nothing = new() + { + Palette = false, + SubtractGreen = false, + Predictor = false, + ColorTransform = false, + Lz77 = false, + ColorCacheBits = 0, + }; + + public TestContext TestContext { get; set; } = null!; + + public static IEnumerable Tools => + [ + ["nessuno"], + ["tavolozza"], + ["verde"], + ["predittore"], + ["colore"], + ["lz77"], + ["cache"], + ["tutti"], + ["predittore-piccolo"], + ["predittore-grande"], + ]; + + [TestMethod] + [DynamicData(nameof(Tools))] + public void EveryImageComesBackExactly(string tool) + { + var settings = Settings(tool); + var sizes = new (int Width, int Height)[] { (1, 1), (2, 1), (1, 3), (5, 4), (17, 13), (64, 1), (1, 40), (101, 67) }; + var seed = 10; + foreach (var (width, height) in sizes) + { + foreach (var image in Images(width, height, seed++)) + { + using (image) + { + var file = WebPEncoder.Encode(image, new WebPEncoderOptions { Lossless = settings }); + using var back = WebPDecoder.Decode(file); + ImageAssert.AreEqual(image, back, $"{tool}, {width}×{height}"); + } + } + } + } + + [TestMethod] + public void TheReferencesComeBackExactly() + { + long ours = 0; + long png = 0; + foreach (var reference in ReferenceImages.All) + { + using var image = PngDecoder.Decode(reference.ReadExpectedPng()); + var file = WebPEncoder.Encode(image); + using var back = WebPDecoder.Decode(file); + ImageAssert.AreEqual(image, back, reference.Name); + ours += file.Length; + png += PngEncoder.Encode(image).Length; + } + + TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture, $"57 riferimenti: WebP senza perdita {ours} byte, PNG di casa {png} byte ({100.0 * ours / png:F1}%).")); + Assert.IsLessThan(png, ours, "il WebP senza perdita deve stare sotto il PNG di casa"); + } + + [TestMethod] + public void TheToolsMakeTheFilesSmaller() + { + // On the large lossless reference the default tools beat plain Huffman coding by a wide margin, and stay + // within reach of libwebp's own file. + var reference = ReferenceImages.Get("webp-grande-senza-perdita"); + using var image = PngDecoder.Decode(reference.ReadExpectedPng()); + var plain = WebPEncoder.Encode(image, new WebPEncoderOptions { Lossless = Nothing }).Length; + var full = WebPEncoder.Encode(image).Length; + var skia = reference.ReadInput().Length; + TestContext.WriteLine($"{reference.Name}: solo Huffman {plain} byte, tutti gli strumenti {full} byte, libwebp {skia} byte."); + Assert.IsLessThan(plain * 3 / 4, full); + Assert.IsLessThan(skia * 2, full); + + using var flat = new RgbaImage(300, 200); + flat.Pixels.Fill(0x80); + Assert.IsLessThan(100, WebPEncoder.Encode(flat).Length); + } + + [TestMethod] + public void WithoutMetadataTheFileIsTheSimpleFormat() + { + using var opaque = TestImages.Random(9, 7, 3, opaque: true); + var file = WebPEncoder.Encode(opaque); + var chunks = WebPTestFiles.Chunks(file); + Assert.AreEqual("VP8L", chunks.Single().Type); + var info = WebPDecoder.Identify(file); + Assert.AreEqual((9, 7, 1, false), (info.Width, info.Height, info.FrameCount, info.HasAlpha)); + + using var transparent = TestImages.Random(9, 7, 3); + Assert.IsTrue(WebPDecoder.Identify(WebPEncoder.Encode(transparent)).HasAlpha); + } + + [TestMethod] + public void MetadataGoesIntoAnExtendedFileInOrder() + { + using var image = TestImages.Random(11, 5, 4); + var tiff = WebPTestFiles.Tiff(6); + var icc = new byte[301]; + new Random(5).NextBytes(icc); + const string Xmp = "città"; + var file = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = [.. "Exif\0\0"u8, .. tiff], IccProfile = icc, Xmp = Xmp }); + + var chunks = WebPTestFiles.Chunks(file); + CollectionAssert.AreEqual(new[] { "VP8X", "ICCP", "VP8L", "EXIF", "XMP " }, chunks.Select(c => c.Type).ToArray()); + var vp8x = chunks[0].Payload; + Assert.AreEqual(0x20 | 0x10 | 0x08 | 0x04, vp8x[0]); + Assert.AreEqual((10, 4), (vp8x[4] | (vp8x[5] << 8) | (vp8x[6] << 16), vp8x[7] | (vp8x[8] << 8) | (vp8x[9] << 16))); + CollectionAssert.AreEqual(tiff, chunks[3].Payload, "il prefisso «Exif» di JPEG si toglie"); + Assert.AreEqual(file.Length, 8 + (int)System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(4))); + Assert.AreEqual(0, file.Length % 2); + + using var back = WebPDecoder.Decode(file, out var info); + ImageAssert.AreEqual(image, back, "con i metadati"); + CollectionAssert.AreEqual(tiff, info.Metadata.Exif); + Assert.AreEqual(6, info.Metadata.Orientation); + CollectionAssert.AreEqual(icc, info.Metadata.IccProfile); + Assert.AreEqual(Xmp, info.Metadata.Xmp); + Assert.IsTrue(info.HasAlpha); + + // Only one kind of metadata: only its flag; an opaque image has no alpha flag. + using var opaque = TestImages.Random(4, 4, 6, opaque: true); + var onlyXmp = WebPEncoder.Encode(opaque, new WebPEncoderOptions { Xmp = "x" }); + Assert.AreEqual(0x04, WebPTestFiles.Payload(onlyXmp, "VP8X")[0]); + Assert.AreEqual("x", WebPDecoder.Identify(onlyXmp).Metadata.Xmp); + } + + [TestMethod] + public void WhatCannotBeWrittenIsRefused() + { + using var image = TestImages.Random(3, 3, 7); + Assert.Throws(() => WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = "non TIFF"u8.ToArray() })); + Assert.Throws(() => WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = [.. "Exif\0\0"u8, 1, 2] })); + Assert.Throws(() => WebPEncoder.Encode(null!)); + using var wide = new RgbaImage(WebPEncoder.MaxDimension + 1, 1); + Assert.Throws(() => WebPEncoder.Encode(wide)); + using var tall = new RgbaImage(1, WebPEncoder.MaxDimension + 1); + Assert.Throws(() => WebPEncoder.Encode(tall)); + } + + [TestMethod] + public void TheLargestSideIsWritten() + { + using var image = TestImages.Random(WebPEncoder.MaxDimension, 2, 8); + var file = WebPEncoder.Encode(image); + using var back = WebPDecoder.Decode(file); + ImageAssert.AreEqual(image, back, "16384×2"); + } + + [TestMethod] + public void ThePrefixCodesOfLengthsAndDistancesInvertTheDecoder() + { + for (var value = 1; value <= (1 << 20); value += value < 5000 ? 1 : 997) + { + var (symbol, bits, extra) = Vp8LEncoder.Prefix(value); + Assert.IsLessThan(40, symbol); + var decoded = symbol < 4 ? symbol + 1 : ((2 + (symbol & 1)) << ((symbol - 2) >> 1)) + extra + 1; + Assert.AreEqual(value, decoded, $"valore {value}"); + Assert.AreEqual(symbol < 4 ? 0 : (symbol - 2) >> 1, bits); + } + + // The 120 short codes cover the neighbours exactly once. + for (var code = 1; code <= 120; code++) + { + var (dx, dy) = Vp8LDecoder.ShortDistance(code); + Assert.AreEqual(code, Vp8LEncoder.DistanceCode(dx + (dy * 1000), 1000), $"codice {code}"); + } + + Assert.AreEqual(9000 + 120, Vp8LEncoder.DistanceCode(9000, 1000)); // eight rows up: no short code + } + + private static Vp8LEncoderSettings Settings(string tool) => tool switch + { + "nessuno" => Nothing, + "tavolozza" => Nothing with { Palette = true }, + "verde" => Nothing with { SubtractGreen = true }, + "predittore" => Nothing with { Predictor = true }, + "colore" => Nothing with { ColorTransform = true }, + "lz77" => Nothing with { Lz77 = true }, + "cache" => Nothing with { ColorCacheBits = 6 }, + "predittore-piccolo" => Vp8LEncoderSettings.Default with { Palette = false, PredictorBits = 2, ColorTransformBits = 2 }, + "predittore-grande" => Vp8LEncoderSettings.Default with { Palette = false, PredictorBits = 9, ColorTransformBits = 9 }, + _ => Vp8LEncoderSettings.Default, + }; + + private static IEnumerable Images(int width, int height, int seed) + { + yield return TestImages.Random(width, height, seed); + yield return TestImages.Random(width, height, seed, opaque: true); + yield return TestImages.Gradient(width, height, seed); + foreach (var colors in (int[])[1, 2, 3, 4, 5, 16, 17, 256]) + { + yield return WebPTestFiles.FewColors(width, height, colors, seed + colors); + } + + // Transparent pixels that keep their colour, and long runs. + var runs = new RgbaImage(width, height); + var pixels = runs.Pixels; + for (var i = 0; i < width * height; i++) + { + pixels[i * 4] = (byte)(i / 7); + pixels[(i * 4) + 1] = 200; + pixels[(i * 4) + 2] = (byte)(i % 3); + pixels[(i * 4) + 3] = (byte)((i / 5) % 2 == 0 ? 0 : 255); + } + + yield return runs; + } +} diff --git a/tests/Febe.Tests/Imaging/WebPReferenceTests.cs b/tests/Febe.Tests/Imaging/WebPReferenceTests.cs new file mode 100644 index 0000000..cddd617 --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPReferenceTests.cs @@ -0,0 +1,74 @@ +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// +/// The in-house WebP decoder against the SkiaSharp (libwebp) reads of the reference set: lossless files must match +/// byte for byte, alpha included; lossy files are compared with the thresholds of , and their +/// alpha (stored losslessly in ALPH) must match exactly. +/// +[TestClass] +public sealed class WebPReferenceTests +{ + public TestContext TestContext { get; set; } = null!; + + public static IEnumerable LosslessCases => ReferenceImages.Of(ReferenceFormat.WebP).Where(c => !IsLossy(c)).Select(c => new object[] { c.Name }); + + public static IEnumerable LossyCases => ReferenceImages.Of(ReferenceFormat.WebP).Where(IsLossy).Select(c => new object[] { c.Name }); + + [TestMethod] + [DynamicData(nameof(LosslessCases))] + public void TheLosslessDecoderReadsTheReferenceExactly(string name) + { + var reference = ReferenceImages.Get(name); + using var expected = PngDecoder.Decode(reference.ReadExpectedPng()); + using var actual = WebPDecoder.Decode(reference.ReadInput()); + ImageAssert.AreEqual(expected, actual, name); + } + + [TestMethod] + [DynamicData(nameof(LossyCases))] + public void TheLossyDecoderIsCloseToTheReference(string name) + { + var reference = ReferenceImages.Get(name); + using var expected = PngDecoder.Decode(reference.ReadExpectedPng()); + using var actual = WebPDecoder.Decode(reference.ReadInput(), out var info); + var result = ImageQuality.Compare(expected, actual); + TestContext.WriteLine($"{name}: {result}"); + ImageQuality.AssertClose(result, name); + + // Alpha is lossless even in a lossy file. + var e = expected.Pixels; + var a = actual.Pixels; + for (var i = 3; i < e.Length; i += 4) + { + Assert.AreEqual(e[i], a[i], $"{name}: alfa del pixel {i / 4}"); + } + + Assert.AreEqual(name.Contains("alfa", StringComparison.Ordinal), info.HasAlpha, name); + } + + [TestMethod] + public void TheFacadeReadsWebPAndIdentifyAgreesWithDecode() + { + foreach (var reference in ReferenceImages.Of(ReferenceFormat.WebP)) + { + var input = reference.ReadInput(); + Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.WebP)); + using var viaFacade = ImageDecoder.Decode(input); + using var direct = WebPDecoder.Decode(input, pooled: true); + Assert.IsTrue(direct.IsPooled); + ImageAssert.AreEqual(direct, viaFacade, reference.Name); + + var info = ImageDecoder.Identify(input); + Assert.AreEqual((ImageFormat.WebP, reference.Width, reference.Height, 1), (info.Format, info.Width, info.Height, info.FrameCount), reference.Name); + Assert.AreSame(ImageMetadata.Empty, info.Metadata, reference.Name); + if (!info.HasAlpha) + { + Assert.IsTrue(direct.IsOpaque(), reference.Name); + } + } + } + + private static bool IsLossy(ReferenceCase c) => !c.Name.Contains("senza-perdita", StringComparison.Ordinal); +} diff --git a/tests/Febe.Tests/Imaging/WebPTestFiles.cs b/tests/Febe.Tests/Imaging/WebPTestFiles.cs new file mode 100644 index 0000000..37ed02d --- /dev/null +++ b/tests/Febe.Tests/Imaging/WebPTestFiles.cs @@ -0,0 +1,185 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Images; + +namespace Febe.Tests.Imaging; + +/// WebP files put together by the tests from RIFF chunks (RFC 9649 §2), to reach what the reference set lacks. +internal static class WebPTestFiles +{ + /// The chunks of a WebP file: FourCC and payload, in order. + public static List<(string Type, byte[] Payload)> Chunks(byte[] file) + { + var chunks = new List<(string, byte[])>(); + var end = 8 + (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(4)); + var pos = 12; + while (pos + 8 <= end) + { + var size = (int)BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos + 4)); + chunks.Add((System.Text.Encoding.ASCII.GetString(file, pos, 4), file.AsSpan(pos + 8, size).ToArray())); + pos += 8 + size + (size & 1); + } + + return chunks; + } + + /// The payload of the first chunk of that type. + public static byte[] Payload(byte[] file, string type) => Chunks(file).First(c => c.Type == type).Payload; + + /// A RIFF/WEBP file of the given chunks (padded to even sizes). + public static byte[] Riff(params (string Type, byte[] Payload)[] chunks) + { + using var body = new MemoryStream(); + body.Write("WEBP"u8); + foreach (var (type, payload) in chunks) + { + body.Write(Chunk(type, payload)); + } + + var file = new byte[8 + body.Length]; + "RIFF"u8.CopyTo(file); + BinaryPrimitives.WriteUInt32LittleEndian(file.AsSpan(4), (uint)body.Length); + body.ToArray().CopyTo(file, 8); + return file; + } + + public static byte[] Chunk(string type, byte[] payload) + { + var chunk = new byte[8 + payload.Length + (payload.Length & 1)]; + System.Text.Encoding.ASCII.GetBytes(type).CopyTo(chunk, 0); + BinaryPrimitives.WriteUInt32LittleEndian(chunk.AsSpan(4), (uint)payload.Length); + payload.CopyTo(chunk, 8); + return chunk; + } + + /// A VP8X payload: the flags byte and the canvas size. + public static byte[] Vp8X(int flags, int width, int height) + { + var payload = new byte[10]; + payload[0] = (byte)flags; + Uint24(payload.AsSpan(4), width - 1); + Uint24(payload.AsSpan(7), height - 1); + return payload; + } + + /// An ANIM payload: background colour (B, G, R, A) and loop count. + public static byte[] Anim(uint backgroundBgra = 0, int loops = 0) + { + var payload = new byte[6]; + BinaryPrimitives.WriteUInt32LittleEndian(payload, backgroundBgra); + BinaryPrimitives.WriteUInt16LittleEndian(payload.AsSpan(4), (ushort)loops); + return payload; + } + + /// An ANMF payload: offset (even), size, duration, flags (2 = do not blend, 1 = dispose) and frame chunks. + public static byte[] Anmf(int x, int y, int width, int height, int flags, params (string Type, byte[] Payload)[] chunks) + { + using var payload = new MemoryStream(); + var header = new byte[16]; + Uint24(header, x / 2); + Uint24(header.AsSpan(3), y / 2); + Uint24(header.AsSpan(6), width - 1); + Uint24(header.AsSpan(9), height - 1); + Uint24(header.AsSpan(12), 100); + header[15] = (byte)flags; + payload.Write(header); + foreach (var (type, data) in chunks) + { + payload.Write(Chunk(type, data)); + } + + return payload.ToArray(); + } + + /// + /// The forward alpha filter of RFC 9649 §2.7.1.2 (1 horizontal, 2 vertical, 3 gradient), written from the + /// predictor definitions, independent of the decoder's inverse. + /// + public static byte[] FilterAlpha(ReadOnlySpan alpha, int width, int height, int filter) + { + var output = new byte[alpha.Length]; + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + int predictor; + if (filter == 0 || (x == 0 && y == 0)) + { + predictor = 0; + } + else if (y == 0) + { + predictor = alpha[x - 1]; + } + else if (x == 0) + { + predictor = alpha[(y - 1) * width]; + } + else + { + int left = alpha[(y * width) + x - 1], top = alpha[((y - 1) * width) + x], topLeft = alpha[((y - 1) * width) + x - 1]; + predictor = filter switch + { + 1 => left, + 2 => top, + _ => Math.Clamp(left + top - topLeft, 0, 255), + }; + } + + output[(y * width) + x] = (byte)(alpha[(y * width) + x] - predictor); + } + } + + return output; + } + + /// The alpha bytes of an image. + public static byte[] AlphaOf(RgbaImage image) + { + var alpha = new byte[image.Width * image.Height]; + for (var i = 0; i < alpha.Length; i++) + { + alpha[i] = image.Pixels[(i * 4) + 3]; + } + + return alpha; + } + + /// A little-endian TIFF with an IFD0 holding only the Orientation tag. + public static byte[] Tiff(int orientation) + { + var tiff = new byte[8 + 2 + 12 + 4]; + "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; + } + + /// An image with only distinct colours (some transparent), from a fixed seed. + public static RgbaImage FewColors(int width, int height, int colors, int seed) + { + var random = new Random(seed); + var palette = new byte[colors * 4]; + random.NextBytes(palette); + var image = new RgbaImage(width, height); + var pixels = image.Pixels; + for (var i = 0; i < width * height; i++) + { + var c = (((i % width) / 3) + ((i / width) / 2) + random.Next(2)) % colors; + palette.AsSpan(c * 4, 4).CopyTo(pixels[(i * 4)..]); + } + + return image; + } + + private static void Uint24(Span destination, int value) + { + destination[0] = (byte)value; + destination[1] = (byte)(value >> 8); + destination[2] = (byte)(value >> 16); + } +} diff --git a/tests/Febe.Tests/Import/Support/ImportTestFiles.cs b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs index d6ad1de..5ae595c 100644 --- a/tests/Febe.Tests/Import/Support/ImportTestFiles.cs +++ b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs @@ -2,7 +2,6 @@ using System.Buffers.Binary; using System.Diagnostics; using System.Text; using Febe.Tests.Support; -using SkiaSharp; namespace Febe.Tests.Import.Support; @@ -244,7 +243,7 @@ internal static class ImportTestFiles public static byte[] Cropped(int scene, int width, int height) { using var bitmap = TestImages.Scene(scene, width, height); - using var crop = TestImages.Crop(bitmap, new SKRectI(0, 0, width / 2, height / 2)); + using var crop = TestImages.Crop(bitmap, 0, 0, width / 2, height / 2); return TestImages.Jpeg(crop, 88); } diff --git a/tests/Febe.Tests/Library/DamagedImageTests.cs b/tests/Febe.Tests/Library/DamagedImageTests.cs new file mode 100644 index 0000000..78fda9e --- /dev/null +++ b/tests/Febe.Tests/Library/DamagedImageTests.cs @@ -0,0 +1,81 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +/// +/// «File danneggiato o incompleto» (spec §4.6, §8.4; Alberto's answer of 25 November 2026): a truncated PNG or JPEG +/// is refused and said so, with no thumbnail and no perceptual hash, and the file stays in the library as it came. +/// +[TestClass] +public sealed class DamagedImageTests +{ + [TestMethod] + public void ATruncatedPngOrJpegIsDamagedAndWhatFebeDoesNotReadIsNot() + { + using var scene = TestImages.Scene(4, 320, 240); + var jpeg = TestImages.Jpeg(scene, 85); + var png = TestImages.Png(scene); + + Assert.IsFalse(DamagedImage.IsDamaged(jpeg), "un JPEG intero"); + Assert.IsFalse(DamagedImage.IsDamaged(png), "un PNG intero"); + Assert.IsTrue(DamagedImage.IsDamaged(jpeg[..(jpeg.Length / 2)]), "un JPEG che finisce a metà della scansione"); + Assert.IsTrue(DamagedImage.IsDamaged(png[..(png.Length / 2)]), "un PNG che finisce a metà dei dati"); + Assert.IsTrue(DamagedImage.IsDamaged(png[..40]), "un PNG che finisce dentro l'intestazione"); + + // Not damaged: Febe just has no picture of them. + Assert.IsFalse(DamagedImage.IsDamaged(ReadOnlyMemory.Empty)); + Assert.IsFalse(DamagedImage.IsDamaged(new byte[100]), "un formato sconosciuto"); + byte[] heic = [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. new byte[64]]; + Assert.IsFalse(DamagedImage.IsDamaged(heic), "HEIC: Febe non lo legge, ma non è rovinato"); + } + + [TestMethod] + public void AFileOnDiskIsReadOnceAndLeftAsItIs() + { + using var temp = new TempFolder(); + using var scene = TestImages.Scene(5, 200, 150); + var cut = TestImages.Jpeg(scene)[..900]; + var path = temp.Combine("foto.jpg"); + File.WriteAllBytes(path, cut); + var written = File.GetLastWriteTimeUtc(path); + + Assert.IsTrue(DamagedImage.IsFileDamaged(path)); + CollectionAssert.AreEqual(cut, File.ReadAllBytes(path), "il file resta com'è"); + Assert.AreEqual(written, File.GetLastWriteTimeUtc(path)); + Assert.IsFalse(DamagedImage.IsFileDamaged(temp.Combine("non-c-e.jpg")), "un file che non c'è non è danneggiato"); + } + + [TestMethod] + public async Task ADamagedPhotoIsStoredWithItsShaButNoThumbnailOrHashAndStays() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + using var scene = TestImages.Scene(6, 640, 480); + var whole = TestImages.Jpeg(scene, 88); + var cutJpeg = whole[..(whole.Length * 2 / 3)]; + var png = TestImages.Png(scene); + var cutPng = png[..(png.Length / 2)]; + + var saved = await library.SaveAsync(account, Make.Entry(account.Id, "701", Make.T0), [new TestFile(Make.Photo(1), cutJpeg, ".jpg"), new TestFile(Make.Photo(2), cutPng, ".png")]); + var intact = await library.SaveAsync(account, Make.Entry(account.Id, "702", Make.T0 + TimeSpan.FromHours(1)), [new TestFile(Make.Photo(1), whole, ".jpg")]); + + Assert.AreEqual(EntryState.Downloaded, saved.Entry.State, "scaricato come gli altri: niente si riscarica da sé"); + foreach (var (media, bytes) in saved.Media.Zip([cutJpeg, cutPng])) + { + Assert.AreEqual(MediaState.Downloaded, media.State); + Assert.IsNull(media.PerceptualHash, "nessuna impronta visiva: mai doppione probabile per impronta"); + Assert.IsFalse(media.HasThumbnail, "la tessera neutra"); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), media.Sha256, "lo SHA-256 sì"); + var path = library.Layout.FullPath(account, media.RelativePath!); + CollectionAssert.AreEqual(bytes, await File.ReadAllBytesAsync(path), "il file resta in libreria com'è arrivato"); + Assert.IsTrue(DamagedImage.IsFileDamaged(path)); + } + + Assert.IsNotNull(intact.Media[0].PerceptualHash, "la stessa foto intera ha la sua impronta"); + Assert.IsTrue(intact.Media[0].HasThumbnail); + } +} diff --git a/tests/Febe.Tests/Library/ImageDecodingTests.cs b/tests/Febe.Tests/Library/ImageDecodingTests.cs new file mode 100644 index 0000000..4e46587 --- /dev/null +++ b/tests/Febe.Tests/Library/ImageDecodingTests.cs @@ -0,0 +1,138 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Images; +using Febe.Core.Library; +using ImagingTestImages = Febe.Tests.Imaging.TestImages; + +namespace Febe.Tests.Library; + +/// +/// How much of a file the library reads for the size and the perceptual hash of a photo: the size from the headers +/// alone where the format allows, and hash and size from one read and one decode. +/// +[TestClass] +public sealed class ImageDecodingTests +{ + [TestMethod] + public void TheSizeOfALargeJpegComesFromItsHeaders() + { + // Noise does not compress: a JPEG well over the prefix, turned by its EXIF tag (orientation 6: shown 600×900). + using var noise = ImagingTestImages.Random(900, 600, 5, opaque: true); + var jpeg = JpegEncoder.Encode(noise, new JpegEncoderOptions { Quality = 98, Exif = Orientation(6) }); + Assert.IsGreaterThan(2 * ImageDecoding.HeaderBytes, jpeg.Length); + + using var stream = new CountingStream(jpeg); + Assert.AreEqual((600, 900), ImageDecoding.ReadSize(stream)); + Assert.AreEqual(ImageDecoding.HeaderBytes, stream.BytesRead, "solo l'inizio del file"); + + // Headers that do not fit the prefix (an ICC profile of 300 KB before the frame): the rest is read too. + var withProfile = JpegEncoder.Encode(noise, new JpegEncoderOptions { Quality = 98, Exif = Orientation(6), IccProfile = Profile(300_000) }); + using var whole = new CountingStream(withProfile); + Assert.AreEqual((600, 900), ImageDecoding.ReadSize(whole)); + Assert.AreEqual(withProfile.Length, whole.BytesRead); + + // PNG is always read whole (every chunk is checked, eXIf may come late); so is a stream that cannot seek. + var png = PngEncoder.Encode(noise); + Assert.IsGreaterThan(ImageDecoding.HeaderBytes, png.Length); + using var pngStream = new CountingStream(png); + Assert.AreEqual((900, 600), ImageDecoding.ReadSize(pngStream)); + Assert.AreEqual(png.Length, pngStream.BytesRead); + using var forward = new CountingStream(jpeg, seekable: false); + Assert.AreEqual((600, 900), ImageDecoding.ReadSize(forward)); + + // Small files, and what is not an image. + Assert.AreEqual((30, 20), ImageDecoding.ReadSize(new MemoryStream(PngEncoder.Encode(ImagingTestImages.Random(30, 20, 1))))); + Assert.IsNull(ImageDecoding.ReadSize(new MemoryStream(new byte[ImageDecoding.HeaderBytes + 10]))); + Assert.IsNull(ImageDecoding.ReadSize(new MemoryStream())); + } + + [TestMethod] + public void HashAndSizeComeFromOneDecodeOfTheSameBytes() + { + using var scene = Support.TestImages.Scene(3, 640, 480); + var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 85, Exif = Orientation(8) }); + var png = PngEncoder.Encode(scene); + foreach (var (name, file) in new[] { ("JPEG", jpeg), ("PNG", png) }) + { + var (hash, size) = PerceptualHash.ComputeWithSize(file); + Assert.AreEqual(PerceptualHash.Compute(new MemoryStream(file)), hash, name); + Assert.AreEqual(ImageDecoding.ReadSize(file), size, name); + } + + Assert.AreEqual((480, 640), PerceptualHash.ComputeWithSize(jpeg).Size, "le misure come si vede, intere anche se decodificato ridotto"); + + // A file cut inside its scan has no hash, but its headers still give the size, as ReadSize did. + var cut = jpeg[..(jpeg.Length / 2)]; + var (noHash, stillSized) = PerceptualHash.ComputeWithSize(cut); + Assert.IsNull(noHash); + Assert.AreEqual((480, 640), stillSized); + var nothing = PerceptualHash.ComputeWithSize(new byte[100]); + Assert.IsNull(nothing.Hash); + Assert.IsNull(nothing.Size); + + // From a file: read once, the same answer. + var path = Path.Combine(Path.GetTempPath(), $"febe-prova-{Guid.NewGuid():N}.jpg"); + try + { + File.WriteAllBytes(path, jpeg); + Assert.AreEqual(PerceptualHash.ComputeWithSize(jpeg), PerceptualHash.ComputeWithSizeFromFile(path)); + File.WriteAllBytes(path, []); + var empty = PerceptualHash.ComputeWithSizeFromFile(path); + Assert.IsNull(empty.Hash); + Assert.IsNull(empty.Size); + } + finally + { + File.Delete(path); + } + } + + /// A big-endian TIFF with only the Orientation tag. + private static byte[] Orientation(ushort value) + { + var tiff = new byte[8 + 2 + 12 + 4]; + "MM\0*"u8.CopyTo(tiff); + BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(4), 8); + BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(8), 1); + BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(10), 0x0112); + BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(12), 3); + BinaryPrimitives.WriteUInt32BigEndian(tiff.AsSpan(14), 1); + BinaryPrimitives.WriteUInt16BigEndian(tiff.AsSpan(18), value); + return tiff; + } + + private static byte[] Profile(int length) + { + var bytes = new byte[length]; + for (var i = 0; i < length; i++) + { + bytes[i] = (byte)((i * 13) + (i >> 5)); + } + + "RGB "u8.CopyTo(bytes.AsSpan(16)); + return bytes; + } + + /// A stream over bytes that counts what was read. + private sealed class CountingStream(byte[] data, bool seekable = true) : MemoryStream(data, writable: false) + { + public long BytesRead { get; private set; } + + public override bool CanSeek => seekable && base.CanSeek; + + public override long Length => seekable ? base.Length : throw new NotSupportedException(); + + public override long Position + { + get => seekable ? base.Position : throw new NotSupportedException(); + set => base.Position = seekable ? value : throw new NotSupportedException(); + } + + // A derived MemoryStream sends Read(Span) through Stream.Read(Span), which calls this one: counted once. + public override int Read(byte[] buffer, int offset, int count) + { + var read = base.Read(buffer, offset, count); + BytesRead += read; + return read; + } + } +} diff --git a/tests/Febe.Tests/Library/PerceptualHashTests.cs b/tests/Febe.Tests/Library/PerceptualHashTests.cs index 8e565fb..f5a688d 100644 --- a/tests/Febe.Tests/Library/PerceptualHashTests.cs +++ b/tests/Febe.Tests/Library/PerceptualHashTests.cs @@ -1,8 +1,8 @@ using System.Diagnostics; +using Febe.Core.Codecs.Images; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Tests.Support; -using SkiaSharp; namespace Febe.Tests.Library; @@ -15,7 +15,7 @@ public sealed class PerceptualHashTests private static ulong Hash(byte[] encoded) => PerceptualHash.Compute(new MemoryStream(encoded)) ?? throw new AssertFailedException("Immagine non decodificata."); - private static ulong Hash(SKBitmap bitmap) => Hash(TestImages.Png(bitmap)); + private static ulong Hash(RgbaImage image) => Hash(TestImages.Png(image)); /// /// Calibration of (spec §9.3, §14.1): resized and recompressed @@ -63,20 +63,20 @@ public sealed class PerceptualHashTests } var side = Math.Min(width, height); - var crops = new (string Name, SKRectI Area)[] + var crops = new (string Name, (int Left, int Top, int Width, int Height) Area)[] { - ("centrale 80%", SKRectI.Create(width / 10, height / 10, width * 8 / 10, height * 8 / 10)), - ("centrale 75%", SKRectI.Create(width / 8, height / 8, width * 3 / 4, height * 3 / 4)), - ("centrale 60%", SKRectI.Create(width / 5, height / 5, width * 3 / 5, height * 3 / 5)), - ("lato sinistro tolto 10%", SKRectI.Create(width / 10, 0, width * 9 / 10, height)), - ("lato sinistro tolto 25%", SKRectI.Create(width / 4, 0, width * 3 / 4, height)), - ("in alto tolto 33%", SKRectI.Create(0, height / 3, width, height * 2 / 3)), - ("quadrato", SKRectI.Create((width - side) / 2, (height - side) / 2, side, side)), - ("quarto in basso a destra", SKRectI.Create(width / 2, height / 2, width / 2, height / 2)), + ("centrale 80%", (width / 10, height / 10, width * 8 / 10, height * 8 / 10)), + ("centrale 75%", (width / 8, height / 8, width * 3 / 4, height * 3 / 4)), + ("centrale 60%", (width / 5, height / 5, width * 3 / 5, height * 3 / 5)), + ("lato sinistro tolto 10%", (width / 10, 0, width * 9 / 10, height)), + ("lato sinistro tolto 25%", (width / 4, 0, width * 3 / 4, height)), + ("in alto tolto 33%", (0, height / 3, width, height * 2 / 3)), + ("quadrato", ((width - side) / 2, (height - side) / 2, side, side)), + ("quarto in basso a destra", (width / 2, height / 2, width / 2, height / 2)), }; foreach (var (name, area) in crops) { - using var cropped = TestImages.Crop(scene, area); + using var cropped = TestImages.Crop(scene, area.Left, area.Top, area.Width, area.Height); var distance = PerceptualHash.Distance(original, Hash(TestImages.Jpeg(cropped, 90))); cropMin = Math.Min(cropMin, distance); Assert.IsGreaterThan(PerceptualHash.DuplicateThreshold, distance, $"Scena {seed}, ritaglio {name}: distanza {distance}"); diff --git a/tests/Febe.Tests/Library/ThumbnailStoreTests.cs b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs index b07a2f4..f0b23e4 100644 --- a/tests/Febe.Tests/Library/ThumbnailStoreTests.cs +++ b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs @@ -1,19 +1,24 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Images; using Febe.Core.Library; +using Febe.Tests.Imaging; using Febe.Tests.Support; -using SkiaSharp; +using TestImages = Febe.Tests.Support.TestImages; namespace Febe.Tests.Library; [TestClass] public sealed class ThumbnailStoreTests { - private static SKImageInfo InfoOf(string path) + private static ImageInfo InfoOf(string path) { - using var codec = SKCodec.Create(path) ?? throw new AssertFailedException("Miniatura non leggibile."); - Assert.AreEqual(SKEncodedImageFormat.Jpeg, codec.EncodedFormat); - return codec.Info; + var info = ImageDecoder.Identify(File.ReadAllBytes(path)); + Assert.AreEqual(ImageFormat.Jpeg, info.Format); + return info; } + private static RgbaImage Read(string path) => ImageDecoder.Decode(File.ReadAllBytes(path)); + [TestMethod] public void ThumbnailsAre480PixelsOnTheLongSideStoredOnceAndSharded() { @@ -68,17 +73,90 @@ public sealed class ThumbnailStoreTests Assert.AreEqual(360, info.Height); } + [TestMethod] + public void UprightAndTaggedSidewaysGiveTheSameThumbnail() + { + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + using var scene = TestImages.Scene(4, 1200, 900); + using var sideways = TestImages.RotateCounterClockwise(scene); + Assert.IsTrue(store.Create(Make.Sha(9), new MemoryStream(TestImages.Png(scene)))); + Assert.IsTrue(store.Create(Make.Sha(10), new MemoryStream(TestImages.WithExifOrientation(TestImages.Jpeg(sideways, 95), 6)))); + using var upright = Read(store.PathFor(Make.Sha(9))); + using var turned = Read(store.PathFor(Make.Sha(10))); + var quality = ImageQuality.Compare(upright, turned); + Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString()); + } + [TestMethod] public void TransparentImagesBecomeJpegOnWhite() { using var temp = new TempFolder(); var store = new ThumbnailStore(temp.Path); - using var transparent = new SKBitmap(new SKImageInfo(600, 600, SKColorType.Rgba8888, SKAlphaType.Premul)); - transparent.Erase(SKColors.Transparent); + using var transparent = new RgbaImage(600, 600); Assert.IsTrue(store.Create(Make.Sha(4), new MemoryStream(TestImages.Png(transparent)))); - using var thumbnail = SKBitmap.Decode(store.PathFor(Make.Sha(4))); + using var thumbnail = Read(store.PathFor(Make.Sha(4))); var pixel = thumbnail.GetPixel(10, 10); - Assert.IsGreaterThan((byte)240, pixel.Red); + Assert.IsGreaterThan((byte)240, pixel.R); + } + + [TestMethod] + public void TheThumbnailShowsThePictureReducedFaithfully() + { + // Compared with the source reduced by area averaging (the most neutral reduction), what differs is only the + // JPEG compression and the filter. + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + using var scene = TestImages.Scene(8, 2400, 1800); + Assert.IsTrue(store.Create(Make.Sha(7), new MemoryStream(TestImages.Png(scene)))); + using var thumbnail = Read(store.PathFor(Make.Sha(7))); + using var expected = ImageResampler.Resize(scene, 480, 360, new ResampleOptions { Filter = ResampleFilter.Area }); + var quality = ImageQuality.Compare(expected, thumbnail); + Assert.IsGreaterThan(28.0, quality.MinPsnr, quality.ToString()); + } + + [TestMethod] + public void AJpegShrunkWhileDecodingGivesTheSameThumbnailAsAFullDecode() + { + // 4000 × 3000 is decoded at a quarter (1000 × 750) and then reduced to 480: compared with the full-size path. + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + using var scene = TestImages.Scene(9, 4000, 3000); + var jpeg = TestImages.Jpeg(scene, 92); + Assert.IsTrue(store.Create(Make.Sha(8), new MemoryStream(jpeg))); + using var thumbnail = Read(store.PathFor(Make.Sha(8))); + Assert.AreEqual((480, 360), (thumbnail.Width, thumbnail.Height)); + using var full = ImageDecoder.Decode(jpeg); + using var reference = ImageResampler.Resize(full, 480, 360); + var quality = ImageQuality.Compare(reference, thumbnail); + Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString()); + } + + [TestMethod] + public void VideoFramesAsBmpBecomeThumbnails() + { + // The in-house video decoder (branch funzione/decoder-h264) hands frames over as 24-bit BMP, rows bottom up. + using var temp = new TempFolder(); + var store = new ThumbnailStore(temp.Path); + using var frame = TestImages.Scene(11, 1280, 720); + Assert.IsTrue(store.Create(Make.Sha(11), new MemoryStream(Bmp24(frame)))); + var info = InfoOf(store.PathFor(Make.Sha(11))); + Assert.AreEqual((480, 270), (info.Width, info.Height)); + using var thumbnail = Read(store.PathFor(Make.Sha(11))); + using var expected = ImageResampler.Resize(frame, 480, 270); + var quality = ImageQuality.Compare(expected, thumbnail); + Assert.IsGreaterThan(30.0, quality.MinPsnr, quality.ToString()); + } + + [TestMethod] + public void ThePhotoOfASearchIsASmallJpeg() + { + using var scene = TestImages.Scene(12, 1080, 1080); + var small = ThumbnailStore.EncodeSmallJpeg(new MemoryStream(TestImages.Jpeg(scene)), 160); + Assert.IsNotNull(small); + var info = ImageDecoder.Identify(small); + Assert.AreEqual((ImageFormat.Jpeg, 160, 160), (info.Format, info.Width, info.Height)); + Assert.IsNull(ThumbnailStore.EncodeSmallJpeg(new MemoryStream([1, 2, 3]), 160)); } [TestMethod] @@ -100,8 +178,14 @@ public sealed class ThumbnailStoreTests var tile = store.NeutralVideoTile(); Assert.AreEqual(Path.Combine(temp.Path, ThumbnailStore.NeutralVideoTileName), tile); var info = InfoOf(tile); - Assert.AreEqual(480, info.Height); + Assert.AreEqual((270, 480), (info.Width, info.Height)); Assert.AreEqual(tile, store.NeutralVideoTile()); + + // Light grey, a darker disc in the middle, the play sign in the light grey again. + using var image = Read(tile); + AssertGrey(image.GetPixel(10, 10), 0xE4, "sfondo"); + AssertGrey(image.GetPixel(135 - 25, 240), 0x9A, "disco"); + AssertGrey(image.GetPixel(135 + 2, 240), 0xE4, "segno di riproduzione"); } [TestMethod] @@ -140,4 +224,39 @@ public sealed class ThumbnailStoreTests Assert.IsNull(await ffmpeg.ExtractJpegAsync(temp.Combine("non-esiste.mp4"))); } + + private static void AssertGrey((byte R, byte G, byte B, byte A) pixel, int level, string what) => + Assert.IsTrue(Math.Abs(pixel.R - level) <= 4 && Math.Abs(pixel.G - level) <= 4 && Math.Abs(pixel.B - level) <= 4, $"{what}: {pixel}"); + + /// A 24-bit BI_RGB BMP, rows bottom up, the way VideoImage.ToBmp writes it. + private static byte[] Bmp24(RgbaImage image) + { + var stride = ((image.Width * 3) + 3) & ~3; + var size = 54 + (stride * image.Height); + var bmp = new byte[size]; + var span = bmp.AsSpan(); + span[0] = (byte)'B'; + span[1] = (byte)'M'; + BinaryPrimitives.WriteInt32LittleEndian(span[2..], size); + BinaryPrimitives.WriteInt32LittleEndian(span[10..], 54); + BinaryPrimitives.WriteInt32LittleEndian(span[14..], 40); + BinaryPrimitives.WriteInt32LittleEndian(span[18..], image.Width); + BinaryPrimitives.WriteInt32LittleEndian(span[22..], image.Height); + BinaryPrimitives.WriteInt16LittleEndian(span[26..], 1); + BinaryPrimitives.WriteInt16LittleEndian(span[28..], 24); + BinaryPrimitives.WriteInt32LittleEndian(span[34..], stride * image.Height); + for (var y = 0; y < image.Height; y++) + { + var source = image.GetRow(y); + var target = span.Slice(54 + ((image.Height - 1 - y) * stride), image.Width * 3); + for (var x = 0; x < image.Width; x++) + { + target[x * 3] = source[(x * 4) + 2]; + target[(x * 3) + 1] = source[(x * 4) + 1]; + target[(x * 3) + 2] = source[x * 4]; + } + } + + return bmp; + } } diff --git a/tests/Febe.Tests/Server/RemoteViewStartTests.cs b/tests/Febe.Tests/Server/RemoteViewStartTests.cs index c105d67..27f489c 100644 --- a/tests/Febe.Tests/Server/RemoteViewStartTests.cs +++ b/tests/Febe.Tests/Server/RemoteViewStartTests.cs @@ -132,6 +132,33 @@ public sealed class RemoteViewStartTests } } + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task OnlyAViewClosedByItsPageIsToldToTheConnection() + { + // Docker (answer of 25 November 2026): a view closed by its page may be Alberto leaving the browser; one replaced + // by another tab, one that did not start, or one closed because Febe stops is not. + var ct = TestContext.CancellationToken; + var told = 0; + await using var bed = new Bed(attempt => attempt == 3 ? new CdpDisconnectedException("Il collegamento con il browser si è chiuso.") : null, viewClosed: () => Interlocked.Increment(ref told)); + + var older = await bed.Host.OpenAsync(ct); + var newer = await bed.Host.OpenAsync(ct); + Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended); + Assert.AreEqual(0, Volatile.Read(ref told), "replaced by another tab: Alberto is still at the browser"); + + await newer.DisposeAsync(); + Assert.AreEqual(1, Volatile.Read(ref told), "the page closed its view"); + + await Assert.ThrowsExactlyAsync(() => bed.Host.OpenAsync(ct)); + Assert.AreEqual(1, Volatile.Read(ref told), "a view that did not start was never the page's"); + + var last = await bed.Host.OpenAsync(ct); + await bed.Host.ShutdownAsync(); + Assert.AreEqual(RemoteViewEnd.ShuttingDown, last.Ended); + Assert.AreEqual(1, Volatile.Read(ref told), "Febe stopping is not Alberto leaving"); + } + [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task PaginaInizialeOpensTheStartPageOfTheMoment() @@ -300,7 +327,8 @@ public sealed class RemoteViewStartTests /// tested in BrowserStartPageTests); null: nowhere. /// /// What «Pagina iniziale» does instead (it wins over ). - public Bed(Func startFailure, Func? startPage = null, Func? open = null) + /// What the connection is told when a view is closed by its page. + public Bed(Func startFailure, Func? startPage = null, Func? open = null, Action? viewClosed = null) { Clock = new VirtualClock(); _start = Clock.Now; @@ -326,7 +354,7 @@ public sealed class RemoteViewStartTests }; Browser = new PageBrowser(Cdp); _log = new FebeLog(null, null, Clock); - Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct))) + Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)), viewClosed: viewClosed) { // The virtual clock moves only in the pauses: a watchdog on it would never wait. Watchdog = null, diff --git a/tests/Febe.Tests/Support/LibraryTestSupport.cs b/tests/Febe.Tests/Support/LibraryTestSupport.cs index 55a0443..f07a994 100644 --- a/tests/Febe.Tests/Support/LibraryTestSupport.cs +++ b/tests/Febe.Tests/Support/LibraryTestSupport.cs @@ -1,8 +1,10 @@ using System.Buffers.Binary; +using System.Numerics; using Febe.Core.Abstractions; +using Febe.Core.Codecs.Images; using Febe.Core.Domain; +using Febe.Core.Drawing; using Febe.Data; -using SkiaSharp; namespace Febe.Tests.Support; @@ -116,37 +118,34 @@ internal static class TestDatabase public static Task OpenAsync(TempFolder folder, string name = "dati") => FebeDatabase.OpenAsync(folder.Combine(name)); } -/// Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed. +/// +/// Generated images: «photos» made of gradients, shapes, lines and grain, reproducible from a seed, drawn and encoded +/// with Febe's own code (Drawing, Codecs/Images). +/// internal static class TestImages { - public static SKBitmap Scene(int seed, int width = 1200, int height = 900) + public static RgbaImage Scene(int seed, int width = 1200, int height = 900) { var random = new Random(seed); - var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); - using var canvas = new SKCanvas(bitmap); - SKColor RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256)); + var image = new RgbaImage(width, height); + using var canvas = new Canvas(image); + Color RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256)); - using (var background = new SKPaint()) - { - var angle = random.NextDouble() * Math.PI * 2; - var dx = (float)Math.Cos(angle) * width / 2; - var dy = (float)Math.Sin(angle) * height / 2; - background.Shader = SKShader.CreateLinearGradient( - new SKPoint((width / 2f) - dx, (height / 2f) - dy), - new SKPoint((width / 2f) + dx, (height / 2f) + dy), - [RandomColor(), RandomColor(), RandomColor()], - null, - SKShaderTileMode.Clamp); - canvas.DrawRect(0, 0, width, height, background); - } + var angle = random.NextDouble() * Math.PI * 2; + var dx = (float)Math.Cos(angle) * width / 2; + var dy = (float)Math.Sin(angle) * height / 2; + var background = new LinearGradientBrush( + new Vector2((width / 2f) - dx, (height / 2f) - dy), + new Vector2((width / 2f) + dx, (height / 2f) + dy), + [RandomColor(), RandomColor(), RandomColor()]); + canvas.FillRect(0, 0, width, height, background); - using var paint = new SKPaint { IsAntialias = true }; var shapes = 10 + random.Next(10); for (var i = 0; i < shapes; i++) { - paint.Color = RandomColor().WithAlpha((byte)(160 + random.Next(96))); - paint.Style = random.Next(4) == 0 ? SKPaintStyle.Stroke : SKPaintStyle.Fill; - paint.StrokeWidth = 4 + random.Next(30); + var color = RandomColor().WithAlpha((byte)(160 + random.Next(96))); + var stroke = random.Next(4) == 0; + float strokeWidth = 4 + random.Next(30); var x = (float)(random.NextDouble() * width); var y = (float)(random.NextDouble() * height); var w = (float)((0.05 + (random.NextDouble() * 0.4)) * width); @@ -154,76 +153,94 @@ internal static class TestImages switch (random.Next(4)) { case 0: - canvas.DrawRect(x - (w / 2), y - (h / 2), w, h, paint); + if (stroke) + { + canvas.StrokeRect(x - (w / 2), y - (h / 2), w, h, strokeWidth, color); + } + else + { + canvas.FillRect(x - (w / 2), y - (h / 2), w, h, color); + } + break; case 1: - canvas.DrawCircle(x, y, Math.Min(w, h) / 2, paint); + if (stroke) + { + canvas.StrokeCircle(x, y, Math.Min(w, h) / 2, strokeWidth, color); + } + else + { + canvas.FillCircle(x, y, Math.Min(w, h) / 2, color); + } + break; case 2: - canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint); + if (stroke) + { + canvas.StrokeEllipse(x, y, w / 2, h / 2, strokeWidth, color); + } + else + { + canvas.FillEllipse(x, y, w / 2, h / 2, color); + } + break; default: - paint.StrokeWidth = 6 + random.Next(20); - canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), paint); + strokeWidth = 6 + random.Next(20); + canvas.DrawLine(x, y, (float)(random.NextDouble() * width), (float)(random.NextDouble() * height), strokeWidth, color); break; } } // Fine grain, as in a photo. - using var grain = new SKPaint { IsAntialias = false }; for (var i = 0; i < width * height / 60; i++) { var v = (byte)random.Next(256); - grain.Color = new SKColor(v, v, v, 28); - canvas.DrawPoint(random.Next(width), random.Next(height), grain); + canvas.BlendPixel(random.Next(width), random.Next(height), new Color(v, v, v, 28)); } - return bitmap; + return image; } - public static byte[] Jpeg(SKBitmap bitmap, int quality = 90) - { - using var image = SKImage.FromBitmap(bitmap); - using var data = image.Encode(SKEncodedImageFormat.Jpeg, quality); - return data.ToArray(); - } + public static byte[] Jpeg(RgbaImage image, int quality = 90) => JpegEncoder.Encode(image, new JpegEncoderOptions { Quality = quality }); - public static byte[] Png(SKBitmap bitmap) - { - using var image = SKImage.FromBitmap(bitmap); - using var data = image.Encode(SKEncodedImageFormat.Png, 100); - return data.ToArray(); - } + public static byte[] Png(RgbaImage image) => PngEncoder.Encode(image); - public static SKBitmap Resize(SKBitmap source, int width, int height) + public static RgbaImage Resize(RgbaImage source, int width, int height) => ImageResampler.Resize(source, width, height); + + /// The pixels of × from (, ). + public static RgbaImage Crop(RgbaImage source, int left, int top, int width, int height) { - var result = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); - using var canvas = new SKCanvas(result); - using var image = SKImage.FromBitmap(source); - canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null); + var result = new RgbaImage(width, height); + for (var y = 0; y < height; y++) + { + source.GetRow(top + y).Slice(left * 4, width * 4).CopyTo(result.GetRow(y)); + } + return result; } - public static SKBitmap Crop(SKBitmap source, SKRectI area) - { - var result = new SKBitmap(new SKImageInfo(area.Width, area.Height, SKColorType.Rgba8888, SKAlphaType.Premul)); - using var canvas = new SKCanvas(result); - using var image = SKImage.FromBitmap(source); - canvas.DrawImage(image, area, new SKRect(0, 0, area.Width, area.Height), new SKSamplingOptions(SKFilterMode.Nearest), null); - return result; - } - - /// Decodes a JPEG/PNG back to a bitmap. - public static SKBitmap Decode(byte[] encoded) => SKBitmap.Decode(encoded) ?? throw new InvalidOperationException("decode"); + /// Decodes a JPEG/PNG back to pixels (as stored: the orientation is not applied). + public static RgbaImage Decode(byte[] encoded) => ImageDecoder.Decode(encoded); /// Rotates pixels 90° counter-clockwise (what a camera stores before tagging orientation 6). - public static SKBitmap RotateCounterClockwise(SKBitmap source) + public static RgbaImage RotateCounterClockwise(RgbaImage source) { - var result = new SKBitmap(new SKImageInfo(source.Height, source.Width, SKColorType.Rgba8888, SKAlphaType.Premul)); - using var canvas = new SKCanvas(result); - canvas.Translate(0, source.Width); - canvas.RotateDegrees(-90); - canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null); + var result = new RgbaImage(source.Height, source.Width); + for (var y = 0; y < result.Height; y++) + { + var row = result.GetRow(y); + for (var x = 0; x < result.Width; x++) + { + // Target (x, y) shows source (w − 1 − y, x). + var (r, g, b, a) = source.GetPixel(source.Width - 1 - y, x); + row[x * 4] = r; + row[(x * 4) + 1] = g; + row[(x * 4) + 2] = b; + row[(x * 4) + 3] = a; + } + } + return result; } diff --git a/tests/Febe.Tests/Web/ConnectionApiTests.cs b/tests/Febe.Tests/Web/ConnectionApiTests.cs index b3ad536..053e05a 100644 --- a/tests/Febe.Tests/Web/ConnectionApiTests.cs +++ b/tests/Febe.Tests/Web/ConnectionApiTests.cs @@ -63,19 +63,21 @@ public sealed class ConnectionApiTests } [TestMethod] - public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows() + public async Task LeavingThePageLetsGoOfTheBrowserInDockerAndOnlyEndsTheHoldOnWindows() { - // Docker: the remote view is the page, leaving it gives the browser back to rest. + // Docker: the remote view is the page; leaving it lets go of the browser like closing the window on Windows (the + // session is copied: answer of 25 November 2026), while the button «Annulla» still cancels. var docker = new RecordingConnection(); await using (var server = await Part2.StartAsync(services: s => s.AddSingleton(docker))) { var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true }); Assert.AreEqual(HttpStatusCode.NoContent, status); + await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel"); var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show"); Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page"); } - CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls); + CollectionAssert.AreEqual(new[] { "leave", "cancel" }, docker.Calls); // Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page. var windows = new RecordingConnection(); diff --git a/tests/Febe.Tests/Web/EngineConnectionStateTests.cs b/tests/Febe.Tests/Web/EngineConnectionStateTests.cs index 46a1500..014a43d 100644 --- a/tests/Febe.Tests/Web/EngineConnectionStateTests.cs +++ b/tests/Febe.Tests/Web/EngineConnectionStateTests.cs @@ -61,6 +61,33 @@ public sealed class EngineConnectionStateTests Assert.AreEqual(JsonValueKind.Null, (await LinkAsync(EngineMode.NotConnected)).GetProperty("username").ValueKind, "Not connected: no name."); } + [TestMethod] + public async Task NotConnectedTakesCopyMissingFromTheSnapshotWithoutAskingTheBrowser() + { + // Issue #36, S4b: the engine already knows whether the copy for the requests is missing (its headline says + // «Serve «Ho finito»»); every event of the stream must not cost a look at the browser for it. + var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.SessionCopyMissing, null, null, false, null) }; + await using var server = await Part2.StartAsync(services: s => + { + s.AddSingleton(sp => new FixedModeMonitor(sp.GetRequiredService()) { Mode = EngineMode.NotConnected }); + s.AddSingleton(connection); + }); + var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService(); + var reads = connection.StatusReads; + + Assert.AreEqual("notConnected", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state"), "the engine's word, not the connection's"); + monitor.CopyMissing = true; + var engine = await server.GetJsonAsync("/api/engine"); + Assert.AreEqual("copyMissing", engine.GetProperty("connection").Str("state")); + Assert.IsTrue(engine.GetProperty("snapshot").GetProperty("sessionCopyMissing").GetBoolean()); + Assert.AreEqual(reads, connection.StatusReads, "no status asked while the engine runs"); + + // Only when the engine loop does not run is the connection asked. + monitor.Mode = EngineMode.Off; + Assert.AreEqual("copyMissing", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state")); + Assert.AreEqual(reads + 1, connection.StatusReads); + } + [TestMethod] public async Task WithoutEngineAndBrowserTheSidebarSaysNotConnectedEvenIfTuIsKnown() { @@ -76,8 +103,10 @@ public sealed class EngineConnectionStateTests { public EngineMode Mode { get; set; } = EngineMode.Resting; + public bool CopyMissing { get; set; } + public Task GetSnapshotAsync(CancellationToken ct = default) => - Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent)); + Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent) with { SessionCopyMissing = CopyMissing }); public async IAsyncEnumerable SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default) { diff --git a/tests/Febe.Tests/Web/HostingAndSecurityTests.cs b/tests/Febe.Tests/Web/HostingAndSecurityTests.cs index da67c05..e6fd1d6 100644 --- a/tests/Febe.Tests/Web/HostingAndSecurityTests.cs +++ b/tests/Febe.Tests/Web/HostingAndSecurityTests.cs @@ -47,6 +47,13 @@ public sealed class HostingAndSecurityTests // The text resource is valid JSON with the Italian texts. using var texts = JsonDocument.Parse(files.ReadText("testi/it.json")!); Assert.AreEqual("Libreria", texts.RootElement.GetProperty("nav").GetProperty("libreria").GetString()); + + // A count of one has its singular (t() picks the part before «|» when n is 1): never «1 di questi servono». + var needed = texts.RootElement.GetProperty("impostazioni").GetProperty("collegamento").GetProperty("salvata").GetProperty("servono").GetString()!; + var forms = needed.Split('|'); + Assert.HasCount(2, forms, needed); + StringAssert.StartsWith(forms[0], "{n} di questi serve "); + StringAssert.StartsWith(forms[1], "{n} di questi servono "); } [TestMethod] diff --git a/tests/Febe.Tests/Web/InterfaceTests.cs b/tests/Febe.Tests/Web/InterfaceTests.cs index 3012c62..6f2453a 100644 --- a/tests/Febe.Tests/Web/InterfaceTests.cs +++ b/tests/Febe.Tests/Web/InterfaceTests.cs @@ -90,12 +90,12 @@ public sealed class InterfaceTests await ui.OpenAsync(new Uri(server.Address, "/browser")); await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "il browser in uso con la vista aperta"); - // Another page from the sidebar: the view closes and the lease of «begin» goes too (like «Annulla»). + // Another page from the sidebar: the view closes and the page lets go of the browser (not «Annulla»: the session is copied). await ui.EvalAsync("document.querySelector('a[data-nav=libreria]').click()"); await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); - await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito lasciando la pagina"); + await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito lasciando la pagina"); await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); - CollectionAssert.AreEqual(new[] { "begin:False", "cancel" }, connection.Snapshot()); + CollectionAssert.AreEqual(new[] { "begin:False", "leave" }, connection.Snapshot()); } [TestMethod] @@ -111,7 +111,7 @@ public sealed class InterfaceTests // The document goes away (tab closed, reload, another site): only the page-hide event is left to say so. await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = "about:blank" }); - await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito chiudendo la scheda"); + await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito chiudendo la scheda"); } [TestMethod] @@ -180,6 +180,31 @@ public sealed class InterfaceTests Assert.IsFalse((await ui.EvalAsync("document.querySelector('.chi-collegato').textContent.includes('@')")).GetBoolean(), "no «@» without a name"); } + [TestMethod] + public async Task TheIncompleteCopyChoiceIsShownOnlyOnceTheServerSaysWhichOneIsStored() + { + // «Tieni la copia completa» stored; the page must not show «Sostituisci comunque» meanwhile, nor let a choice be + // made that the late answer would then undo. + var saved = new SavedSessionStatus(SavedSessionStatus.Present, null, 3, 7, 7, [], 2, 2, [], 0); + var connection = new RecordingConnection { Status = Connected with { SavedSession = saved } }; + await using var server = await DockerAsync(connection, new FakeRemoteViewHost()); + await server.Db.Settings.SetAsync(Febe.Core.Collection.Requests.SessionCopySettings.IncompleteCopyKey, Febe.Core.Collection.Requests.SessionCopySettings.KeepCompleteText); + await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.Requests); + await ui.OpenAsync(new Uri(server.Address, "/libreria")); + await ui.EvalAsync("window.__hold('/api/connection/settings')"); + await ui.NavigateAsync("/impostazioni/collegamento"); + await ui.WaitAsync("document.querySelector('.sessione-salvata input[value=\"tieni-completa\"]') !== null", "riquadro della sessione salvata"); + await ui.WaitAsync("window.__started['/api/connection/settings'] >= 1", "scelta chiesta al server"); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.sessione-salvata input[type=radio]')].every((i) => !i.checked && i.disabled)")).GetBoolean(), "neither choice shown nor pickable before the answer " + ui.Report()); + + await ui.EvalAsync("window.__release('/api/connection/settings')"); + await ui.WaitAsync("document.querySelector('.sessione-salvata input[value=\"tieni-completa\"]').checked", "la scelta salvata mostrata"); + Assert.IsFalse((await ui.EvalAsync("document.querySelector('.sessione-salvata input[value=\"sostituisci\"]').checked")).GetBoolean()); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.sessione-salvata input[type=radio]')].every((i) => !i.disabled)")).GetBoolean(), "pickable once known"); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('.scelta-ignota').hidden")).GetBoolean(), "no warning when the choice was read"); + } + [TestMethod] public async Task HoFinitoOnCollegamentoClosesTheRemoteView() { @@ -233,7 +258,7 @@ public sealed class InterfaceTests await ui.NavigateAsync("/libreria"); await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); await ui.WaitForQuietAsync("richieste della pagina finite"); - CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot(), "leaving the page gives the browser back"); + CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "leave" }, connection.Snapshot(), "leaving the page gives the browser back"); await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); } diff --git a/tests/Febe.Tests/Web/LibraryApiTests.cs b/tests/Febe.Tests/Web/LibraryApiTests.cs index 934f6f7..74ebec4 100644 --- a/tests/Febe.Tests/Web/LibraryApiTests.cs +++ b/tests/Febe.Tests/Web/LibraryApiTests.cs @@ -111,6 +111,8 @@ public sealed class LibraryApiTests Assert.AreEqual("foto_1.jpg", media[0].Str("fileName")); Assert.AreEqual(Path.Combine("marta.demo", "post"), media[0].Str("folder")); Assert.IsFalse(media[1].Bool("available"), "a file missing from disk is said, not hidden"); + Assert.IsFalse(media[0].Bool("damaged"), "a whole photo without a thumbnail yet is not damaged"); + Assert.IsFalse(media[1].Bool("damaged")); using (var file = await server.Client.GetAsync($"/api/media/{media[0].Long("id")}/file?download=1")) { @@ -149,6 +151,49 @@ public sealed class LibraryApiTests Assert.AreEqual(JsonValueKind.Null, after.GetProperty("instagramUrl").ValueKind); } + [TestMethod] + public async Task ADamagedPhotoHasTheNeutralTileTheViewerSaysSoAndItsFileStays() + { + await using var server = await WebTestServer.StartAsync(); + var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var folder = server.Library.Layout.AccountFolder(account); + Directory.CreateDirectory(Path.Combine(folder, "post")); + var whole = TestImages.Jpeg(TestImages.Scene(7, 240, 180)); + var cut = whole[..(whole.Length / 2)]; + var png = TestImages.Png(TestImages.Scene(8, 120, 90)); + var cutPng = png[..(png.Length / 2)]; + await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_1.jpg"), cut); + await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_2.png"), cutPng); + await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_3.jpg"), whole); + var added = await server.Db.Entries.AddAsync( + Make.Entry(account.Id, "1", Make.T0) with { State = EntryState.Downloaded }, + [ + Make.Stored(Make.Photo(1), Make.Sha(1), "post/foto_1.jpg") with { Bytes = cut.Length }, + Make.Stored(Make.Photo(2), Make.Sha(2), "post/foto_2.png") with { Bytes = cutPng.Length }, + Make.Stored(Make.Photo(3), Make.Sha(3), "post/foto_3.jpg") with { Bytes = whole.Length }, + ]); + var id = added.Stored.Entry.Id; + + var tile = (await server.GetJsonAsync("/api/library")).Items("tiles").Single(); + Assert.AreEqual(JsonValueKind.Null, tile.GetProperty("cover").GetProperty("thumb").ValueKind, "the neutral tile in the mosaic"); + + var media = (await server.GetJsonAsync($"/api/entries/{id}")).Items("media").ToList(); + Assert.IsTrue(media[0].Bool("damaged"), "a JPEG cut in its scan: «File danneggiato o incompleto»"); + Assert.IsTrue(media[1].Bool("damaged"), "a PNG cut in its data"); + Assert.IsFalse(media[2].Bool("damaged")); + Assert.IsTrue(media.All(m => m.Bool("available")), "the file is in the library: its actions stay"); + + // The file stays as it came, and can still be downloaded (rule 12: Febe never deletes or replaces it). + using (var file = await server.Client.GetAsync($"/api/media/{media[0].Long("id")}/file?download=1")) + { + Assert.AreEqual(HttpStatusCode.OK, file.StatusCode); + CollectionAssert.AreEqual(cut, await file.Content.ReadAsByteArrayAsync()); + } + + CollectionAssert.AreEqual(cut, await File.ReadAllBytesAsync(Path.Combine(folder, "post", "foto_1.jpg"))); + Assert.AreEqual(MediaState.Downloaded, (await server.Db.Media.GetAsync(media[0].Long("id")))!.State); + } + [TestMethod] public async Task DeletionCanLetTheEntryComeBack() { diff --git a/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs index f268362..e361ac2 100644 --- a/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs +++ b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs @@ -69,6 +69,7 @@ internal sealed class FixedProblems(params ConfigurationProblem[] problems) : IC internal sealed class RecordingConnection : IConnectionService { private readonly Lock _gate = new(); + private int _statusReads; public List Calls { get; } = []; @@ -86,7 +87,14 @@ internal sealed class RecordingConnection : IConnectionService } } - public Task GetStatusAsync(CancellationToken ct) => Task.FromResult(Status); + /// How many times the status was asked (each one costs the real connection a look at the browser). + public int StatusReads => Volatile.Read(ref _statusReads); + + public Task GetStatusAsync(CancellationToken ct) + { + Interlocked.Increment(ref _statusReads); + return Task.FromResult(Status); + } public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) { @@ -116,6 +124,14 @@ internal sealed class RecordingConnection : IConnectionService return Task.CompletedTask; } + /// Docker: the page of the browser left without «Ho finito» or «Annulla» (not «Annulla»: it copies). + public Task LeavePageAsync(CancellationToken ct) + { + Record("leave"); + Status = Status with { UserIsDriving = false }; + return Task.CompletedTask; + } + public Task ReleaseAsync(CancellationToken ct) { Record("release"); diff --git a/tests/Febe.Tests/Web/ScriptSyntaxTests.cs b/tests/Febe.Tests/Web/ScriptSyntaxTests.cs new file mode 100644 index 0000000..daea174 --- /dev/null +++ b/tests/Febe.Tests/Web/ScriptSyntaxTests.cs @@ -0,0 +1,110 @@ +using Febe.Tests.Desktop.Support; +using Febe.Tests.Web.Support; + +namespace Febe.Tests.Web; + +/// +/// The modules of the interface load: a mistake that stops one module from parsing breaks every page importing it, and +/// the Chromium tests that would see it run only in the CI. reads them without a browser. +/// +[TestClass] +public sealed class ScriptSyntaxTests +{ + [TestMethod] + public void EveryModuleOfTheInterfaceReadsWithoutTheMistakesThatStopItLoading() + { + var root = Repository.PathOf("src", "Febe.Web", "wwwroot"); + var files = Directory.GetFiles(root, "*.js", SearchOption.AllDirectories); + Assert.IsGreaterThan(30, files.Length, "the modules of the interface"); + var problems = new List(); + foreach (var file in files) + { + var name = Path.GetRelativePath(root, file); + problems.AddRange(ScriptCheck.Problems(File.ReadAllText(file)).Select(p => $"{name}, {p}")); + } + + Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems)); + } + + [TestMethod] + public void EveryStaticImportNamesSomethingTheOtherModuleExports() + { + var root = Repository.PathOf("src", "Febe.Web", "wwwroot"); + var problems = new List(); + var checkedNames = 0; + foreach (var file in Directory.GetFiles(root, "*.js", SearchOption.AllDirectories)) + { + foreach (var (from, names, line) in ScriptCheck.Imports(File.ReadAllText(file))) + { + if (!from.StartsWith('.')) + { + continue; + } + + var target = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, from)); + var where = $"{Path.GetRelativePath(root, file)}, riga {line}"; + if (!File.Exists(target)) + { + problems.Add($"{where}: «{from}» non esiste"); + continue; + } + + var exports = ScriptCheck.Exports(File.ReadAllText(target)); + foreach (var name in names) + { + checkedNames++; + if (!exports.Contains(name)) + { + problems.Add($"{where}: «{from}» non esporta «{name}»"); + } + } + } + } + + Assert.IsGreaterThan(50, checkedNames); + Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems)); + } + + [TestMethod] + [DataRow("export function box(saved, page) {\n if (!saved) return null;\n let saved = null;\n}", "«saved» dichiarato di nuovo con let (già parametro", DisplayName = "parametro ridichiarato (connection.js, b29b35a)")] + [DataRow("const show = (value) => { const value = 1; };", "«value» dichiarato di nuovo", DisplayName = "parametro di una freccia")] + [DataRow("items.map(x => { let x = 2; return x; });", "«x» dichiarato di nuovo", DisplayName = "parametro senza parentesi")] + [DataRow("function f() { let a = 1; if (a) { let b; } const a = 2; }", "«a» dichiarato di nuovo con const", DisplayName = "due volte nello stesso blocco")] + [DataRow("import { h } from './dom.js';\nconst h = 1;", "«h» dichiarato di nuovo con const (già import", DisplayName = "nome già importato")] + [DataRow("class A { m(p) { class p {} } }", "«p» dichiarato di nuovo con class", DisplayName = "classe con il nome di un parametro")] + [DataRow("function f() { if (x) { return 1; }", "mai chiusa", DisplayName = "parentesi graffa mai chiusa")] + [DataRow("const a = [1, 2);", "chiude «[»", DisplayName = "parentesi che non corrispondono")] + [DataRow("const s = 'non chiusa;\n", "stringa non chiusa", DisplayName = "stringa non chiusa")] + [DataRow("const s = `a ${b} c;\n", "modello fra apici inversi non chiuso", DisplayName = "modello non chiuso")] + public void TheCheckFindsTheMistakesThatStopAModuleLoading(string source, string expected) + { + var problems = ScriptCheck.Problems(source); + Assert.IsTrue(problems.Any(p => p.Contains(expected, StringComparison.Ordinal)), string.Join(" | ", problems.DefaultIfEmpty("(nessuno)"))); + } + + [TestMethod] + [DataRow("export function box(saved, page) {\n let stored = null;\n const show = (value) => { stored = value; };\n}", DisplayName = "la correzione di connection.js")] + [DataRow("for (let i = 0; i < 3; i++) { let i2 = i; }\nfor (let i = 0; i < 3; i++) { const j = i; }", DisplayName = "variabili dei cicli")] + [DataRow("const re = /a{2}[/}]\\//g; const half = 4 / 2; const t = `x ${ { a: 1 }.a } ${`y ${1}`}`;", DisplayName = "espressioni regolari, divisioni e modelli annidati")] + [DataRow("function f(a) { { let a = 1; } if (a) { const a = 2; } }", DisplayName = "lo stesso nome in un blocco interno")] + [DataRow("const o = { let: 1, const: 2 }; o.let = o.const;", DisplayName = "proprietà con nomi di parole chiave")] + [DataRow("try { x(); } catch (error) { console.log(error); }\nconst error = 1;", DisplayName = "parametro di catch e nome fuori")] + [DataRow("// a comment with ' and ` and {\n/* and } */ const a = \"}\";", DisplayName = "commenti e stringhe con parentesi")] + public void TheCheckLeavesValidCodeAlone(string source) + { + var problems = ScriptCheck.Problems(source); + Assert.IsEmpty(problems, string.Join(" | ", problems)); + } + + [TestMethod] + public void ImportsAndExportsAreReadByTheirNames() + { + var exports = ScriptCheck.Exports("export function a() {}\nexport async function b() {}\nexport const c = 1;\nexport class D {}\nconst e = 1, f = 2;\nexport { e, f as g };\nexport default a;"); + CollectionAssert.AreEquivalent(new[] { "a", "b", "c", "D", "e", "g", "default" }, exports.ToArray()); + var imports = ScriptCheck.Imports("import { a, b as c } from './x.js';\nimport * as y from './y.js';\nconst z = await import('./z.js');"); + Assert.HasCount(2, imports); + Assert.AreEqual("./x.js", imports[0].From); + CollectionAssert.AreEqual(new[] { "a", "b" }, imports[0].Names); + Assert.IsEmpty(imports[1].Names); + } +} diff --git a/tests/Febe.Tests/Web/Support/ScriptCheck.cs b/tests/Febe.Tests/Web/Support/ScriptCheck.cs new file mode 100644 index 0000000..ce26e4b --- /dev/null +++ b/tests/Febe.Tests/Web/Support/ScriptCheck.cs @@ -0,0 +1,610 @@ +using System.Text; + +namespace Febe.Tests.Web.Support; + +/// +/// A small check of the interface's ES modules that runs without a browser (the Chromium tests run only in the CI): it +/// reads the tokens of a module — comments, strings, template literals, regular expressions — and finds the mistakes +/// that stop a whole module from loading, so that every page importing it breaks: brackets that do not match, a +/// let, const or class declared twice in one block or with the name of a parameter of its function, +/// or of an import, and a static import of a name the other module does not export. Not a JavaScript parser: what it +/// does not understand (destructured bindings, var) it leaves alone rather than guess. +/// +internal static class ScriptCheck +{ + private static readonly HashSet RegexAfterWords = new(StringComparer.Ordinal) + { + "return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield", "await", + }; + + private static readonly HashSet NotFunctionBefore = new(StringComparer.Ordinal) + { + "if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield", + }; + + private static readonly HashSet Reserved = new(StringComparer.Ordinal) + { + "if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield", + "function", "class", "const", "let", "var", "this", "super", "null", "true", "false", "else", "do", "try", "catch", + "finally", "throw", "case", "default", "break", "continue", "import", "export", "async", "instanceof", + }; + + internal enum Kind + { + Word, + Punct, + Text, + Number, + Regex, + } + + internal readonly record struct Token(Kind Kind, string Value, int Line); + + /// The problems found in the source of one module, each with its line; empty when it reads cleanly. + public static List Problems(string source) + { + var problems = new List(); + List tokens; + try + { + tokens = Tokens(source); + } + catch (FormatException ex) + { + problems.Add(ex.Message); + return problems; + } + + CheckScopes(tokens, problems); + return problems; + } + + /// The names a module exports (export function, const, let, class, { a as b }, default). + public static HashSet Exports(string source) + { + var names = new HashSet(StringComparer.Ordinal); + var tokens = Tokens(source); + for (var i = 0; i < tokens.Count - 1; i++) + { + if (!IsWord(tokens[i], "export")) + { + continue; + } + + var j = i + 1; + if (IsWord(tokens[j], "default")) + { + names.Add("default"); + continue; + } + + if (IsWord(tokens[j], "async")) + { + j++; + } + + if (j < tokens.Count && tokens[j].Kind == Kind.Word && tokens[j].Value is "function" or "const" or "let" or "var" or "class") + { + j++; + if (j < tokens.Count && IsPunct(tokens[j], "*")) + { + j++; + } + + if (j < tokens.Count && tokens[j].Kind == Kind.Word) + { + names.Add(tokens[j].Value); + } + } + else if (j < tokens.Count && IsPunct(tokens[j], "{")) + { + for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++) + { + if (tokens[j].Kind == Kind.Word && (j + 1 >= tokens.Count || IsPunct(tokens[j + 1], ",") || IsPunct(tokens[j + 1], "}"))) + { + names.Add(tokens[j].Value); + } + } + } + } + + return names; + } + + /// The static imports of a module: the module named and the names taken from it (not «* as» nor default). + public static List<(string From, List Names, int Line)> Imports(string source) + { + var imports = new List<(string, List, int)>(); + var tokens = Tokens(source); + for (var i = 0; i < tokens.Count - 1; i++) + { + if (!IsWord(tokens[i], "import") || IsPunct(tokens[i + 1], "(") || IsPunct(tokens[i + 1], ".")) + { + continue; + } + + var names = new List(); + var j = i + 1; + for (; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++) + { + if (IsPunct(tokens[j], "{")) + { + for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++) + { + if (tokens[j].Kind == Kind.Word && !IsWord(tokens[j], "as") && (j == 0 || !IsWord(tokens[j - 1], "as"))) + { + names.Add(tokens[j].Value); + } + } + } + } + + if (j < tokens.Count && IsWord(tokens[j], "from")) + { + j++; + } + + if (j < tokens.Count && tokens[j].Kind == Kind.Text) + { + imports.Add((tokens[j].Value, names, tokens[i].Line)); + } + } + + return imports; + } + + private static bool IsWord(Token token, string value) => token.Kind == Kind.Word && token.Value == value; + + private static bool IsPunct(Token token, string value) => token.Kind == Kind.Punct && token.Value == value; + + /// The tokens of the source; throws for an unfinished string, comment or regex. + internal static List Tokens(string s) + { + var tokens = new List(); + + // Braces opened in code: '{' an ordinary one, 'E' the «${» of a template literal. + var braces = new Stack(); + var line = 1; + var i = 0; + var inTemplate = false; + + bool RegexMayStart() + { + if (tokens.Count == 0) + { + return true; + } + + var last = tokens[^1]; + return last.Kind switch + { + Kind.Punct => last.Value is not (")" or "]" or "}"), + Kind.Word => RegexAfterWords.Contains(last.Value), + _ => false, + }; + } + + void ScanTemplate() + { + // From just after a backtick or the «}» of an expression, up to the closing backtick or the next «${». + var start = line; + var text = new StringBuilder(); + while (true) + { + if (i >= s.Length) + { + throw new FormatException($"riga {start}: modello fra apici inversi non chiuso"); + } + + var c = s[i]; + if (c == '\\') + { + i += 2; + continue; + } + + if (c == '\n') + { + line++; + } + + if (c == '`') + { + i++; + inTemplate = false; + tokens.Add(new Token(Kind.Text, text.ToString(), start)); + return; + } + + if (c == '$' && i + 1 < s.Length && s[i + 1] == '{') + { + i += 2; + braces.Push('E'); + inTemplate = false; + tokens.Add(new Token(Kind.Text, text.ToString(), start)); + tokens.Add(new Token(Kind.Punct, "${", line)); + return; + } + + text.Append(c); + i++; + } + } + + while (i < s.Length || inTemplate) + { + if (inTemplate) + { + ScanTemplate(); + continue; + } + + var c = s[i]; + if (c == '\n') + { + line++; + i++; + continue; + } + + if (char.IsWhiteSpace(c)) + { + i++; + continue; + } + + if (c == '/' && i + 1 < s.Length && s[i + 1] == '/') + { + while (i < s.Length && s[i] != '\n') + { + i++; + } + + continue; + } + + if (c == '/' && i + 1 < s.Length && s[i + 1] == '*') + { + var end = s.IndexOf("*/", i + 2, StringComparison.Ordinal); + if (end < 0) + { + throw new FormatException($"riga {line}: commento non chiuso"); + } + + line += s.AsSpan(i, end - i).Count('\n'); + i = end + 2; + continue; + } + + if (c is '\'' or '"') + { + i++; + var text = new StringBuilder(); + while (true) + { + if (i >= s.Length || s[i] == '\n') + { + throw new FormatException($"riga {line}: stringa non chiusa"); + } + + if (s[i] == '\\') + { + text.Append(s[i + 1]); + i += 2; + continue; + } + + if (s[i] == c) + { + i++; + break; + } + + text.Append(s[i++]); + } + + tokens.Add(new Token(Kind.Text, text.ToString(), line)); + continue; + } + + if (c == '`') + { + i++; + inTemplate = true; + continue; + } + + if (c == '/' && RegexMayStart()) + { + var start = i++; + var inClass = false; + while (true) + { + if (i >= s.Length || s[i] == '\n') + { + throw new FormatException($"riga {line}: espressione regolare non chiusa"); + } + + if (s[i] == '\\') + { + i += 2; + continue; + } + + if (s[i] == '[') + { + inClass = true; + } + else if (s[i] == ']') + { + inClass = false; + } + else if (s[i] == '/' && !inClass) + { + i++; + break; + } + + i++; + } + + while (i < s.Length && char.IsAsciiLetter(s[i])) + { + i++; + } + + tokens.Add(new Token(Kind.Regex, s[start..i], line)); + continue; + } + + if (char.IsLetter(c) || c is '_' or '$' or '#') + { + var start = i++; + while (i < s.Length && (char.IsLetterOrDigit(s[i]) || s[i] is '_' or '$')) + { + i++; + } + + tokens.Add(new Token(Kind.Word, s[start..i], line)); + continue; + } + + if (char.IsAsciiDigit(c) || (c == '.' && i + 1 < s.Length && char.IsAsciiDigit(s[i + 1]))) + { + var start = i++; + while (i < s.Length && (char.IsAsciiLetterOrDigit(s[i]) || s[i] is '.' or '_')) + { + i++; + } + + tokens.Add(new Token(Kind.Number, s[start..i], line)); + continue; + } + + if (c == '{') + { + braces.Push('{'); + } + else if (c == '}') + { + if (braces.Count > 0 && braces.Peek() == 'E') + { + braces.Pop(); + i++; + tokens.Add(new Token(Kind.Punct, "}$", line)); + inTemplate = true; + continue; + } + + if (braces.Count > 0) + { + braces.Pop(); + } + } + + // The punctuators that matter here; any other is one character. + string[] longest = ["...", "=>", "?.", "??", "===", "!==", "==", "!=", "&&", "||", "**", "<=", ">=", "++", "--"]; + var punct = longest.FirstOrDefault(p => string.CompareOrdinal(s, i, p, 0, p.Length) == 0) ?? c.ToString(); + tokens.Add(new Token(Kind.Punct, punct, line)); + i += punct.Length; + } + + return tokens; + } + + private sealed class Frame(char open, int line, int start) + { + public char Open { get; } = open; + + public int Line { get; } = line; + + /// Index of the opening token. + public int Start { get; } = start; + + /// Names declared in this block with let, const or class, or as parameters (for a function body). + public Dictionary Names { get; } = new(StringComparer.Ordinal); + } + + private static void CheckScopes(List tokens, List problems) + { + var frames = new Stack(); + frames.Push(new Frame('m', 1, -1)); + List? pendingParams = null; + var pendingAt = -1; + + void Declare(string name, string how, int line) + { + var scope = frames.Peek(); + if (scope.Names.TryGetValue(name, out var before)) + { + problems.Add($"riga {line}: «{name}» dichiarato di nuovo con {how} (già {before} nello stesso blocco)"); + return; + } + + scope.Names[name] = how; + } + + for (var i = 0; i < tokens.Count; i++) + { + var token = tokens[i]; + var prev = i > 0 ? tokens[i - 1] : default; + if (token.Kind == Kind.Punct) + { + switch (token.Value) + { + case "{": + { + var frame = new Frame('{', token.Line, i); + if (pendingParams is not null && pendingAt == i) + { + foreach (var name in pendingParams) + { + frame.Names.TryAdd(name, "parametro"); + } + } + + frames.Push(frame); + pendingParams = null; + continue; + } + + case "(" or "[" or "${": + frames.Push(new Frame(token.Value[0], token.Line, i)); + continue; + case "}" or ")" or "]" or "}$": + { + var open = token.Value switch { "}" => '{', ")" => '(', "]" => '[', _ => '$' }; + if (frames.Count <= 1 || frames.Peek().Open != open) + { + var top = frames.Peek(); + problems.Add(top.Open == 'm' + ? $"riga {token.Line}: «{token.Value[0]}» senza apertura" + : $"riga {token.Line}: «{token.Value[0]}» chiude «{top.Open}» aperta alla riga {top.Line}"); + return; + } + + var closed = frames.Pop(); + if (open == '(') + { + OnParenClosed(tokens, closed.Start, i, ref pendingParams, ref pendingAt); + } + + continue; + } + + case "=>": + if (prev.Kind == Kind.Word && !Reserved.Contains(prev.Value)) + { + pendingParams = [prev.Value]; + pendingAt = i + 1; + } + else if (pendingParams is not null && pendingAt == i) + { + pendingAt = i + 1; // «(a, b) => {» + } + + continue; + } + + continue; + } + + if (token.Kind != Kind.Word || i + 1 >= tokens.Count || (prev.Kind == Kind.Punct && prev.Value is "." or "?.")) + { + continue; + } + + var next = tokens[i + 1]; + if (token.Value is "let" or "const" && next.Kind == Kind.Word && !Reserved.Contains(next.Value)) + { + Declare(next.Value, token.Value, next.Line); + } + else if (token.Value == "class" && next.Kind == Kind.Word && !Reserved.Contains(next.Value) && StatementStart(tokens, i)) + { + Declare(next.Value, "class", next.Line); + } + else if (token.Value == "import" && frames.Count == 1 && !IsPunct(next, "(") && !IsPunct(next, ".")) + { + for (var j = i + 1; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++) + { + var t = tokens[j]; + var after = j + 1 < tokens.Count ? tokens[j + 1] : default; + if (t.Kind == Kind.Word && !IsWord(t, "as") && !IsWord(after, "as") && !Reserved.Contains(t.Value)) + { + Declare(t.Value, "import", t.Line); + } + } + } + } + + if (frames.Count > 1) + { + var open = frames.Peek(); + problems.Add($"riga {open.Line}: «{open.Open}» mai chiusa"); + } + } + + /// A «)» just closed: when a function body follows, the simple names of its parameters are kept for it. + private static void OnParenClosed(List tokens, int open, int close, ref List? pending, ref int pendingAt) + { + var next = close + 1 < tokens.Count ? tokens[close + 1] : default; + var before = open > 0 ? tokens[open - 1] : default; + var arrow = IsPunct(next, "=>"); + var body = IsPunct(next, "{") && before.Kind == Kind.Word && (!NotFunctionBefore.Contains(before.Value) || before.Value == "function"); + if (!arrow && !body) + { + return; + } + + var names = new List(); + var depth = 0; + var pieceStart = true; + for (var j = open + 1; j < close; j++) + { + var t = tokens[j]; + if (t.Kind == Kind.Punct && t.Value is "(" or "[" or "{" or "${") + { + depth++; + } + else if (t.Kind == Kind.Punct && t.Value is ")" or "]" or "}" or "}$") + { + depth--; + } + + if (depth == 0 && IsPunct(t, ",")) + { + pieceStart = true; + continue; + } + + if (pieceStart && depth == 0) + { + pieceStart = false; + var name = IsPunct(t, "...") && j + 1 < close ? tokens[j + 1] : t; + if (name.Kind == Kind.Word && !Reserved.Contains(name.Value)) + { + names.Add(name.Value); + } + } + else if (pieceStart) + { + pieceStart = false; // a destructured parameter: left alone + } + } + + pending = names; + pendingAt = close + 1; + } + + /// True when the word at starts a statement (a declaration, not an expression). + private static bool StatementStart(List tokens, int i) + { + if (i == 0) + { + return true; + } + + var prev = tokens[i - 1]; + return (prev.Kind == Kind.Punct && prev.Value is ";" or "{" or "}") || IsWord(prev, "export") || IsWord(prev, "default"); + } +} diff --git a/tools/Febe.SitoDiProva/DirectApi.cs b/tools/Febe.SitoDiProva/DirectApi.cs index d05cc26..827988b 100644 --- a/tools/Febe.SitoDiProva/DirectApi.cs +++ b/tools/Febe.SitoDiProva/DirectApi.cs @@ -53,6 +53,15 @@ public sealed partial class TestSite /// The nonce of the page load (session:entry_nonce, header x-fb-entry-nonce; AvvioProva.nonce). public const string EntryNonce = "nonce-di-prova"; + /// The revision of the page load (session:spin_r, field __spin_r; GiroProva.revisione, a number in the page). + public const string SpinRevision = "1001"; + + /// The branch of the page load (session:spin_b, field __spin_b; GiroProva.ramo). + public const string SpinBranch = "ramo-di-prova"; + + /// The time of the page load (session:spin_t, field __spin_t; GiroProva.tempo, a number in the page). + public const string SpinTime = "1700000000"; + /// A cookie of the pages limited to the addresses under (Path=/api/): the copy keeps it with its path. public const string ApiPathCookie = "percorso_api"; @@ -258,7 +267,8 @@ public sealed partial class TestSite // The values of the page the saved session copies (S4): a missing or different one gets the same generic 400. if (form["__rev"].ToString() != Revision || form["__hs"].ToString() != HasteSession || form["__hsi"].ToString() != HasteSessionId || form["__ccg"].ToString() != ConnectionClass || form["dpr"].ToString() != Dpr || form["__comet_req"].ToString() != CometReq - || request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce) + || request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce + || form["__spin_r"].ToString() != SpinRevision || form["__spin_b"].ToString() != SpinBranch || form["__spin_t"].ToString() != SpinTime) { return ("campi", null); } diff --git a/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj b/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj index 322bb92..080282a 100644 --- a/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj +++ b/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj @@ -1,14 +1,14 @@ + Dati sintetici generati da un seme, in un formato JSON nostro (LEGGIMI.md); immagini disegnate e codificate con il + codice di Febe (Febe.Core: Drawing e Codecs/Images), nessuna libreria di grafica. --> Exe febe-sito-di-prova Febe.SitoDiProva - - +