diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index 6f63595..603ec76 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -123,7 +123,7 @@ Tutto il resto si scrive in casa, dalle specifiche pubbliche dei formati e mai c - 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. Di un MPEG-PS codec e dimensioni vengono dall'intestazione di sequenza MPEG-1 o MPEG-2, o dall'SPS di una traccia H.264 o H.265 (questa solo con il tipo di flusso 0x24 nella mappa del flusso di programma); i suoi campioni, spezzati nei pacchetti PES, non si elencano, quindi nemmeno una traccia H.264 o H.265 dà un fotogramma e la miniatura è la tessera neutra. Fra questi contenitori la miniatura viene solo da un FLV con H.264; -- rimuxaggio in MP4, senza ricodifica; +- rimuxaggio in MP4, senza ricodifica (MOV, M4V, 3GP, MKV e WebM con H.264 o HEVC e AAC o MP3, tappa E3, §4.10); - 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»; @@ -219,8 +219,8 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz - Deve restare fluida con 200.000 elementi: caricamento a finestre, miniature generate una volta e conservate. - **«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, tranne «In evidenza», disegnata per raccolta. «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. Ha una tessera solo un file presente in libreria (scaricato o importato): un file ancora da scaricare, fallito o saltato no; con i filtri «Foto» e «Video» si vedono solo i file di quel tipo. 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 elementi: elimino gli elementi interi, 9 file.»). La scelta si ricorda per pagina, una per la Libreria e una per le viste degli account, **solo nel browser in cui si fa** (memoria locale del browser, chiavi `febe.mosaico.libreria` e `febe.mosaico.account`, lette e scritte dentro un `try`): a differenza del tema, che Febe conserva nelle sue impostazioni (Impostazioni → Generali, §10.5) e ogni browser ritrova, non passa a un altro browser né alla finestra di Febe per Windows. 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. Nell'interfaccia di programmazione (`src/Febe.Web/LEGGIMI.md`) `/api/library` e `/api/library/days` prendono `mode=grouped|files` (vuoto vale `grouped`; un altro valore dà 400); con `files` il cursore della finestra è `ms.elemento.posizione` (data in millisecondi, elemento, posizione del file nella serie; raggruppato è `ms.elemento`, e un cursore malformato dà 400), e `/api/library/days` ha il campo `files`, la somma dei file presenti in libreria dei giorni (con `grouped` è `null`), mentre i totali `entries` e `accounts` contano sempre elementi. - **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é. Un HEIC che non si decodifica ha solo la tessera neutra, senza questa scritta (§3). -- 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). +- 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 (tappa E3; per un video senza fotogrammi la riga «Fotogramma non disponibile per questo video»), «È un video fermo?» a richiesta (tappa E4), e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· PNG», «· fotogramma a 0:01 · PNG») e dei file convertiti della libreria («Convertito in PNG · 2,1 MB»). +- 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); i suoi file convertiti della libreria (§4.10, «Conversione della libreria») se ne vanno con i suoi file, e la conferma li conta. - 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» in ogni linguetta tranne «In evidenza», 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. @@ -259,7 +259,7 @@ Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, più ### 4.10 Esportazione -Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Dalla tappa E2 (27 novembre 2026) le copie degli originali, accanto all'elenco CSV di §4.8; formati e fotogrammi con E3, video fermi con E4, l'automatica con E5. Fino a E3 ed E4 i loro comandi («Fotogrammi…», «Fotogramma», «È un video fermo?», i formati e la conversione della libreria) mancano dall'interfaccia, non sono spenti; fino a E5 una destinazione in pausa si riprova con «Riprova» o «Riprendi», non con il giro orario. +Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Dalla tappa E2 (27 novembre 2026) le copie degli originali, accanto all'elenco CSV di §4.8; dalla tappa E3 (28 novembre 2026) i formati delle copie, la conversione della libreria e i fotogrammi («Fotogrammi…», «Fotogramma», i menu dei formati, «Conversione della libreria»); video fermi con E4, l'automatica con E5. Fino a E4 i suoi comandi («È un video fermo?», «Salva il fotogramma») mancano dall'interfaccia, non sono spenti; fino a E5 una destinazione in pausa si riprova con «Riprova» o «Riprendi», non con il giro orario. **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». @@ -276,7 +276,7 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo **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. Si registra in `media_conversion` (migrazione `0003`, tappa E1; decisione di Alberto del 26 novembre 2026): una riga per file convertito, legata alla riga `media` dell'originale, con formato, percorso, byte, SHA-256 del convertito, data e stato; la tabella `media` non cambia. La conversione la fa la tappa E3. +- **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. Si registra in `media_conversion` (migrazione `0003`, tappa E1; decisione di Alberto del 26 novembre 2026): una riga per file convertito, legata alla riga `media` dell'originale, con formato, percorso, byte, SHA-256 del convertito, data e stato; la tabella `media` non cambia. La conversione la fa la tappa E3 (qui sotto, «Conversione della libreria»). | | Scelte | Come | |---|---|---| @@ -285,13 +285,21 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo - **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. +- **Quale formato** (tappa E3). Per ogni file vale la scelta della singola «Copia in…» («Formato: come la destinazione · Cambia»), poi quella della destinazione («Come le impostazioni generali», il predefinito), poi Impostazioni → Esportazione. Un formato nuovo vale per i file non ancora copiati («Già copiato», qui sotto). Lo stesso formato si riconosce dai byte, non dall'estensione: un `.jpg` che è un PNG si converte in JPG; un WEBP con perdita con «WEBP senza perdita» si copia byte per byte, perché ricodificarlo lo farebbe solo più grande (proposta, §16 domanda 36); un video è già MP4 quando è ISO BMFF con un marchio diverso da quello di QuickTime (`qt `) e con l'estensione `.mp4`. +- **Copiati come sono anche** (tappa E3, oltre la tabella; proposta, §16 domande 31 e 38): le immagini CMYK o YCCK e quelle con più di 8 bit per colore verso PNG e WEBP senza perdita, perché i codificatori di Febe sono RGB a 8 bit (verso JPG si convertono: un profilo ICC non RGB è detto «non tenuto», come un profilo grigio verso ogni formato); le immagini oltre 40 megapixel per WEBP e oltre 100 per PNG e JPG, con un lato oltre 16.384 pixel per WEBP, o più grandi di 512 MB. Ognuna con la sua nota («Copiato com'è: immagine CMYK», «Copiato com'è: troppo grande per il formato scelto»). Un EXIF rovinato non ferma la conversione: si lascia fuori, con la nota. +- **Rimuxaggio** (tappa E3). MOV, M4V, 3GP e Matroska (MKV, WebM) con una traccia video H.264 o HEVC e al più una traccia audio AAC o MP3 diventano MP4 copiando i campioni uno per uno, senza tenerli tutti in memoria: restano fotogrammi chiave, ordine di presentazione, l'inizio ritardato e il priming dell'AAC (l'elenco di modifiche), la rotazione, la lingua delle tracce e le date. Le tracce in più (codice di tempo, sottotitoli, una seconda traccia audio) si tolgono, e la nota lo dice («Tracce tolte: 1»). Si copia com'è, con il motivo, un video con un altro codec (VP9, AV1, Opus…), senza la configurazione del codec, con tracce Matroska codificate, con più di un taglio nell'elenco di modifiche, o in un contenitore che MP4 non prende così com'è (AVI, ASF, FLV, MPEG-PS). +- **Note e spazio** (tappa E3). Le note sono nel resoconto del lavoro (colonne «Come sono» e «Note»), nelle righe del visualizzatore e, previste dall'estensione, nel riepilogo di «Copia in…» («circa 3 HEIC copiati come sono»; «con perdita» quando almeno un file si converte in JPG). I byte del riepilogo sono quelli degli originali, «circa»; il controllo dello spazio della destinazione usa la dimensione del convertito, perché Febe converte prima di controllare. +- **Conversione della libreria** (tappa E3). Due impostazioni, Foto e Video, in Impostazioni → Esportazione, «Originale» (cioè spente) per impostazione predefinita. Il convertito si scrive accanto all'originale, nella stessa cartella, con lo stesso nome e l'estensione del formato (`nome.png`; `nome (2).png` se il nome è occupato: mai una sovrascrittura), con le regole di scrittura, i metadati e le note delle copie, e la data del file secondo `libreria.data-file-pubblicazione`. Un file già nel formato scelto, HEIC, AVIF, raw, GIF e WebM non entrano in coda; un'immagine animata o un video che non si rimuxa «non si convertono», e non si riprovano finché il file non cambia. Lavora in sottofondo, un file per volta, mai durante una sessione del motore; lascia il passo a importazione, copie e ricostruzione, che partono subito, e riprende dopo; si mette in pausa quando lo spazio libero della libreria scenderebbe sotto la soglia del disco (10 GB / 5 %) con il file da scrivere. Accenderla chiede «Convertire anche i N file già in libreria?», con lo spazio che occupano gli originali, e la risposta proposta è **«Solo i nuovi»**: un file nuovo (salvato in libreria da quando il formato è quello scelto) entra in coda dopo la sua riga di `_febe.jsonl`, anche se arriva tardi in un elemento vecchio, senza i file che l'elemento aveva già; spegnerla svuota la coda e lascia i convertiti dove sono (proposta, §16 domanda 29). Il convertito **non è mai la fonte di un'esportazione**: «Copia in…», «Fotogrammi…» e il CSV partono sempre dall'originale, che resta il file della libreria. Il visualizzatore mostra i convertiti nel pannello File, con «Scarica» o «Mostra nella cartella» e ciò che non si è tenuto (proposta, §16 domanda 30); Impostazioni → Esportazione e la scheda Esportazione della Dashboard dicono a che punto è («In coda 12 · convertiti 340 · non riusciti 2 · non si convertono 3»), con «Interrompi», «Riprendi» e «Riprova i non riusciti». Solo una scelta esplicita toglie un convertito, sempre insieme al suo originale: «Elimina dalla libreria» (la conferma li conta: «elimino gli elementi interi, 9 file e 2 file convertiti»), la rimozione di un account con i suoi file, «Tieni il più grande» per il file che si scarta; un convertito cambiato fuori da Febe dopo la conversione resta dov'è, e lo si dice. Se l'originale cambia (§4.10, «Superato»), il convertito di prima resta e si rifà quello nuovo. La ricostruzione non converte: riconosce i convertiti accanto agli originali e non li conta fra i file sconosciuti. L'importazione riconosce un convertito della libreria, o una copia convertita o un fotogramma trovati in una destinazione, come «già in libreria» («È una copia convertita (o un fotogramma) di un file già in libreria.»), mai come doppione probabile dell'originale (proposta, §16 domanda 37). **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». +- **Quali fotogrammi** (tappa E3). Gli istanti sono quelli che il lettore del visualizzatore mostra (il tempo di presentazione, con il ritardo iniziale dell'elenco di modifiche). «Questo istante» dà il fotogramma mostrato in quel momento (prima dell'inizio il primo, oltre la fine l'ultimo); dal visualizzatore la finestra si apre all'istante del lettore, con l'anteprima. «Uno ogni k secondi» parte da 0:00 (0, k, 2k… prima della fine), con k di almeno 0,1 secondi; «N in tutto» divide il video in N parti uguali e prende il centro di ognuna, (i + ½) · durata / N (proposta, §16 domanda 33). Limiti (proposta, §16 domanda 38): N da 1 a 1.000, al più 1.000 fotogrammi per video («Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo») e 20.000 per richiesta; le anteprime sono di al più 480 pixel e si fanno in 30 secondi («Il fotogramma richiede troppo tempo: scegli la cartella delle copie»). Il fotogramma è a piena risoluzione, mai ridimensionato, ruotato come il video si vede, e **senza metadati**: non ha EXIF né data del video (proposta, §16 domanda 32). Il formato proposto è **PNG** (proposta, §16 domanda 35); JPG dice «con perdita». +- **Nomi e uscite dei fotogrammi** (tappa E3). Il nome è quello del video con un suffisso prima dell'estensione: `_t0m12s340` (minuti, secondi e millesimi dell'istante del fotogramma davvero mostrato) per «Questo istante» e «Uno ogni k secondi», `_f001` (la posizione, con almeno tre cifre) per «N in tutto»; `_fotogramma` resta a «Salva il fotogramma» (E4). «Scarica»: un fotogramma è l'immagine stessa; da 2 a 20 uno zip in qualunque momento; da 21 a 500 uno zip solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione; oltre 500 solo «Nella cartella delle copie» (proposta, §16 domanda 34). Lo zip si scrive mentre si scarica, senza compressione (le immagini sono già compresse), con una cartella per account e i nomi resi unici («nome (2).png»), e si chiama `febe-fotogrammi-AAAA-MM-GG.zip`; la data delle voci segue `libreria.data-file-pubblicazione`. «Nella cartella delle copie» è un lavoro di copia verso la destinazione di ogni account, con gli stessi file dovuti di «Copia in…» (un account che non si esporta si salta e si conta); «Scarica» non guarda le destinazioni. Un video che non dà fotogrammi si salta con la nota «Fotogramma non disponibile per questo video». +- **Un fotogramma non fa «Copiato».** La copia di un fotogramma ha la sua identità, con l'istante del fotogramma mostrato in millisecondi (arrotondato in su): lo stesso fotogramma chiesto di nuovo è «già copiato», un altro istante è un'altra copia. Il video resta «Non ancora copiato» finché non c'è una sua copia intera o convertita; un elemento che ha soltanto fotogrammi copiati ha sulla tessera il segno «Solo fotogrammi», e il visualizzatore dice «· fotogramma a 0:01,125 · PNG». Un fotogramma «Tolto» o «Superato» si riscrive a una nuova richiesta esplicita (proposta, §16 domanda 32). «Una copia sola» non vale per i fotogrammi. - **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. +- Copie, conversioni e analisi lunghe partono fuori dalle sessioni del motore; esportazione, importazione e ricostruzione non girano insieme. La conversione della libreria gira in sottofondo e cede il passo a tutte e tre (tappa E3); uno zip di più di 20 fotogrammi conta come un lavoro lungo. **Manuale e automatica.** @@ -301,11 +309,12 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo **«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. +- **«Già copiato» guarda il file, non il formato** (tappa E3; proposta, §16 domanda 28, che cambia ciò che seguirebbe dall'identità qui sopra). Un file dovuto è «Copiato» in una destinazione quando ha lì una copia corrente intera o convertita, **in qualunque formato**, ed è «Tolto» o «Superato» quando lo è la sua ultima copia intera o convertita; i fotogrammi non contano. Piano, filtro «Copie», segno sulla tessera, conteggio della scheda dell'account, «Una copia sola» e copia usano questa sola regola, mentre l'identità registrata resta quella completa. Così un formato nuovo vale per i file non ancora copiati, e un file già copiato in un'altra forma si salta con «Già copiato in un altro formato». Per averlo nel formato nuovo: togliere il file vecchio dalla destinazione, «Controlla le copie» lo segna «Tolto», poi «Copia di nuovo». «Copia di nuovo» dal visualizzatore rifà **proprio quella copia** (stessa variante, formato e istante del fotogramma); la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…» usa i formati di adesso. - 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: dal visualizzatore, un file alla volta, o per tutti quelli scelti con la casella «Copia di nuovo anche i N tolti o superati» della finestra «Copia in…», spenta all'apertura (proposta, §16 domanda 25). «Tolto» lo trova «Controlla le copie» (Impostazioni → Esportazione), che guarda soltanto: con la radice della destinazione irraggiungibile non segna nulla come tolto e mette la destinazione in pausa. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà. -- **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»). +- **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 (dalla tappa E3: prima la lunghezza, poi lo SHA-256; per un rimuxaggio la lunghezza si sa prima di scrivere; una riga orfana si ricollega solo se ha la stessa forma e lo stesso SHA-256 della copia). 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»). Contano solo le copie intere o convertite dei file dovuti; un elemento senza nessuna di queste ma con almeno un fotogramma copiato ha il segno «Solo fotogrammi» (tappa E3). - **File dovuti** (tappa E2): un file è dovuto quando è presente in libreria (scaricato o importato, con il suo SHA-256), il suo account ha «Esporta questo account» acceso e una destinazione effettiva, e il suo tipo di contenuto è fra quelli della destinazione (post foto, post video, storie, evidenza, taggati, profilo; una storia in una raccolta in evidenza è anche evidenza). Il segno sulla tessera, il filtro «Copie», il conteggio della scheda dell'account e «Copia in…» considerano solo i file dovuti (proposta, §16 domanda 26), così «312 su 1.204 non ancora copiati» è proprio ciò che «Copia in…» copierebbe. Le tre scelte del filtro dividono i file dovuti senza sovrapporsi: «Copiati» (copia corrente «Copiato»), «Tolti o superati» (l'ultima copia è «Tolto» o «Superato»), «Non ancora copiati» (tutti gli altri, «Non riuscito» compreso, che la copia successiva riprova). Un account spento non ha file dovuti. -- 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». +- 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», «· PNG», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo», con le note su una seconda riga; il segno «Solo fotogrammi» sulla tessera), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie». **Casi particolari.** @@ -783,7 +792,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_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), usate dalla tappa E2 (copie degli originali; `video_analysis` e `media_conversion` aspettano E4 ed E3): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account (nessuna riga vuol dire acceso, §4.10); copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; 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 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` | +| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), usate dalla tappa E2 (copie degli originali) e dalla tappa E3 (copie convertite e fotogrammi in `export_copy` ed `export_item`, conversione della libreria in `media_conversion`, senza una migrazione nuova; `video_analysis` aspetta E4): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account (nessuna riga vuol dire acceso, §4.10); copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; 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 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Le note di un file di un lavoro (`export_item.note`) e l'ultimo errore di una conversione (`media_conversion.last_error`) sono elenchi di codici separati da spazi; per una conversione riuscita `last_error` dice ciò che non si è tenuto (tappa E3, `docs/decisioni.md`). Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` | Vincoli che contano: @@ -907,7 +916,7 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f 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, nella Libreria vuota; nella Dashboard, che `/` apre per prima, lo stesso benvenuto in un riquadro compatto sopra il cruscotto finché non c'è nessun account, §7.9); 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 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 delle copie», «Conversione della libreria» con la domanda «Convertire anche i N file già in libreria?» e la riga di stato con «Interrompi», «Riprendi» e «Riprova i non riusciti», «Una copia per account» o «Una copia sola», nota su `/esporta` in Docker; dai mockup 08 e 07); finestra della destinazione (cartella, tipi, formati con «Come le impostazioni generali», schema con anteprima, e dalla tappa E5 «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 · circa 3 HEIC copiati come sono · circa 4,2 GB», con «con perdita» quando serve) e la riga «Formato: come la destinazione · Cambia», e finestra «Fotogrammi…» (dialoghi del 13 e mockup 09: «Questo istante», «Uno ogni k secondi», «N in tutto», le anteprime, il formato, «Scarica» o «Nella cartella delle copie»); 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, anche «Solo fotogrammi» (mockup 01 e 12); nel visualizzatore «Copia in…», «Fotogramma», dalla tappa E4 «È un video fermo?», e nel pannello File le righe delle copie con la loro forma e le righe dei file convertiti (mockup 02); scheda «Esportazione» nella Dashboard con avanzamento, Interrompi, Riprendi, il riquadro «Conversione della libreria» e il resoconto con «Come sono» e «Note» (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): @@ -1175,6 +1184,17 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del | 25 | Nella finestra «Copia in…» (§4.10) si offre «Copia di nuovo anche i N tolti o superati», o «Copia di nuovo» resta solo nel visualizzatore, un file alla volta? | E2, prima di unire | Si offre nella finestra, spenta all'apertura: senza la casella i tolti e i superati si saltano e si contano. Così fa la tappa E2 | | 26 | Il conteggio della scheda dell'account, il filtro «Copie» e il segno sulla tessera (§4.10) considerano solo i file dei tipi scelti per la destinazione (con il solo «post foto», le storie non sono dovute)? | E2, prima di unire | Sì, solo i file dovuti (§4.10, «File dovuti»), così «312 su 1.204 non ancora copiati» è ciò che «Copia in…» copierebbe. Così fa la tappa E2 | | 27 | Il margine di spazio libero delle destinazioni (§4.10, «più un margine»): quanto? | E2, prima di unire | 64 MB oltre al prossimo file. Così fa la tappa E2 | +| 28 | Formati delle copie (§4.10, «Già copiato»): se il formato cambia (per esempio da Originale a JPG), i file già copiati nella forma di prima si copiano di nuovo? L'identità di una copia comprende il formato, quindi la risposta cambia che cosa vuol dire «già copiato» | E3, prima di unire | No: «già copiato» guarda il file, non il formato, e il formato nuovo vale per i file non ancora copiati; un file già copiato in un'altra forma si salta con «Già copiato in un altro formato». Per averlo nella forma nuova si toglie il file vecchio dalla destinazione, «Controlla le copie» lo segna «Tolto», poi «Copia di nuovo». L'alternativa è «già copiato» per formato: un cambio ricopierebbe ogni file nella forma nuova accanto a quella vecchia. Così fa la tappa E3 | +| 29 | Conversione della libreria accesa (§4.10): si convertono solo i file nuovi o anche quelli già in libreria? Quando entra in coda un file nuovo? Che cosa succede quando si spegne? | E3, prima di unire | Si chiede, con «Solo i nuovi» come risposta proposta e «Anche i N già in libreria» (con lo spazio degli originali) come l'altra; un file nuovo entra in coda dopo la sua riga di `_febe.jsonl`; spenta, la coda si svuota e i convertiti restano dove sono. Così fa la tappa E3 | +| 30 | Il visualizzatore mostra i file convertiti della libreria accanto all'originale, con ciò che non si è tenuto? | E3, prima di unire | Sì, nel pannello File: «Convertito in PNG · 2,1 MB», con «Scarica» o «Mostra nella cartella» e le perdite su una seconda riga. Così fa la tappa E3 | +| 31 | Immagini con più di 8 bit per colore o CMYK verso PNG o WEBP senza perdita: i codificatori di Febe sono RGB a 8 bit. Si copia l'originale con una nota o si converte lo stesso? E un profilo ICC grigio, che l'uscita RGB non tiene? | E3, prima di unire | Si copia l'originale con una nota; verso JPG si convertono (JPG perde comunque, e il profilo CMYK si dice «non tenuto»); un profilo ICC grigio si dice «non tenuto». Così fa la tappa E3 | +| 32 | Fotogrammi (§4.10): nomi `_t0m12s340` per un istante e per «uno ogni k secondi», `_f001` per «N in tutto», `_fotogramma` tenuto per E4; l'istante del nome e di «già copiato» è quello del fotogramma davvero mostrato, in millesimi arrotondati in su. I fotogrammi si ruotano come il video si vede e non hanno metadati. Un fotogramma «Tolto» o «Superato» si riscrive a una nuova richiesta. Va bene? | E3, prima di unire | Sì. Così fa la tappa E3 | +| 33 | «N in tutto»: fotogrammi al centro di N parti uguali ((i + ½) · durata / N)? «Uno ogni k secondi» da 0:00? | E3, prima di unire | Sì a tutti e due. Così fa la tappa E3 | +| 34 | «Scarica» di più fotogrammi: uno zip; fino a 20 in qualunque momento; da 21 a 500 solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione; oltre 500 solo «Nella cartella delle copie». Va bene? | E3, prima di unire | Sì. Così fa la tappa E3 | +| 35 | Formato proposto per i fotogrammi? | E3, prima di unire | PNG: nessuna perdita, piena risoluzione. Così fa la tappa E3 | +| 36 | Un WEBP con perdita con «WEBP senza perdita»: si copia byte per byte o si ricodifica senza perdita? | E3, prima di unire | Byte per byte: è lo stesso formato, e ricodificarlo lo farebbe solo più grande. Così fa la tappa E3 | +| 37 | Importare una copia convertita o un fotogramma trovati in una destinazione (o un convertito della libreria): si riconosce («È una copia convertita (o un fotogramma) di un file già in libreria.») invece di proporlo come doppione probabile dell'originale? | E3, prima di unire | Sì, «già in libreria», mai una coppia di doppioni. Così fa la tappa E3 | +| 38 | Limiti: al più 1.000 fotogrammi per video e 20.000 per richiesta, «uno ogni k secondi» con k di almeno 0,1 s, N al più 1.000; foto copiate come sono oltre 40 megapixel (WEBP) o 100 (JPG e PNG), con un lato oltre 16.384 pixel per WEBP, oltre 512 MB; anteprime di al più 480 pixel entro 30 secondi; zip di al più 500 fotogrammi. Vanno bene? Alberto non ha dato numeri | E3, prima di unire | Sì: sono i limiti di memoria e di tempo di un server di casa. Così fa la tappa E3 | --- @@ -1556,6 +1576,14 @@ Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con | 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 | +| Formato delle copie | `ExportFormat` | Originale, JPG, PNG, WEBP senza perdita, MP4: generale, della destinazione o della singola «Copia in…» (§4.10) | +| Copia convertita | `ExportVariant.Converted` | Una copia esterna in un altro formato; con l'intera e il fotogramma, una delle tre varianti di una copia (§4.10) | +| Copiato com'è | `AsIs` (codici `AsIs…`) | Un file che non si converte (HEIC, raw, animato, CMYK…) e si copia byte per byte, con una nota (§4.10) | +| Con perdita | `Lossy` | Una conversione che non tiene tutti i pixel: solo JPG, a qualità 92 (§4.10) | +| Conversione della libreria | `LibraryConversion` | Il lavoro in sottofondo che aggiunge accanto all'originale il file convertito nel formato scelto per la libreria (§4.10) | +| File convertito | `MediaConversion` | Un file aggiunto dalla conversione della libreria, legato al suo originale (`media_conversion`, §8.3) | +| Solo fotogrammi | `ExportMark.FrameOnly` | Il segno di un elemento che di copiato ha soltanto fotogrammi: non conta come «Copiato» (§4.10) | +| Note | `ExportText.Notes`, codici | Ciò che una copia o una conversione dice di sé: copiata com'è, che cosa non ha tenuto, perché si è saltata (§4.10) | | 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) | diff --git a/docs/decisioni.md b/docs/decisioni.md index 1e4ec59..d0d0ba4 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -629,3 +629,31 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-27 | Tappa E2, revisione: **«Una copia sola»** ha una regola sola in piano, filtro «Copie», visualizzatore e copiatore: conta una copia nella destinazione dell'account stesso, o una copia di **un altro account** (mai una riga generale senza account) in una destinazione in uso. `FindCopiedElsewhereAsync` riceve l'account da escludere. «Storia» del filtro comprende ogni riga «Tolto» o «Superato», con o senza data | I quattro punti davano risposte diverse per lo stesso file | | 2026-11-27 | Tappa E2, revisione: il controllo della cartella confronta anche **dove sta davvero** la cartella (`FolderIdentity`): su Windows il percorso finale (`GetFinalPathNameByHandle`, che risolve collegamenti, giunzioni, `subst` e unità di rete), su Linux `realpath` più il dispositivo `major:minor` e la cartella del suo file system letti da `/proc/self/mountinfo` (un bind mount di una cartella della libreria è dentro la radice del montaggio della libreria). Su Windows le giunzioni **sotto** la cartella scelta non si cercano | SPECIFICA §4.10, «Cartelle rifiutate»: il confronto per testo e il file di prova non vedevano un collegamento né un bind mount di una sottocartella | | 2026-11-27 | Tappa E2, revisione: lo **sfoglia delle cartelle** (`/api/export/folders`) ha un tempo massimo per l'elenco e uno per ogni sottocartella (guardate in parallelo; oltre il tempo «senza sottocartelle»); il piano dice `HasDestination`, e «Copia in…» scrive «Nessuna cartella» solo quando non ce n'è nessuna, altrimenti «file di account che non si esportano». Il visualizzatore tiene «In copia…» dopo «Copia di nuovo» e rilegge le copie alla fine del lavoro; la Dashboard fa una lettura per volta | Una condivisione morta bloccava il dialogo; le altre erano parole sbagliate o letture doppie | +| 2026-11-28 | Tappa E3: lo **zip dei fotogrammi** si scrive con l'API asincrona di `ZipArchive` (`CreateAsync`, `OpenAsync`, `DisposeAsync`) su `Response.Body`, senza abilitare l'I/O sincrono di Kestrel: .NET 10 scrive ancora in modo sincrono il piccolo descrittore di ogni voce, che `FrameService` tiene in memoria (al più 64 KB) e manda con la scrittura asincrona seguente. Il video della dimostrazione è scritto in casa (`H264PcmWriter`: solo macroblocchi I_PCM, 240×432, 8 fotogrammi al secondo, 2 s) | Un `Write` sincrono sul corpo della risposta è rifiutato da Kestrel; abilitarlo terrebbe un thread fermo per ogni lettore lento | +| 2026-11-28 | Tappa E3: **«già copiato» per file, in qualunque forma** (proposta, §16 domanda 28). Un file dovuto è «Copiato» quando ha una copia corrente intera o convertita in qualunque formato; «Tolto» o «Superato» quando lo è la sua ultima copia intera o convertita; i fotogrammi non contano mai (`variant <> 'Frame'` in `CopyStatesSql`, `ReplacedCopySql`, `ReplacedStatesSql`, `CopiedElsewhereSql` e nei rami «Non riuscito», «Tolti o superati» e «Storia» del filtro). Piano, filtro, segni, conteggio dell'account, «Una copia sola» e copiatore leggono la stessa regola (`ListCurrentCopiesAnyFormAsync`, `FindLatestCopyAnyFormAsync`, `FindCopiedElsewhereAsync(sha, exceptAccountId)`, tutte su `ix_export_copy_sha256`); l'identità registrata resta quella completa di §4.10 (`ux_export_copy_identity`). Per lo stato di un file vale «Copiato» > «Non riuscito» > l'ultima riga «Tolto»/«Superato», come il filtro di E2, dove «Non ancora copiati» comprende i non riusciti. Dopo una copia riuscita le righe «Non riuscito» delle altre forme dello stesso file si tolgono (`ClearFailedAsync`): non hanno file | Con l'identità completa un cambio di formato ricopierebbe ogni file accanto a quello vecchio; la regola sola evita che piano, filtro e copiatore dicano cose diverse | +| 2026-11-28 | Tappa E3: **richiesta ed esito**. `export_item` tiene ciò che si è chiesto (`Converted` + `Jpg`, `Frame` + `Png` + istante chiesto), `export_copy` ciò che è uscito (un HEIC chiesto in JPG è una copia `Whole`/`Original` con la nota). `UpdateItemsAsync` non cambia mai variante, formato e istante di un file. Le scelte di un lavoro di fotogrammi e il «Copia di nuovo» esatto stanno in `setting` (`esportazione.lavoro.{id}.fotogrammi` = `Istante`, `Ogni` o `Numero:N`; `esportazione.lavoro.{id}.esatta`), tolte prima di scrivere quelle di un lavoro nuovo con lo stesso numero. Nessuna migrazione `0005` | Il commento della `0003` su `export_item`; la ripresa di un lavoro deve rifare la stessa richiesta | +| 2026-11-28 | Tappa E3: **il formato di una copia** si sceglie così: la scelta della singola «Copia in…», poi quella della destinazione (le colonne `photo_format`/`video_format` di `export_destination` già nella `0003`, `null` = «Come le impostazioni generali»), poi `esportazione.formato-foto`/`-video`. Cambiare il formato di una destinazione non la ritira (lo fa solo la cartella). Sul filo i formati restano quelli di E2 (`original`, `jpg`, `png`, `webplossless`, `mp4`); `PUT /api/export/settings` è parziale e risponde `{ message, overview, queued }`, così il JavaScript che legge `message` continua a funzionare | SPECIFICA §4.10, «per le copie»: valori predefiniti che destinazione e «Copia in…» possono cambiare | +| 2026-11-28 | Tappa E3: **quando una foto si converte** (`ImageConverter.Check`): il formato si riconosce dai byte (`ImageFormatSniffer`), non dall'estensione; stesso formato → copia byte per byte (anche un WEBP con perdita verso «WEBP senza perdita», proposta, §16 domanda 36); HEIF/AVIF, TIFF e raw, ciò che non si identifica, le immagini animate (presenza di `acTL`, di `ANIM`/`ANMF`, GIF con più di un fotogramma), CMYK/YCCK e più di 8 bit verso PNG e WEBP, oltre 40 megapixel per WEBP o 100 per PNG e JPG, un lato WEBP oltre 16.384, un file oltre 512 MiB → copiato com'è con il suo codice (`AsIs…`; proposte, §16 domande 31 e 38). JPG a qualità 92, 4:4:4, trasparenza su bianco (`TransparencyWhite`). I metadati si ripuliscono **prima** dei codificatori: ciò che il formato non tiene (EXIF oltre 65.533 byte in JPG, EXIF senza intestazione TIFF, ICC non RGB o in più di 255 pezzi, IPTC, altri blocchi, testi, commento troppo lungo, XMP esteso) diventa un codice `Lost…`, mai un'eccezione; i codificatori tengono i loro controlli per chi li chiama direttamente | La memoria di un server di casa (il WEBP senza perdita vuole circa 24-28 byte per pixel: 40 megapixel sono circa 1,1 GB) e la regola «ciò che non si tiene lo dice il resoconto» | +| 2026-11-28 | Tappa E3: **stesse conversioni, stessi byte** (D9 del progetto della tappa), con la stessa versione di Febe **sullo stesso runtime di .NET**: JPEG (DCT in virgola mobile con `MathF.Round`, senza SIMD) è deterministico; in `Vp8LWriter` le stime dei costi non usano più `Math.Log2` ma un logaritmo in base 2 a virgola fissa (Q16, tabella per i valori piccoli e quadrati esatti oltre), così le scelte del codificatore WEBP non dipendono dalla libreria C (UCRT o glibc). **Limite noto:** PNG comprime con `ZLibStream` della BCL a `CompressionLevel.Optimal`, i cui byte possono cambiare con un aggiornamento di servizio di .NET; allora l'adozione per percorso di un PNG convertito prima non riconosce il file e scrive su un nome libero un secondo file uguale nei pixel. Nessun numero di versione delle conversioni è registrato: un codificatore che cambia uscita ha lo stesso effetto. Un deflate scritto in casa non è nella tappa E3; un PNG non compresso è stato scartato (file molte volte più grandi) | SPECIFICA §4.10, adozione: «i suoi codificatori sono fissi». Il danno del limite è al più un file in più, mai una sovrascrittura | +| 2026-11-28 | Tappa E3: **rimuxaggio** (`Mp4Remuxer`): ISO BMFF (`qt `, `M4V `, `3gp*`, ogni estensione non `.mp4`) e Matroska/WebM, con una traccia H.264 o HEVC (`avc1`/`avc3`/`hvc1`/`hev1` come nell'origine) e al più una AAC o MP3; un file ISO con un marchio diverso da `qt ` e l'estensione `.mp4` è già MP4 e si copia. L'elenco di modifiche dell'origine si riporta: il tratto vuoto iniziale (un inizio ritardato) e il tempo del primo tratto (il priming dell'AAC resta nascosto); più di un tratto non vuoto → rifiutato (`EditList`). MP3 nell'MP4 con l'OTI 0x6B (letto dall'`esds`, prima si scambiava per AAC), anche dentro `wave` di `mp4a`; per gli ID Matroska vecchi `A_AAC/MPEG4/…` la configurazione AAC si ricava da frequenza e canali; tracce Matroska con `ContentEncodings` rifiutate. Tracce in più tolte (`LostTracks:n`), `udta`/`meta`/tag non riportati (`LostVideoMetadata`); si tengono rotazione, lingua (`mdhd`, prima sempre «und») e date. Il lettore lavora con un «adesso» fisso (`ContainerReader.AnyDate`), così l'uscita non dipende dall'orologio; `Mp4Writer.Prepare` dà la lunghezza esatta prima di scrivere, e `Write` di prima dà gli stessi byte. In memoria solo le tabelle e il `moov`: i campioni si leggono e si scrivono uno per volta | SPECIFICA §4.10: «solo rimuxaggio, mai ricodifica»; un video non rimuxabile si copia com'è con il motivo | +| 2026-11-28 | Tappa E3: **fotogrammi** (`VideoFrameReader`). Gli istanti sono tempi di presentazione come li mostra il lettore: i PTS del lettore ISO comprendono già `ctts` e tolgono il primo tratto non vuoto, e vi si aggiunge il tratto vuoto iniziale. «Questo istante» = il campione con il tempo mostrato più grande che non supera l'istante (il primo prima dell'inizio, l'ultimo oltre la fine). La decodifica è esatta: parte da un IDR, da un CRA/BLA di HEVC o da un I di H.264 con un punto di ripresa (`recovery_frame_cnt` 0), altrimenti dal campione 0; i fotogrammi escono nell'ordine di decodifica e i nomi vengono da `Locate`. L'identità di un fotogramma copiato è l'istante del campione mostrato in millisecondi **arrotondato in su** (`frame_at_ms`): richiesto di nuovo a quell'istante trova lo stesso campione (sotto i 1.000 fotogrammi al secondo due campioni non distano meno di 1 ms); in un lavoro i doppioni si tolgono per campione, e il file del lavoro tiene l'istante chiesto. I pixel si ruotano come il video si vede (90 → EXIF 6, 180 → 3, 270 → 8) e **il fotogramma non ha metadati** (manca uno scrittore di EXIF; la data del file segue `libreria.data-file-pubblicazione`; proposta, §16 domanda 32). Oltre 8 bit si porta a 8 all'uscita. Suffissi `_t0m12s340` e `_f001` protetti dall'accorciamento a 240 caratteri (`FitPath(…, keepSuffix)`, il numero libero va dopo: `x_f001 (2).png`) | SPECIFICA §4.10, «Fotogrammi»; con l'arrotondamento in su basta una regola sola per ritrovare il fotogramma | +| 2026-11-28 | Tappa E3: **fotogrammi nelle destinazioni**: un lavoro di copia con file `Frame`, creati di seguito per video nell'ordine degli istanti; il copiatore li prende a gruppi per video e formato (anche fra due pagine di 500), apre il video una volta, scrive un fotogramma alla volta e fra l'uno e l'altro guarda sessione, interruzione e cartella: una pausa lascia in attesa il resto. Un video senza durata nota si misura quando si registra il lavoro; uno illeggibile dà un istante 0 e poi «Fotogramma non disponibile per questo video» senza riga di copia. Prima di registrare qualunque cosa il lavoro si rifiuta oltre 1.000 fotogrammi per un video o 20.000 in tutto. Nel piano un fotogramma conta 0 byte; il segno della tessera è `FrameOnly` quando l'elemento non ha copie intere o convertite e ha almeno un fotogramma copiato (proposta, §16 domande 32 e 38) | SPECIFICA §4.10: un fotogramma non fa «Copiato»; un video si legge una volta sola, non mille | +| 2026-11-28 | Tappa E3: **adozione e spazio con le conversioni**. Il file si converte **prima** dei controlli di dimensione (FAT32) e di spazio, che usano la lunghezza del convertito; il riepilogo dice «circa» con i byte degli originali. Adozione: la lunghezza, poi lo SHA-256 del file trovato contro quello della conversione; per un rimuxaggio lo SHA-256 si calcola scrivendo in un pozzo che conta e somma, solo se la lunghezza coincide. Una riga orfana di E2 si ricollega solo con lo stesso SHA-256 della copia, la stessa variante, lo stesso formato e lo stesso istante. Una foto si legge tutta in memoria e il suo SHA-256 si confronta prima di convertire; per video e fotogrammi l'origine si ricontrolla prima del cambio di nome (`SourceChanged`). Una foto oltre 512 MiB, copiata com'è, si copia in flusso | SPECIFICA §4.10, «Adozione per percorso», e lo spazio di §4.10 | +| 2026-11-28 | Tappa E3: **le note sono un elenco di codici** separati da spazi (`Codice` o `Codice:argomento`, argomento senza spazi) in `export_item.note` e in `media_conversion.last_error`; `ExportText.Note` li traduce uno per uno e li unisce con « · », e un codice sconosciuto si mostra com'è. In una riga di `media_conversion` **«Convertito»** `last_error` dice ciò che non si è tenuto (codici `Lost…`); in una «Non riuscito» il perché (`SourceMissing`, `SourceChanged`, `AccountFolderMissing`, `Error:`, oppure `AsIs…`, che non si converte). Il resoconto tiene al più 200 file con una nota e conta per account i «come sono» per etichetta | Nessuna colonna nuova: `note` e `last_error` sono `TEXT` senza vincoli. Una copia può perdere più cose insieme | +| 2026-11-28 | Tappa E3: **permesso di sottofondo** (`LongWorkGate.TryEnterBackground`, solo per `LongWorkKind.LibraryConversion`). Si prende solo se nessun lavoro lungo lo tiene; `Busy` non lo vede, così `EnsureIdle` delle copie e dell'importazione non rifiuta. `TryEnter` (sincrono, firma invariata) di un lavoro in primo piano lo toglie: sotto il lucchetto lo segna, fuori dal lucchetto annulla `Preempted` e, se il lavoro sta registrando un file (`TryBeginCommit`: un cambio di nome e una transazione, con `CancellationToken.None`), aspetta al più 10 secondi; oltre restituisce `false` con «La conversione della libreria sta salvando un file: riprova fra un attimo.». Fuori dalla registrazione il lavoro legge l'originale e scrive solo il suo `.part`, che la ricostruzione salta; quando vede la richiesta toglie il `.part` e lascia la riga «In coda». `FrameDownload` è un tipo nuovo con i suoi messaggi («scarica i fotogrammi») | SPECIFICA §4.10: la conversione cede il passo. Chi avvia copie e importazioni chiama `TryEnter` sotto i suoi lucchetti: una sospensione asincrona cambierebbe quei chiamanti, una registrazione dura millisecondi | +| 2026-11-28 | Tappa E3: **lavoro della conversione della libreria** (`LibraryConversionWorker`): un ciclo avviato con `InBackground` in `FebeApp` (non un `BackgroundService`, che con un'eccezione fermerebbe l'ospite), mai nella dimostrazione. Si sveglia con `LibraryConversionQueue.Signal()` o ogni 30 secondi, aspetta fuori dalle sessioni (ogni 5 secondi), prende 50 righe per volta; in pausa con `esportazione.libreria-sospesa` = `1`. Per ogni riga: elemento sparito → riga tolta; cartella dell'account assente → «Non riuscito» (`AccountFolderMissing`), mai creata (`RequireExistingRoot`); originale mancante → `SourceMissing`; SHA-256 cambiato → la riga prende quello nuovo; un video si somma prima del rimuxaggio; stesso formato riconosciuto dai byte → riga tolta (il vincolo `sha256 <> source_sha256` non lascia registrarla); copiato com'è → «Non riuscito» con il codice `AsIs…`, definitivo («Riprova i non riusciti» lo salta); spazio sotto `DiskThresholds.Default` con il file da scrivere → pausa con il motivo. Scrittura con `SafeFileWriter` nella cartella dell'originale, stesso nome, estensione del formato, nome libero, rilettura dal disco; adozione di un file con lo stesso SHA-256 solo se nessun file presente e nessuna conversione viva dell'account registrano quel percorso. Se alla registrazione l'elemento non c'è più (o il posto è preso), Febe toglie il file **appena scritto da lei**, dopo averne riletto lo SHA-256, mai un file adottato. Ogni errore di un file finisce in `last_error` come `Error:`; il registro ha solo il nome del tipo | Regola 11: la conversione aggiunge e non toglie; un disco staccato non deve diventare una cartella locale; nel registro mai percorsi | +| 2026-11-28 | Tappa E3: **righe della conversione sempre vere**. Un file nuovo entra in coda in `LibraryIngest.AppendJournalAsync`, dopo la sua riga di `_febe.jsonl` (scaricamento e importazione; nessun costruttore cambia). Spegnere o cambiare un formato toglie le righe «In coda» di quello di prima; i convertiti e le loro righe restano. Un originale cambiato (`ExportSupersession.FileChangedAsync`): le righe «Convertito» diventano «Superato» (il file resta), quelle «In coda» o «Non riuscito», **anche le `AsIs…`** (il verdetto era sui byte di prima), tornano «In coda» con lo SHA-256 nuovo. «Elimina dalla libreria» che ricorda la scelta segna «Tolto» i convertiti e toglie le righe senza file; «Eliminalo e lascia che torni» toglie le righe (`RemoveWithConversionsAsync`); poi il file convertito si cancella solo se il suo SHA-256 è ancora quello registrato e nessuna riga viva tiene quel percorso, altrimenti resta ed è detto. `EntryStore.RemoveAsync` resta severo: una riga «Convertito» o «Superato» lo fa fallire (`ON DELETE RESTRICT`) con un errore in italiano. Il file scartato da «Tieni il più grande» porta via i suoi convertiti in una transazione (`ForgetDeletedMediaAsync`). La ricostruzione non converte: salta i percorsi registrati, conta i convertiti accanto agli originali (`RebuildReport.ConversionsFound`) e, con la conversione accesa per quel formato, ne rimette la riga «In coda» (il lavoro poi la adotta per SHA-256); per gli elementi eliminati passa solo le conversioni il cui file manca e conta le altre (`ConversionsOfDeletedEntries`) | SPECIFICA §4.10: il convertito è legato al suo originale; regola 11 | +| 2026-11-28 | Tappa E3: **l'importazione riconosce i convertiti** (proposta, §16 domanda 37): uno SHA-256 di una conversione della libreria o di una copia convertita o di un fotogramma (`export_copy.copy_sha256` delle righe `Converted`/`Frame`) è «già in libreria», con la nota «È una copia convertita (o un fotogramma) di un file già in libreria.», mai una coppia di doppioni. Le copie si leggono una volta per importazione in un insieme in memoria (`LoadConvertedCopyShasAsync`), perché `copy_sha256` non ha un indice e la tappa non aggiunge migrazioni | Una copia convertita somiglia all'originale per impronta: senza la regola l'importazione di una destinazione proporrebbe centinaia di doppioni | +| 2026-11-28 | Tappa E3: **risorse delle conversioni**. Ogni conversione di una foto (copiatore, lavoro della libreria e fotogrammi delle destinazioni) passa da un solo `ConversionThrottle` del processo (`SemaphoreSlim(1)`) e gira con `Task.Run`; un video si legge a pezzi; un fotogramma è un'immagine RGBA alla volta. I file della libreria si aprono anche con `FileShare.Delete`, così una lettura lunga non blocca «Elimina dalla libreria» su Windows | Un server di casa con poca memoria; due conversioni di foto grandi insieme raddoppierebbero il picco | +| 2026-11-28 | Tappa E3: **fotogrammi dall'interfaccia** (`FrameService`). Anteprime e fotogrammi singoli uno alla volta, entro 30 secondi (oltre, 503 «Il fotogramma richiede troppo tempo: scegli la cartella delle copie»), con le informazioni dei video in memoria per SHA-256 (le ultime 64); anteprima JPG di al più 480 pixel, scaricamento in PNG di serie con il nome del fotogramma. «Scarica» passa da un gettone in memoria (5 minuti, un uso solo): 1 fotogramma → l'immagine, da 2 a 500 → uno zip `febe-fotogrammi-AAAA-MM-GG.zip`, non compresso, con voci `/` rese uniche come i nomi liberi e la data delle voci secondo `libreria.data-file-pubblicazione` tenuta fra il 1980 e il 2107 (i limiti dello zip). Oltre 20 fotogrammi lo zip vuole il permesso `FrameDownload` (409 altrimenti) e niente sessione del motore, lascia il permesso anche se il browser chiude, e si interrompe dopo 60 secondi senza che una scrittura vada avanti. Oltre 500 → «Per più di 500 fotogrammi scegli la cartella delle copie» (proposta, §16 domanda 34). Gli errori con un codice (409, 503) passano da `ApiStatusException` | Un browser lento non deve tenere il permesso dei lavori lunghi per sempre; uno zip grande non deve fermare il motore | +| 2026-11-28 | Tappa E3, interfaccia: un dialogo aperto dal visualizzatore resta sopra di lui (velo dei dialoghi da `z-index` 40 a 55, il visualizzatore è a 50, i menu a 60); il segno «Solo fotogrammi» è disegnato in CSS, senza un file d'icona; «Fotogrammi…» dalla selezione ha solo il campo dell'istante, senza anteprime (non c'è un video solo); il riquadro «Conversione della libreria» della Dashboard compare solo quando la conversione è accesa o ha righe; la domanda «Convertire anche i N file già in libreria?» si fa a ogni cambio verso un formato che non è «Originale», se l'anteprima trova file da convertire. La dimostrazione non avvia mai la conversione: semina una copia PNG fatta dal motore vero, un fotogramma a 1,234 s (il campione mostrato è a 1,125 s) e due righe `media_conversion` («Convertito» in PNG con il suo file e «Non riuscito» `AsIsAnimated`) | Un dialogo sotto il visualizzatore non si vedeva; un riquadro sempre presente per una funzione spenta sarebbe rumore | +| 2026-11-28 | Revisione della tappa E3, immagini: il controllo prima della conversione stima anche la memoria di lavoro del decodificatore JPEG (`ImageInfo.DecodeWorkingBytes`: un progressivo tiene i coefficienti), così un JPEG che il decodificatore rifiuterebbe esce «troppo grande» (`AsIsTooLarge`) e non «illeggibile»; un'eccezione di limite durante la conversione della libreria fa lo stesso. Un EXIF che non si tiene (illeggibile o troppo grande per il JPG) lascia comunque un EXIF minimo con il solo orientamento (`ExifOrientation.Minimal`, nell'ordine dei byte della fonte) | Il verdetto deve dire il vero motivo; senza orientamento la foto uscirebbe girata | +| 2026-11-28 | Revisione della tappa E3, fotogrammi: gli istanti di «Uno ogni k secondi» e «N in tutto» sono in millisecondi interi (`ExportFrames.WholeMs`) prima di contare i doppioni; la copia ricalcola gli istanti dalla durata (misurata se il database non la sa) e trova l'indice del nome per istante (`ExportFrames.IndexOf`), con il conteggio delle righe solo come riserva. I video di durata sconosciuta si misurano nel pianificatore (`lengthOf`, una volta per video e per richiesta) prima che si registri qualcosa, così contano nei limiti di 500 per richiesta e 5000 per video; un video che non si misura dà il solo fotogramma a 0 | Nomi e conteggi non devono dipendere dall'ordine delle righe né scoprire il troppo dopo averlo scritto | +| 2026-11-28 | Revisione della tappa E3, video: il rimuxaggio porta in MP4 la durata del segmento di `elst` (`MediaTrack.EditSegmentDuration`) e la scrive quando taglia la fine; i fotogrammi non cadono oltre la fine mostrata. Il punto di recupero H.264 vale come IDR solo con `exact_match_flag` = 1. MP3 in MP4: `objectTypeIndication` 0x69 (MPEG-2, fino a 24 kHz) o 0x6B (MPEG-1) secondo la frequenza | Un AAC con la fine tagliata è comune; un recovery point inesatto dà fotogrammi sporchi; 0x6B con 22,05 kHz è un'etichetta falsa (ISO/IEC 14496-1, tabella 5) | +| 2026-11-28 | Revisione della tappa E3, conversione della libreria: il lavoro ricontrolla il formato della riga con le impostazioni di adesso e toglie quella di un formato spento o cambiato; spegnere o cambiare un formato toglie anche i suoi «Non riuscito» (non `AsIs…`, `DeleteQueueAsync`); «Riprova» rimette solo i formati di adesso. Prima di rileggere l'originale il lavoro guarda lo spazio libero e si mette in pausa se è già sotto la soglia. «Anche i N» conta e mette in coda solo il tipo che si sta cambiando (`?photo=`/`?video=`, e nel PUT i tipi il cui formato cambia), mai l'altro che aveva già avuto «Solo i nuovi». Il PUT delle impostazioni dell'esportazione passa da un cancello (uno per volta): due clic veloci non partono dallo stesso «prima» | Una riga di un formato spento non deve scrivere file; rileggere un originale grande con il disco pieno è lavoro buttato; due cambi insieme perdevano l'uno o l'altro | +| 2026-11-28 | Revisione della tappa E3: «file nuovo» per «Solo i nuovi» vuol dire salvato in libreria (`media.downloaded_at`) da quando il formato di quel tipo è quello di adesso (`esportazione.libreria-formato-foto-dal` / `-video-dal`, in millisecondi, scritti da `OnSettingsChangedAsync`; senza la chiave ogni file è nuovo). Un file arrivato tardi in un elemento vecchio mette in coda sé, non i fratelli | Come per «Automatica» (`automatic_since` contro `media.downloaded_at`); passare gli id dai chiamanti non reggeva alle righe del giornale rimandate | +| 2026-11-28 | Revisione della tappa E3: «Elimina dalla libreria» (con memoria) e «Tieni il più grande» scelgono le righe dei convertiti nella stessa transazione che elimina (`MarkDeletedWithConversionsAsync`, `ForgetDeletedMediaAsync` che segna anche il file «Eliminato»), così un convertito registrato dal lavoro un attimo prima se ne va con il suo originale. Lo zip dei fotogrammi si scrive a pezzi di 64 KB, ognuno con i suoi 60 secondi: un browser lento che legge non si interrompe, uno fermo sì | Un convertito orfano resterebbe sul disco con la riga «Convertito»; un fotogramma grande su una linea lenta superava i 60 secondi in una scrittura sola | +| 2026-11-28 | Seconda revisione della tappa E3, video: `Mp4Writer` misura la fine della presentazione in tempo di composizione (il massimo di decodifica + scarto di composizione + durata di ogni campione), non la somma delle durate di decodifica. Con i fotogrammi B l'edit comincia al primo scarto di composizione e con la somma l'MP4 nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone), e durava altrettanto meno in `mvhd`, `tkhd` ed `elst`; il segmento della sorgente resta il limite. Vale per ogni scrittura, non solo per le sorgenti con un segmento: per una traccia senza scarti la fine è la stessa di prima e i byte non cambiano, con gli scarti il risultato di prima era sbagliato anche senza segmento (Matroska, ISO senza `elst`). | Una MOV con fotogrammi B rimuxata in MP4 (conversione della libreria o copia) deve mostrare quello che mostrava la sorgente; i fotogrammi presi dal convertito ora leggono il segmento giusto. | +| 2026-11-28 | Seconda revisione della tappa E3, conversione della libreria: il lavoro ricorda il file che l'ha messo in pausa per spazio e quanto serve al suo convertito (riga, SHA-256 dell'originale, byte), e finché il disco non ha posto anche per quello la pausa vale prima di rileggere l'originale (hash, decodifica, rimuxaggio). Non si sottraggono i byte dell'originale in anticipo: un PNG grande che diventa un JPG piccolo resterebbe fermo senza motivo. Il ricordo è del processo: dopo un riavvio l'originale si rilegge una volta. | La pausa per spazio (D17) non deve rileggere lo stesso video di 2 GB a ogni risveglio quando lo spazio libero sta fra la soglia e la soglia più il file. | +| 2026-11-28 | Seconda revisione della tappa E3: un cambio dei formati della libreria si salva in una transazione sola con le chiavi «dal» e la coda svuotata del formato sostituito (`LibraryConversionQueue.SaveSettingsAsync`, `IMediaConversionStore.SaveSettingsAndDeleteQueuesAsync`); «Anche i N» dopo il salvataggio non dipende più dalla richiesta (`CancellationToken.None`). Il gancio della libreria legge formati e chiavi «dal» con una lettura sola. | Una scheda chiusa, un arresto o un file salvato in quel momento non devono vedere il formato nuovo senza la sua chiave «dal» (che metterebbe in coda tutto l'elemento) né lasciare «Non riuscito» del formato vecchio che «Riprova» non tocca più. | +| 2026-11-28 | Seconda revisione della tappa E3, fotogrammi: i tempi di `WriteStall` dello zip passano da un `TimeProvider` della BCL (`FrameService.StallTime`, di serie quello di sistema); la prova del lettore lento usa un `TimeProvider` scritto nella prova che avanza solo quando il collegamento finto manda un pezzo. | La prova dipendeva da orologi veri con 250 ms di margine e poteva cadere su un esecutore carico della CI; ora non dipende dal carico. Nessun pacchetto esterno. | diff --git a/docs/guida/Copie-e-ricostruzione.md b/docs/guida/Copie-e-ricostruzione.md index df6fc1f..7679499 100644 --- a/docs/guida/Copie-e-ricostruzione.md +++ b/docs/guida/Copie-e-ricostruzione.md @@ -54,6 +54,9 @@ Che cosa fa: disco, e rispetta le eliminazioni (un elemento eliminato «ricordando la scelta» resta eliminato); - **non riscarica nulla** e **non sposta, non rinomina e non cancella nessun file**; - gli elementi già presenti nel database restano come sono: si può lanciare anche su un database esistente; +- non converte nulla: i file della conversione della libreria accanto ai loro originali (`foto.png` accanto a + `foto.jpg`) si riconoscono e non contano fra i file sconosciuti; se la conversione è accesa per quel formato, il file + torna nell'elenco dei convertiti dopo la ricostruzione; - mostra l'avanzamento (cartelle e file controllati) e alla fine un resoconto. Che cosa non torna: diff --git a/docs/guida/Esportazione.md b/docs/guida/Esportazione.md index feebaf0..aa2af57 100644 --- a/docs/guida/Esportazione.md +++ b/docs/guida/Esportazione.md @@ -2,11 +2,12 @@ Le **copie esterne** sono copie dei file della libreria in cartelle fuori da Febe: un disco USB, una chiavetta, una cartella di rete, un'altra cartella del server. La libreria non cambia: Febe legge i suoi file e li copia così come -sono, byte per byte. Non riscarica nulla e non apre Instagram: è solo lavoro sul disco. +sono, byte per byte, oppure convertiti in un altro formato (vedi «Formati»), oppure ne prende dei fotogrammi (vedi +«Fotogrammi»). Non riscarica nulla e non apre Instagram: è solo lavoro sul disco. -In questa versione (tappa E2) si copiano gli **originali**. Le copie in un altro formato e i fotogrammi dei video -arrivano con la tappa E3, l'analisi dei video fermi con la E4, le copie automatiche con la E5: fino ad allora quei -comandi non ci sono. +In questa versione (tappa E3) ci sono le copie degli originali, i formati delle copie, la conversione della libreria e +i fotogrammi dei video. L'analisi dei video fermi arriva con la tappa E4 e le copie automatiche con la E5: fino ad +allora quei comandi («È un video fermo?», «Automatica») non ci sono. > **Le copie esterne escono dal controllo di Febe.** Chi ha la cartella di una copia, o il disco su cui sta, ha quei > file, comprese le foto e i video di altre persone. Febe non le cifra, non le cancella e, dopo averle scritte, ne sa @@ -78,13 +79,54 @@ quando quell'account ne ha una). La finestra conta prima di copiare: quanti file, quanti già copiati (saltati), quanti tolti o superati (saltati), quanti di account che non si esportano, quanti non presenti in libreria, circa quanto spazio, e lo spazio libero di ogni cartella. **«Copia di nuovo anche i N tolti o superati»** è spenta: accendila se vuoi riscriverli (vedi «Stati»). -«Copia N file» fa partire il lavoro e la finestra si chiude: le copie vanno avanti da sole e si seguono nella Dashboard. +La riga **«Formato: come la destinazione · Cambia»** dice in che formato arrivano i file; «Cambia» lo sceglie solo per +questa copia (vedi «Formati»), e il riepilogo dice allora anche quanti file si copiano come sono («circa 3 HEIC copiati +come sono») e «con perdita» se qualche file diventa JPG. «Copia N file» fa partire il lavoro e la finestra si chiude: +le copie vanno avanti da sole e si seguono nella Dashboard. Si copiano solo i **file dovuti**: i file presenti in libreria di un account che si esporta e ha una cartella delle copie, del tipo che quella cartella copia. Il segno sulle tessere, il filtro «Copie», il conteggio della scheda dell'account e «Copia in…» contano tutti e soli questi file, così «312 su 1.204 non ancora copiati» è proprio ciò che «Copia in…» copierebbe. +## Formati + +Di solito le copie sono gli **originali**, byte per byte. Puoi chiedere invece che arrivino in un altro formato: + +| | Scelte | +|---|---| +| Foto | **Originale** (di solito), JPG, PNG, WEBP senza perdita | +| Video | **Originale** (di solito), MP4 | + +Il formato si sceglie in tre posti, e vale il più vicino alla copia: **«Cambia»** nella finestra «Copia in…» (solo per +quella copia), la parte **«Formati»** della finestra di una cartella («Come le impostazioni generali», di solito), +**Impostazioni ▸ Esportazione ▸ «Formati delle copie»**. + +- **Con perdita solo se lo scegli.** JPG è l'unico formato con perdita: Febe lo scrive a **qualità 92**, e la finestra lo + dice («con perdita: qualità 92», «con perdita» nel riepilogo). La trasparenza in JPG diventa bianco. PNG e WEBP senza + perdita tengono tutti i pixel. +- **Video in MP4: solo rimuxaggio, mai ricodifica.** Febe porta in MP4 un MOV, un M4V, un 3GP o un MKV/WebM con video + H.264 o HEVC e audio AAC o MP3, copiando i fotogrammi così come sono: tengono qualità, rotazione, lingua delle tracce + e date. Tracce in più (codice di tempo, sottotitoli, una seconda traccia audio) si tolgono, e la nota lo dice. Un + video con un altro codec (VP9, AV1, Opus…) si copia com'è. +- **Un file già in quel formato si copia byte per byte**, mai ricodificato. Febe lo riconosce dal contenuto, non dal + nome: un `.jpg` che in realtà è un PNG si converte. Un WEBP con perdita resta com'è anche con «WEBP senza perdita». +- **Si copiano come sono, con una nota:** HEIC, AVIF, raw (`.dng`, `.cr2`, `.nef`…), le immagini animate (GIF, WEBP e + PNG animati: convertite perderebbero i fotogrammi dopo il primo), ciò che Febe non riesce a leggere, le immagini CMYK + o con più di 8 bit per colore verso PNG e WEBP, le immagini troppo grandi per il formato (oltre 40 megapixel per WEBP, + oltre 100 per JPG e PNG, oltre 512 MB), i video che non si portano in MP4 senza ricodificarli. +- **I metadati vengono con il file:** EXIF (l'orientamento resta un dato, i pixel non si ruotano), profilo ICC, XMP; per + i video date, rotazione e lingua. Ciò che il formato non può tenere (un EXIF troppo grande per JPG, un profilo ICC non + RGB…) lo dicono le note («Non tenuto: profilo ICC»). +- **Un formato nuovo vale per i file non ancora copiati.** Un file già copiato in un'altra forma resta «Copiato» e si + salta («Già copiato in un altro formato»). Se lo vuoi anche nel formato nuovo: togli il file vecchio dalla cartella, + «Controlla le copie» lo segna «Tolto», poi «Copia di nuovo». +- Il riepilogo prevede le note dal nome dei file e dice lo spazio degli originali, «circa»: un convertito può occupare + di più. Lo spazio della cartella Febe lo controlla sul file convertito, prima di scriverlo. + +Le note di ogni file stanno nel **resoconto** del lavoro (Dashboard ▸ Esportazione ▸ «Resoconto», colonne «Come sono» e +«Note») e nelle righe del visualizzatore. + ## Come Febe scrive una copia - Prima di ogni gruppo di copie (al più 100 file o 1 GB) Febe scrive e toglie un file di prova nella cartella. Se non @@ -97,7 +139,8 @@ dell'account e «Copia in…» contano tutti e soli questi file, così «312 su della libreria, poi prende il nome definitivo. **Febe non sovrascrive mai un file**: se il nome è occupato da un altro file, scrive `nome (2).jpg` e lascia l'altro com'è. Non cancella e non sposta nulla nelle cartelle delle copie; i `.part` rimasti da una copia interrotta li toglie solo nelle cartelle di quel lavoro, mai frugando nel resto. -- La data del file segue l'impostazione della libreria «Imposta la data del file a quella di pubblicazione». +- La data del file segue l'impostazione della libreria «Imposta la data del file a quella di pubblicazione», anche + per i file convertiti e i fotogrammi. - Non si copia durante una sessione del motore: la copia aspetta che la sessione finisca («Aspetto la fine della sessione del motore»). Copie, importazione e ricostruzione del database non girano insieme: mentre una lavora, le altre due aspettano che finisca o che la interrompi. @@ -106,28 +149,31 @@ dell'account e «Copia in…» contano tutti e soli questi file, così «312 su Se nel posto dove andrebbe la copia c'è già un file **identico** (stesso SHA-256 dell'originale), Febe lo adotta come copia invece di scriverne un secondo: succede dopo un database perso o ricostruito, con un backup vecchio della -cartella, con due Febe sulla stessa cartella. La sola dimensione non basta mai: un file diverso con la stessa -dimensione resta com'è, e la copia va su un nome libero. +cartella, con due Febe sulla stessa cartella. Per un file convertito o un fotogramma Febe rifà la conversione e vuole +lo stesso SHA-256 del file che trova. La sola dimensione non basta mai: un file diverso con la stessa dimensione resta +com'è, e la copia va su un nome libero. ## Stati di una copia | Stato | Che cosa vuol dire | |---|---| -| **Copiato** | Il file è nella cartella, uguale all'originale | +| **Copiato** | Il file è nella cartella, uguale all'originale o convertito nel formato chiesto | | **Tolto** | Il file non c'è più nella cartella (l'hai spostato o cancellato tu, o il disco è un altro). Lo trova «Controlla le copie» in Impostazioni ▸ Esportazione, che guarda soltanto e non tocca nessun file. Con il disco staccato non segna nulla come tolto: mette la cartella in pausa | | **Superato** | Il file della libreria è cambiato dopo la copia: «Tieni il più grande» fra due doppioni, un'importazione che sostituisce, una ricostruzione che trova un altro file. La copia vecchia resta | | **Non riuscito** | La copia non si è potuta fare (per esempio il limite di FAT32): la prossima «Copia in…» ci riprova | **Tolto e Superato non si ricopiano mai da soli.** «Copia di nuovo», nel pannello File del visualizzatore accanto alla riga della copia, oppure la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…», scrive un file nuovo, e -la copia vecchia resta dov'è. Eliminare un elemento dalla libreria non tocca le sue copie. +la copia vecchia resta dov'è. Dal visualizzatore rifà proprio quella copia, nella sua forma (intero, PNG, il fotogramma +a quell'istante…); la casella di «Copia in…» usa i formati di adesso. Eliminare un elemento dalla libreria non tocca le +sue copie. Dove si vede: - un piccolo **segno sulla tessera** (solo se c'è almeno una cartella delle copie), con «2/3» per un post copiato in - parte; -- le righe del **pannello File** del visualizzatore: «Copiato in Disco USB il 3 novembre · intero», «Tolto da…», - «Superato in…», con «Copia di nuovo»; + parte e un piccolo riquadro, **«Solo fotogrammi»**, per un elemento di cui sono stati copiati solo dei fotogrammi; +- le righe del **pannello File** del visualizzatore: «Copiato in Disco USB il 3 novembre · intero», «… · PNG», + «… · fotogramma a 0:01,125 · PNG», «Tolto da…», «Superato in…», con «Copia di nuovo» e, sotto, le note; - il conteggio nella **scheda dell'account** («312 su 1.204 non ancora copiati», i tolti o superati, i non riusciti); - il filtro **«Copie»** in Libreria e nella scheda dell'account: Tutti, Non ancora copiati, Copiati, Tolti o superati. Resta nell'indirizzo della pagina (`?copie=non-copiati`). @@ -141,6 +187,79 @@ Quando lo stesso file è il post di un account e il taggato di un altro, Imposta - **«Una copia sola»**: si copia una volta, nel primo account che lo copia; l'altro lo mostra «Copiato» con la cartella dove sta. +## Fotogrammi + +Un **fotogramma** è un'immagine presa da un video, a piena risoluzione e girata come il video si vede. Si chiede: + +- dal **visualizzatore**, con **«Fotogramma»** sotto un video: il video si ferma e la finestra si apre all'istante in + cui era, con l'anteprima e il cursore per spostarsi; +- dalla **selezione**, in Libreria e nella scheda di un account: «Seleziona», scegli le tessere, **«Fotogrammi…»** nella + barra in basso. Lo stesso istante (o la stessa regola) vale per ogni video scelto; **le foto si saltano**, e la + finestra lo dice. + +Quali fotogrammi: + +- **Questo istante**: il fotogramma che il video mostra in quel momento (scrivi l'istante come `0:12` o `0:12,5`); oltre + la fine, l'ultimo; +- **Uno ogni k secondi**: da 0:00, poi ogni k secondi fino alla fine (k almeno 0,1 secondi); +- **N in tutto**: il video diviso in N parti uguali, un fotogramma al centro di ognuna (da 1 a 1.000). + +Dal visualizzatore la finestra mostra le anteprime dei primi sei («e altri N»). Formato: **PNG** (di solito, nessuna +perdita), JPG (con perdita) o WEBP senza perdita. **Il fotogramma non ha l'audio**, e la finestra lo ricorda; non ha +nemmeno i metadati del video. Un video in un codec che Febe non decodifica (VP9, AV1…) o rovinato dice **«Fotogramma +non disponibile per questo video»**. + +Dove vanno: + +- **«Scarica»**: un fotogramma si scarica com'è; più fotogrammi in uno **zip** (`febe-fotogrammi-AAAA-MM-GG.zip`, una + cartella per account). Fino a 20 fotogrammi lo zip si fa in qualunque momento; da 21 a 500 solo fuori dalle sessioni + del motore e quando non lavorano importazione, copie o ricostruzione; per più di 500 scegli la cartella delle copie. + «Scarica» non guarda le cartelle delle copie né «Esporta questo account». +- **«Nella cartella delle copie»**: un lavoro di copia, come «Copia in…», nella cartella di ogni account, accanto alle + copie, con gli stessi file dovuti (gli account che non si esportano si saltano e si contano). Si segue nella + Dashboard. + +I nomi sono quelli del video con l'istante: `video_t0m12s340.png` (0 minuti, 12 secondi e 340 millesimi: l'istante del +fotogramma davvero mostrato) per «Questo istante» e «Uno ogni k secondi», `video_f001.png`, `video_f002.png`… per «N in +tutto». Al più 1.000 fotogrammi per video («Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo») e +20.000 per volta. + +**Un fotogramma non fa «copiato» il video:** il video resta «Non ancora copiato» finché non ne copi il file intero, e +un elemento con soli fotogrammi ha il segno «Solo fotogrammi». Lo stesso fotogramma chiesto di nuovo nella stessa +cartella è «già copiato»; un fotogramma «Tolto» si riscrive quando lo chiedi di nuovo. + +## Conversione della libreria + +Oltre alle copie, Febe può tenere **nella libreria** un file convertito accanto a ogni foto o video: Impostazioni ▸ +Esportazione ▸ **«Conversione della libreria»**, Foto (JPG, PNG, WEBP senza perdita) e Video (MP4). Di solito è spenta +(«Originale»). + +- **Il file convertito si aggiunge: l'originale resta**, con il suo nome. Il convertito va nella stessa cartella, con lo + stesso nome e l'estensione nuova (`foto.png` accanto a `foto.jpg`; `foto (2).png` se il nome è già preso: mai una + sovrascrittura), con le stesse regole e le stesse note delle copie. +- Resta l'originale il file della libreria: SHA-256, miniatura, doppioni, `_febe.jsonl`, «Copia in…», «Fotogrammi…» e + l'elenco CSV usano sempre l'originale. Il convertito non si riscarica e non è un doppione. +- Quando la accendi Febe chiede **«Convertire anche i N file già in libreria?»**, con lo spazio che occupano gli + originali (i convertiti possono occupare di più): **«Solo i nuovi»** converte da adesso in poi, ogni file dopo il + suo scaricamento o la sua importazione; «Anche i N già in libreria» li mette tutti in coda. Spegnerla svuota la coda; + i file già convertiti restano dove sono. +- Lavora **in sottofondo**, un file alla volta, mai durante una sessione del motore; quando parte un'importazione, una + copia o una ricostruzione si fa da parte e riprende dopo. Con il disco della libreria quasi pieno (sotto 10 GB o il 5 % + liberi, contando il file da scrivere) si mette in pausa e lo dice. +- **A che punto è**: in Impostazioni ▸ Esportazione e nella Dashboard, scheda Esportazione («In coda 12 · convertiti 340 + · non riusciti 2 · non si convertono 3»), con **«Interrompi»**, **«Riprendi»** e **«Riprova i non riusciti»**. «Non si + converte» vuol dire che il file resta solo originale (HEIC, raw, un'immagine animata, un video che non va in MP4 + senza ricodifica): non si riprova finché il file non cambia. +- Nel **visualizzatore**, pannello File: «Convertito in PNG · 2,1 MB» con «Mostra nella cartella» (Windows) o «Scarica», + e sotto ciò che non si è tenuto. +- Solo tu togli un convertito, sempre con il suo originale: «Elimina dalla libreria» (la conferma li conta: «… 9 file e + 2 file convertiti»), la rimozione di un account con i suoi file, «Tieni il più grande» per il file che scarti. Un + convertito che hai cambiato tu dopo la conversione resta dov'è, e Febe lo dice. Se l'originale cambia, il convertito + di prima resta e se ne fa uno nuovo. +- La ricostruzione del database non converte e riconosce i convertiti accanto agli originali; l'importazione riconosce + un convertito, o una copia convertita o un fotogramma di una cartella delle copie, come già in libreria («È una copia + convertita (o un fotogramma) di un file già in libreria.»). + ## La Dashboard, scheda Esportazione La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportazione`). @@ -150,8 +269,11 @@ La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportaz - **Da riprendere:** le cartelle in pausa con il motivo e **«Riprova»**; le copie interrotte o in pausa con **«Riprendi»** (riparte dai file che mancano) e **«Annulla»** (i file già copiati restano, gli altri non si copiano); **«Riprendi tutte»**. Una copia interrotta da un arresto di Febe si ritrova qui al riavvio: non riparte da sola. +- **Conversione della libreria** (quando è accesa o ha già lavorato): a che punto è, con «Interrompi», «Riprendi» e + «Riprova i non riusciti». - **Ultimi lavori**, ognuno con il suo **«Resoconto»**: copiati, già presenti e riconosciuti, già copiati, saltati, non - presenti in libreria, non riusciti, per account, e i file da guardare con il motivo. + presenti in libreria, non riusciti, per account (con i file copiati come sono), i file da guardare con il motivo e le + note dei file copiati (che cosa non si è tenuto, che cosa si è copiato com'è). Quando ci sono copie da riprendere o cartelle in pausa, la scheda Motore lo dice con un avviso. diff --git a/docs/guida/Home.md b/docs/guida/Home.md index 342918a..5827132 100644 --- a/docs/guida/Home.md +++ b/docs/guida/Home.md @@ -49,6 +49,8 @@ fare solo con Instagram o su Windows: Unraid. - **Copie esterne degli originali (tappa E2, 27 novembre 2026):** pronte, da provare dal vivo su Unraid con `/esporta` montata e su Windows con una cartella di rete. Vedi [Copie esterne](Esportazione). +- **Formati, fotogrammi e conversione della libreria (tappa E3, 28 novembre 2026):** pronti, da provare dal vivo con + foto e video veri della tua libreria (HEIC e MOV del telefono compresi). Vedi [Copie esterne](Esportazione). ## Pagine della guida @@ -60,7 +62,7 @@ fare solo con Instagram o su Windows: | [Account e impostazioni](Account-e-impostazioni) | Aggiungere account, punti di partenza, impostazioni per account | | [Libreria](Libreria) | Mosaico, filtri, visualizzatore, eliminazione, esportazione CSV, nomi dei file | | [Importazione](Importazione) | Portare in libreria foto e video che hai già, senza doppioni | -| [Copie esterne](Esportazione) | Copiare i file della libreria su un disco esterno o una cartella di rete: cartelle, «Copia in…», stati delle copie, `/esporta` in Docker | +| [Copie esterne](Esportazione) | Copiare i file della libreria su un disco esterno o una cartella di rete: cartelle, «Copia in…», formati, fotogrammi, conversione della libreria, stati delle copie, `/esporta` in Docker | | [Limiti e comportamento](Limiti-e-comportamento) | Profili di prudenza, tetti, fascia oraria, ritmo delle sessioni | | [Dashboard e arresti](Dashboard-e-arresti) | La Dashboard, pagina iniziale e cruscotto del motore; che cosa fare dopo una verifica o un rallentamento | | [Avvisi e Telegram](Avvisi-e-Telegram) | Striscia, notifiche di Windows, messaggi Telegram con un bot tuo | diff --git a/docs/guida/Importazione.md b/docs/guida/Importazione.md index 0572fd6..dd5c4b2 100644 --- a/docs/guida/Importazione.md +++ b/docs/guida/Importazione.md @@ -43,7 +43,9 @@ Quattro contatori: I doppioni si cercano anche dentro la sorgente stessa (una copia identica nella sorgente si copia una volta sola). Per i video vale solo lo SHA-256 (e il codice). Un file che hai eliminato «ricordando la scelta» conta come già in -libreria: un'importazione non annulla un'eliminazione. +libreria: un'importazione non annulla un'eliminazione. Anche un file convertito della libreria, o una copia convertita +o un fotogramma presi da una cartella delle copie ([Copie esterne](Esportazione)), conta come già in libreria («È una +copia convertita (o un fotogramma) di un file già in libreria.»), mai come doppione probabile dell'originale. **Cartelle e account.** Una tabella lega ogni cartella della sorgente a un account: uno esistente (riconosciuto per identificativo o per nome), oppure un nuovo account «Solo archivio» con il nome della cartella. Una cartella senza diff --git a/docs/guida/Libreria.md b/docs/guida/Libreria.md index 1243d7e..cf864df 100644 --- a/docs/guida/Libreria.md +++ b/docs/guida/Libreria.md @@ -43,7 +43,9 @@ si legge «Libreria, file 12 di 61.034». A lato: la serie dei file, didascalia, - **Mostra nella cartella** (Windows) oppure **Scarica** il file (dal browser, in Docker); - **Apri su Instagram**, nel tuo browser; -- **Elimina dalla libreria**. +- **Elimina dalla libreria**; +- con le copie esterne, **«Copia in…»** e, per i video, **«Fotogramma»** (vedi [Copie esterne](Esportazione)); nel + pannello File le righe delle copie e, con la conversione della libreria accesa, dei file convertiti. ## Eliminare @@ -55,7 +57,9 @@ Eliminare chiede conferma. I file vengono cancellati dal disco e non si recupera scarica di nuovo. L'eliminazione si scrive prima nel file `_febe.jsonl` dell'account, poi nel database, poi sul disco: anche una -ricostruzione del database la rispetta. +ricostruzione del database la rispetta. Se la conversione della libreria ha aggiunto dei file convertiti, se ne vanno +con i loro originali e la conferma li conta («… 9 file e 2 file convertiti»); un convertito che hai cambiato tu resta. +Le copie esterne invece restano dove sono. **La libreria non cancella e non sostituisce mai un file da sola.** Se un contenuto sparisce da Instagram, il file resta. Un file si elimina o si sostituisce solo per una scelta tua. @@ -63,7 +67,8 @@ resta. Un file si elimina o si sostituisce solo per una scelta tua. ## Selezione multipla «Seleziona» attiva la scelta delle tessere; nella barra in basso: **Esporta l'elenco** degli elementi scelti oppure -**Elimina** (con la stessa conferma di sopra). «Fine» chiude la selezione. +**Elimina** (con la stessa conferma di sopra); **Fotogrammi…** per i video scelti; con una cartella delle copie anche +«Copia in…» ([Copie esterne](Esportazione)). «Fine» chiude la selezione. Con «Tutte le foto» si scelgono i file, ma l'elenco CSV ed «Elimina» lavorano sugli **elementi interi** a cui appartengono: la barra lo dice («3 file scelti, di 2 elementi», «Elimina 2 elementi») e anche la conferma («3 file diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index ce3a02a..90f734a 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -152,6 +152,16 @@ Vedi anche [Copie esterne](Esportazione). | «C'è un lavoro di copia non finito verso questa cartella…» | Prima di cambiare la cartella, riprendi o annulla quel lavoro nella Dashboard, scheda Esportazione | | «Copia in…» dice «N di account che non si esportano» | Quegli account hanno «Esporta questo account» spento (scheda dell'account ▸ Impostazioni ▸ «Copie esterne») | | «Copia in…» o il filtro «Copie» non ci sono | Manca una cartella delle copie: scegline una in Impostazioni ▸ Esportazione (o nella scheda dell'account) | +| Ho scelto JPG ma un file è arrivato com'è («HEIC copiato com'è», «Immagine animata copiata com'è…», «Copiato com'è: …») | È voluto: HEIC, AVIF, raw, immagini animate, immagini CMYK o con più di 8 bit verso PNG e WEBP e quelle troppo grandi non si convertono. Le note sono nel resoconto e nel visualizzatore | +| «Video copiato com'è: non si porta in MP4 senza ricodificarlo (codec video)» | Il video non è H.264 o HEVC (o l'audio non è AAC o MP3, o il contenitore non si rimuxa): Febe non ricodifica mai, quindi lo copia com'è | +| «Già copiato in un altro formato» | Il file è già nella cartella in un'altra forma. Per averlo nel formato nuovo: togli il file vecchio dalla cartella, «Controlla le copie», poi «Copia di nuovo» | +| «Fotogramma non disponibile per questo video» | Il video è in un codec che Febe non decodifica (VP9, AV1…) o è rovinato. Il video intero si copia lo stesso | +| «Il fotogramma richiede troppo tempo: scegli la cartella delle copie» | Un video lungo o grande non dà l'anteprima in 30 secondi: scegli «Nella cartella delle copie», che lavora senza fretta | +| «Il motore è in sessione: per più di 20 fotogrammi riprova fra poco» | Uno zip di più di 20 fotogrammi si prepara solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione: riprova dopo, o scegli meno fotogrammi | +| «Per più di 500 fotogrammi scegli la cartella delle copie» o «Più di 1.000 fotogrammi per un video…» | Sono i limiti di «Scarica» e di un video: scegli «Nella cartella delle copie», o un intervallo più lungo | +| La conversione della libreria non va avanti: «Il motore è in sessione…», «Un'importazione, una copia o una ricostruzione è al lavoro…» | È voluto: la conversione lavora in sottofondo e cede il passo. Riprende da sola | +| «Spazio libero sotto la soglia: la conversione della libreria è in pausa» | Il disco della libreria è quasi pieno: libera spazio (o spegni la conversione); riprende da sola | +| Un file convertito «non si converte» o «Conversione … non riuscita» | «Non si converte» è definitivo (HEIC, raw, animata…); per gli altri, se la cartella dell'account era staccata o il file mancava, sistema e premi «Riprova i non riusciti» in Impostazioni ▸ Esportazione | ## Database diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index c4ee796..d3e68e3 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -119,4 +119,5 @@ trattale come i dati che descrivono. Le [copie esterne](Esportazione) escono dal controllo di Febe: chi ha la cartella delle copie, o il disco su cui sta, ha quei file, foto e video di altre persone compresi. Febe non le cifra e non le cancella; nelle cartelle delle copie non scrive diari, identificativi o didascalie, solo i file. Una chiavetta o un disco con le copie va trattato come la -libreria. +libreria. Lo stesso vale per i fotogrammi scaricati e per i loro zip, che finiscono nei download del browser. Una +conversione con perdita (JPG) è una scelta tua: Febe non la fa mai da sola. diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md index d053d8c..a97e2fc 100644 --- a/docs/prove-dal-vivo.md +++ b/docs/prove-dal-vivo.md @@ -549,7 +549,7 @@ cambiano». Se i nomi sono diversi, il catalogo va corretto prima di configurare --- -## F. Copie esterne (tappa E2): Docker con `/esporta`, FAT32, cartella di rete su Windows +## F. Copie esterne (tappe E2 ed E3): Docker con `/esporta`, FAT32, cartella di rete su Windows, formati, fotogrammi Scopo: vedere sul tuo impianto ciò che le prove automatiche non possono fare (specifica §4.10, §11, §12): un montaggio vero su Unraid, un disco FAT32 vero, una condivisione che si stacca. **Non serve Instagram**: le copie leggono solo @@ -618,10 +618,67 @@ in quelle cartelle, né crearne la cartella scelta. 5. Facoltativo: esci da Febe durante una copia e riaprilo. Atteso: la copia è «Interrotta» nella scheda Esportazione e non riparte da sola; nel registro «N copie interrotte dall'arresto precedente…». -### F5. Che cosa riferire +### F5. Formati delle copie con i tuoi file (tappa E3) + +Le prove automatiche convertono immagini e video costruiti da loro; qui servono file veri del tuo telefono e della +libreria: qualche JPG con la posizione nell'EXIF, una foto HEIC, un PNG con la trasparenza, una GIF animata, un MOV +dell'iPhone (meglio se girato in verticale) e un video con VP9 o AV1, se ne hai uno (per esempio un WebM). + +1. Impostazioni ▸ Esportazione ▸ «Formati delle copie»: Foto **JPG**, Video **MP4**. Atteso: «con perdita: qualità 92» + sotto JPG, «solo rimuxaggio, mai ricodifica» sotto MP4. +2. «Copia in…» su quei file. Atteso nel riepilogo: «circa 1 HEIC copiato com'è», «con perdita». Copia, poi + «Resoconto»: l'HEIC, la GIF e il video VP9/AV1 «come sono», con la nota; il PNG con «La trasparenza è diventata + bianco». +3. Nella cartella delle copie: il JPG di partenza è **identico** all'originale (confronta lo SHA-256, per esempio con + `Get-FileHash` su Windows o `sha256sum` su Unraid); il PNG è diventato `.jpg`, con lo sfondo bianco dove era + trasparente; il MOV è diventato `.mp4`, si apre nel browser e nel lettore di sistema, è **diritto** come l'originale, + ha l'audio e la stessa durata, e le proprietà del file (Windows: Proprietà ▸ Dettagli) hanno la stessa data di + ripresa; la foto convertita ha ancora l'EXIF (data, fotocamera, posizione) e l'orientamento giusto. +4. Cambia Foto in **PNG** e rifai «Copia in…» sugli stessi file. Atteso: «già copiati, saltati» e nel resoconto «Già + copiato in un altro formato»; nessun file nuovo. Togli a mano un JPG convertito dalla cartella, «Controlla le copie», + poi «Copia di nuovo» dal visualizzatore: atteso di nuovo il JPG (la forma di quella copia), non un PNG. +5. Rimetti i formati su «Originale». + +### F6. Fotogrammi (tappa E3) + +1. Apri nel visualizzatore un video vero H.264 (un reel scaricato) e uno HEVC (un MOV dell'iPhone recente). Ferma il + lettore su un'immagine riconoscibile e premi «Fotogramma». Atteso: la finestra si apre a quell'istante e + l'anteprima è **la stessa immagine** che vedevi; «Il fotogramma non ha l'audio.». +2. «Scarica» in PNG. Atteso: un file `…_t0m…s….png` della piena risoluzione del video, diritto come il video si vede. +3. «N in tutto» = 5, «Scarica». Atteso: uno zip `febe-fotogrammi-AAAA-MM-GG.zip` con una cartella dell'account e + cinque file `…_f001.png` … `…_f005.png`, distribuiti lungo il video. +4. Su un video VP9 o AV1 (o una tessera neutra): atteso «Fotogramma non disponibile per questo video». +5. Dalla Libreria: «Seleziona», scegli alcuni video e qualche foto, «Fotogrammi…», «Uno ogni 10 secondi», «Nella + cartella delle copie». Atteso: «le N foto si saltano»; il lavoro nella Dashboard; nella cartella i fotogrammi accanto + alle copie, con l'istante nel nome. Le tessere dei video copiati solo come fotogrammi hanno il segno «Solo + fotogrammi» e il filtro «Copie» li mette fra i «Non ancora copiati». +6. Facoltativo: durante una sessione del motore chiedi lo zip di 30 fotogrammi. Atteso: «Il motore è in sessione: per + più di 20 fotogrammi riprova fra poco»; fuori dalla sessione lo zip parte. + +### F7. Conversione della libreria (tappa E3) + +Prima: annota il numero dei file di una cartella di account e lo SHA-256 di due o tre originali (`Get-FileHash` o +`sha256sum`). Alla fine gli originali devono essere **identici** e i file solo in più. + +1. Impostazioni ▸ Esportazione ▸ «Conversione della libreria»: Foto **PNG**. Atteso il dialogo «Convertire anche i N + file già in libreria?» con lo spazio degli originali; scegli **«Solo i nuovi»**. Atteso: niente in coda. +2. Importa (o lascia scaricare) due o tre foto JPG nuove. Atteso, fuori dalle sessioni del motore e entro un minuto o + due: «convertiti 3» nella riga di stato; accanto a ogni `foto.jpg` della libreria un `foto.png`; il visualizzatore + mostra «Convertito in PNG · …» con «Mostra nella cartella» (Windows) o «Scarica». +3. Avvia un'importazione grande mentre la conversione lavora (con «Anche i N già in libreria» su un account piccolo). + Atteso: l'importazione parte subito; la conversione dice «Un'importazione, una copia o una ricostruzione è al + lavoro…» e riprende dopo. +4. «Interrompi», poi «Riprendi». Atteso: si ferma e riparte; i file già convertiti restano. +5. Elimina dalla libreria un elemento con un convertito. Atteso: la conferma dice «… e 1 file convertito»; dopo, + originale e convertito non ci sono più, le copie esterne restano. +6. Rimetti Foto su «Originale». Atteso: la coda si svuota, i file convertiti restano dove sono. + +### F8. Che cosa riferire - Per ogni passo «come atteso» oppure il testo esatto di ciò che hai visto, con l'ora. - Il conteggio dei file della cartella delle copie prima e dopo (F2, F4): solo file in più, mai meno o cambiati. +- In F5 e F7 gli SHA-256 degli originali prima e dopo (devono coincidere) e, per F5 passo 3, se data, posizione e + rotazione sono rimaste; in F6 se l'anteprima era davvero l'immagine che il lettore mostrava. - Le righe del registro dell'avvio che parlano di copie esterne (F1, F2) e quelle della pausa (F2 passo 8, F4). - In F2 passo 1 l'esito di `stat -c '%u:%g' /mnt/user/Febe-copie /mnt/user/Febe-copie/disco` dal terminale di Unraid. - Se un file è finito nel posto sbagliato (per esempio nella cartella vuota del server con il disco smontato): il diff --git a/docs/schermate/15-impostazioni-esportazione-docker.png b/docs/schermate/15-impostazioni-esportazione-docker.png index 91cf9c4..382a241 100644 Binary files a/docs/schermate/15-impostazioni-esportazione-docker.png and b/docs/schermate/15-impostazioni-esportazione-docker.png differ diff --git a/docs/schermate/15-impostazioni-esportazione.png b/docs/schermate/15-impostazioni-esportazione.png index 1b8cb3c..b2917af 100644 Binary files a/docs/schermate/15-impostazioni-esportazione.png and b/docs/schermate/15-impostazioni-esportazione.png differ diff --git a/docs/schermate/16-destinazione.png b/docs/schermate/16-destinazione.png index d6e8965..d104a34 100644 Binary files a/docs/schermate/16-destinazione.png and b/docs/schermate/16-destinazione.png differ diff --git a/docs/schermate/17-account-copie-esterne.png b/docs/schermate/17-account-copie-esterne.png index 13b57fe..09e814b 100644 Binary files a/docs/schermate/17-account-copie-esterne.png and b/docs/schermate/17-account-copie-esterne.png differ diff --git a/docs/schermate/18-copia-in.png b/docs/schermate/18-copia-in.png index f4b9616..9d96344 100644 Binary files a/docs/schermate/18-copia-in.png and b/docs/schermate/18-copia-in.png differ diff --git a/docs/schermate/19-libreria-copie.png b/docs/schermate/19-libreria-copie.png index 05c5fc9..d9fa64f 100644 Binary files a/docs/schermate/19-libreria-copie.png and b/docs/schermate/19-libreria-copie.png differ diff --git a/docs/schermate/20-visualizzatore-copie.png b/docs/schermate/20-visualizzatore-copie.png index ece700b..e46af99 100644 Binary files a/docs/schermate/20-visualizzatore-copie.png and b/docs/schermate/20-visualizzatore-copie.png differ diff --git a/docs/schermate/21-dashboard-esportazione.png b/docs/schermate/21-dashboard-esportazione.png index e4f2190..b340305 100644 Binary files a/docs/schermate/21-dashboard-esportazione.png and b/docs/schermate/21-dashboard-esportazione.png differ diff --git a/docs/schermate/22-fotogrammi-striscia.png b/docs/schermate/22-fotogrammi-striscia.png new file mode 100644 index 0000000..317c828 Binary files /dev/null and b/docs/schermate/22-fotogrammi-striscia.png differ diff --git a/docs/schermate/22-fotogrammi-visualizzatore.png b/docs/schermate/22-fotogrammi-visualizzatore.png new file mode 100644 index 0000000..059c725 Binary files /dev/null and b/docs/schermate/22-fotogrammi-visualizzatore.png differ diff --git a/docs/schermate/23-fotogrammi-selezione.png b/docs/schermate/23-fotogrammi-selezione.png new file mode 100644 index 0000000..85f6920 Binary files /dev/null and b/docs/schermate/23-fotogrammi-selezione.png differ diff --git a/docs/schermate/24-visualizzatore-fotogramma.png b/docs/schermate/24-visualizzatore-fotogramma.png new file mode 100644 index 0000000..69c0af4 Binary files /dev/null and b/docs/schermate/24-visualizzatore-fotogramma.png differ diff --git a/docs/schermate/25-copia-in-formati.png b/docs/schermate/25-copia-in-formati.png new file mode 100644 index 0000000..0340bb3 Binary files /dev/null and b/docs/schermate/25-copia-in-formati.png differ diff --git a/docs/schermate/26-conversione-libreria.png b/docs/schermate/26-conversione-libreria.png new file mode 100644 index 0000000..542c244 Binary files /dev/null and b/docs/schermate/26-conversione-libreria.png differ diff --git a/docs/schermate/differenze.md b/docs/schermate/differenze.md index 7b5bb79..a5931cd 100644 --- a/docs/schermate/differenze.md +++ b/docs/schermate/differenze.md @@ -41,14 +41,20 @@ solo per l'interfaccia di Febe (§10.7). | `doppioni-download.png` | `/doppioni` | confronto di `miniature/09-importa-revisione.png` (§9.5) | | `primo-avvio.png` | `/libreria?scena=scollegato`, libreria vuota disegnata dal passo `benvenuto.js` | (nessuno: §10.3) | | `errore-configurazione.png` | `/libreria?scena=errore` | (nessuno) | -| `15-impostazioni-esportazione.png` | `/impostazioni/esportazione` (presa il 27/11 da Windows, come le righe seguenti) | composta da `docs/mockup/08-impostazioni-generali.png` e `miniature/07-limiti-e-comportamento.png` | +| `15-impostazioni-esportazione.png` | `/impostazioni/esportazione`, 1440 × 1470 (presa il 27/11 da Windows, come le righe seguenti fino alla 21; tutte rifatte il 28/11 con i formati della tappa E3) | composta da `docs/mockup/08-impostazioni-generali.png` e `miniature/07-limiti-e-comportamento.png` | | `15-impostazioni-esportazione-docker.png` | `/impostazioni/esportazione?veste=docker`, con la nota su `/esporta` | come sopra | | `16-destinazione.png` | `/impostazioni/esportazione`, «Modifica…» della cartella generale, «Uno schema suo» con il primo schema cambiato (passo `destinazione.js`), 1440 × 1000 | composta dal mockup 08 («Nomi dei file», «Risultato») e dai dialoghi di `miniature/13-foglio-di-stile.png` | | `17-account-copie-esterne.png` | `/account/3/impostazioni` (@studio.lumen.demo, cartella sua), scorsa fino a «Cartella» (passo `account-copie.js`), 1440 × 1000 | composta da `miniature/05-account-impostazioni.png` | | `18-copia-in.png` | `/libreria`, menu dell'icona CSV → «Copia i file in…» su tutta la libreria (passo `copia-in.js`) | composta dai dialoghi del 13 e da `miniature/09-importa-revisione.png` | | `19-libreria-copie.png` | `/libreria?copie=copiati`, menu dell'icona CSV aperto (passo `menu-csv.js`) | composta da `docs/mockup/01-libreria.png` | | `20-visualizzatore-copie.png` | `/libreria?copie=tolti`, la prima foto con «Copia di nuovo» (passo `visualizzatore-copie.js`) | composta da `miniature/02-visualizzatore.png` | -| `21-dashboard-esportazione.png` | `/dashboard/esportazione` | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) | +| `21-dashboard-esportazione.png` | `/dashboard/esportazione`, con il riquadro «Conversione della libreria» | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) | +| `22-fotogrammi-visualizzatore.png` | `/libreria`, il video di @marta.demo con un fotogramma copiato, il lettore a 1,25 s, «Fotogramma»: «Questo istante» con l'anteprima (passo `fotogrammi-visualizzatore.js`), 1440 × 1000 (presa il 28/11 da Windows, come le righe seguenti) | composta dai dialoghi di `miniature/13-foglio-di-stile.png` sopra `miniature/02-visualizzatore.png` | +| `22-fotogrammi-striscia.png` | come sopra, «N in tutto» 8, JPG, «Nella cartella delle copie» (passo `fotogrammi-striscia.js`), 1440 × 1000 | come sopra, con la riga delle cartelle di `miniature/09-importa-revisione.png` | +| `23-fotogrammi-selezione.png` | `/libreria?account=2` (@marta.demo), «Seleziona», quattro video e quattro foto, «Fotogrammi…» (passo `fotogrammi-selezione.js`), 1440 × 1000 | composta dai dialoghi del 13 sopra `docs/mockup/01-libreria.png` | +| `24-visualizzatore-fotogramma.png` | `/libreria`, lo stesso video, righe «Copia» con «· intero» e «· fotogramma a 0:01,125 · PNG» (passo `visualizzatore-fotogramma.js`) | composta da `miniature/02-visualizzatore.png` | +| `25-copia-in-formati.png` | come la 18, con «Cambia» aperto e PNG per le foto (passo `copia-in-formati.js`), 1440 × 1000 | composta dai dialoghi del 13 e dai controlli segmentati di `miniature/07-limiti-e-comportamento.png` | +| `26-conversione-libreria.png` | `/impostazioni/esportazione`, «Conversione della libreria» → PNG: la domanda «Convertire anche i N file già in libreria?» (passo `conversione-libreria.js`; nessuna risposta, l'impostazione resta «Originale») | composta da `docs/mockup/08-impostazioni-generali.png` e dai dialoghi del 13 | ## Differenze che restano @@ -228,14 +234,15 @@ da cui nascono. Le prove dell'interfaccia (`ExportInterfaceTests`: impostazioni destinazione, blocco dell'account, «Copia in…» dalla selezione, filtro «Copie» e segno sulle tessere, righe del visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui non sono state eseguite. Differenze: -- **Formati e conversione non ci sono (E3).** La tappa E2 copia solo gli originali: la finestra della destinazione non - ha la parte dei formati, Impostazioni → Esportazione non ha «Formati predefiniti delle copie» né «Conversione della - libreria», e il riepilogo di «Copia in…» non ha mai «3 HEIC copiati come sono» né «con perdita». I controlli mancano, - non sono spenti: un controllo grigio senza niente dietro non dice che cosa succede (§10.4). +- **Formati e conversione non c'erano (E3).** Nelle schermate del 27/11 la finestra della destinazione non aveva la + parte dei formati, Impostazioni → Esportazione non aveva «Formati delle copie» né «Conversione della libreria», e + «Copia in…» non aveva la riga del formato: sono arrivati con la tappa E3, e le schermate 15–21 sono state rifatte il + 28/11 con loro (qui sotto, «Formati e fotogrammi»). - **«Automatica» non c'è (E5).** La scelta si conserva ma non si mostra, con la domanda «Solo i nuovi»: senza il giro orario della tappa E5 un interruttore acceso non farebbe nulla. -- **«Fotogrammi…» e «Fotogramma» non ci sono (E3)**: né nella barra della selezione della Libreria e della scheda - account, né nel visualizzatore. Neppure la finestra «Fotogrammi…». +- **«Fotogrammi…» e «Fotogramma» non c'erano (E3)** nelle schermate del 27/11: né nella barra della selezione della + Libreria e della scheda account, né nel visualizzatore. Sono arrivati con la tappa E3 (qui sotto; nella 20 rifatta + il 28/11 la foto non ha «Fotogramma», che è solo dei video). - **«È un video fermo?» non c'è (E4)** nel visualizzatore. - **Segno sulla tessera** (voluto, §4.10): l'ultimo dei segni in alto a destra, un riquadro scuro con l'icona `copy` quando i file dovuti dell'elemento sono tutti copiati, con «2/3» quando lo sono solo in parte. Nel mockup 01 non c'è. @@ -287,6 +294,81 @@ visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui visualizzatore, la finestra della destinazione in Docker, il «Resoconto», una copia in corso con Interrompi, una cartella in pausa con «Riprova», il tema scuro, la finestra stretta e il telefono. +### Formati e fotogrammi (tappa E3, issue #58, dal 28 novembre 2026) + +Anche queste parti non hanno un mockup (§10.3 «Schermate dell'esportazione»): sono composte dai mockup esistenti, come +dice la tabella. Il 28/11 le schermate `15-…` – `21-…` sono state rifatte e le sei nuove `22-…` – `26-…` prese con il +programma delle schermate da Windows (`tools/Febe.Schermate`, browser senza finestra, scala 1,25), una alla volta con +`una`, su una dimostrazione appena avviata (`--demo --porta 8490`), nell'ordine della tabella; nessun passo converte, +scarica o copia, e la domanda della conversione resta senza risposta. Misure: 1440 × 900; 1440 × 1000 per le finestre +alte (fotogrammi, «Copia in…» con «Cambia» aperto); 1440 × 1470 per Impostazioni → Esportazione intera, che ora arriva +fino a «Conversione della libreria». Poi sono state messe accanto ai mockup da cui nascono; le stesse finestre sono state +guardate anche in tema scuro e a 390 × 844 (senza schermata nella cartella). Le prove dell'interfaccia girano solo nella +CI. Differenze: + +- **Impostazioni → Esportazione** (mockup 08 e 07): due blocchi nuovi, «Formati delle copie» dopo «Cartella generale» e + «Conversione della libreria» in fondo, con i controlli segmentati del mockup 07 (Foto: Originale · JPG · PNG · WEBP + senza perdita; Video: Originale · MP4) e la nota sotto il controllo («con perdita: qualità 92», «solo rimuxaggio, mai + ricodifica»). Il blocco della conversione ha la riga di stato («In coda 12 · convertiti 340 · …») con «Interrompi» o + «Riprendi» e «Riprova i non riusciti», e l'avviso del motivo dell'attesa; la domanda «Convertire anche i N file già + in libreria?» è un dialogo del mockup 13 con «Solo i nuovi» come pulsante principale. +- **Finestra della destinazione**: una parte «Formati» con gli stessi controlli e la prima voce «Come le impostazioni + generali». +- **«Copia in…»**: una riga «Formato: come la destinazione · Cambia» sopra il riepilogo; «Cambia» apre i due controlli + per quella copia sola. Il riepilogo aggiunge «circa 3 HEIC copiati come sono» e «con perdita». +- **Finestra «Fotogrammi…»** (dialoghi del mockup 13, elenco delle scelte del passo 3 del mockup 09): dal visualizzatore + anteprima grande del fotogramma (al più 480 pixel), cursore e campo dell'istante, la riga «Fotogramma a 0:01,125», + una striscia con le prime sei anteprime e «e altri N»; poi formato (PNG, JPG con la nota «con perdita», WEBP senza + perdita), «Il fotogramma non ha l'audio.» e l'uscita, «Scarica» o «Nella cartella delle copie» (spenta senza una + cartella). **Dalla selezione** la finestra ha solo il campo dell'istante, senza anteprime né cursore (non c'è un + video solo), e il riepilogo dice «4 fotogrammi da 4 video · le 6 foto si saltano» (23). +- **Visualizzatore** (mockup 02): «Fotogramma» fra le azioni dei video (ferma il video e apre la finestra al suo + istante), o la riga «Fotogramma non disponibile per questo video»; le righe delle copie aggiungono la forma («· intero», + «· PNG», «· fotogramma a 0:01,125 · PNG») e le note su una seconda riga; i file convertiti della libreria hanno una + riga loro («Convertito in PNG · 2,1 MB») con «Mostra nella cartella» su Windows o «Scarica». +- **Segno «Solo fotogrammi»** sulla tessera (mockup 01): un piccolo riquadro disegnato in CSS, senza un'icona nuova, + nello stesso posto del segno delle copie. Nel mockup non c'è (come il segno delle copie, voluto). +- **Dashboard → Esportazione**: un riquadro «Conversione della libreria» fra «Da riprendere» e «Ultimi lavori», solo + quando la conversione è accesa o ha righe; nel resoconto la colonna «Come sono» e la parte «Note». Aggiunte senza + mockup. +- **Conferma dell'eliminazione**: aggiunge i file convertiti («… elimino gli elementi interi, 9 file e 2 file + convertiti»). +- **Dialoghi sopra il visualizzatore**: un dialogo aperto dal visualizzatore (la finestra «Fotogrammi», «Copia in…») + ora sta sopra di lui; prima restava sotto. +- **Contenuti dimostrativi.** Ogni video della dimostrazione è lo stesso video di 2 secondi, 240 × 432: le informazioni + del file nel visualizzatore (720 × 1280, 0:11 nella 22 e nella 24) non coincidono con quelle della finestra dei + fotogrammi («Video di 0:02, 240 × 432 pixel»), e l'anteprima è stretta in mezzo a un riquadro nero largo. «Nella + cartella delle copie» dei fotogrammi e una «Copia in…» di un video finiscono in errore nella dimostrazione («non + corrisponde»), perché i video dimostrativi hanno lo SHA-256 della loro copertina; le anteprime e «Scarica» funzionano. + Le foto della dimostrazione sono tutte JPEG: nella 25 il riepilogo di «Copia in…» con PNG resta uguale a quello della + 18 (994 file; i 28.865 già copiati restano «già copiati» in qualunque formato, decisione D3) e non può mostrare né + «con perdita» né «copiati come sono» («con perdita» si vede nella 22-striscia: «8 fotogrammi da 1 video · con + perdita»). Il segno + «Solo fotogrammi» non si vede in nessuna tessera: il video del fotogramma dimostrativo ha anche la copia intera (per + SHA-256, come sopra), quindi la sua tessera ha il segno delle copie. I numeri delle schermate 15–21 sono quelli della + dimostrazione del 28/11 e non coincidono con quelli citati qui sopra per la tappa E2 (per esempio «335 su 657 non ancora + copiati» invece di «371 su 648»). +- **Confronto con le immagini** (28/11): la finestra «Fotogrammi» ha intestazione, piede con «Annulla» e il pulsante + principale, titoli delle parti e righe divisorie dei dialoghi del 13; le scelte «Scarica» / «Nella cartella delle + copie» sono le scelte a pallino con la riga d'aiuto del passo 3 del mockup 09; la riga della cartella nella 22-striscia + e nella 25 è quella dell'elenco delle cartelle dell'importazione. I controlli dei formati sono i segmentati del mockup + 07, con l'etichetta a sinistra come le righe del mockup 08. Il visualizzatore (24) è quello del mockup 02 con le righe + «Copia» e cinque azioni in fondo invece di due («Copia in…» e «Fotogramma» si aggiungono). Nessuna differenza da + segnalare oltre a quelle elencate qui sopra e ai ritocchi seguenti. +- **Sistemato il 28/11** dopo il confronto: + - nella finestra «Fotogrammi» la riga «Fotogramma a 0:01,25» accanto al campo dell'istante (e «Lo stesso istante in ogni + video…» dalla selezione) stava 6 px più in alto del campo, perché la regola dei paragrafi dei dialoghi le dava 12 px + sotto: ora è centrata sul campo; + - sotto «Formato» la nota «Il fotogramma non ha l'audio.» (e «con perdita: qualità 92») aveva 12 px in più sotto, e la + parte «Formato» finiva più larga delle altre: ora le parti hanno lo stesso respiro; + - in «Copia in…» con «Cambia» aperto il controllo delle foto (cinque voci) non stava accanto all'etichetta «Foto» e + andava a capo, mentre quello dei video restava accanto a «Video»: i due controlli partivano da punti diversi. Ora in + «Copia in…» le etichette stanno sopra i controlli, e i due controlli sono allineati. +- **Senza schermata:** la veste Docker («Scarica» del convertito), la linguetta della scheda account con «Fotogrammi…», + «Uno ogni k secondi», la riga «Convertito in PNG» del visualizzatore, la conferma dell'eliminazione con i file + convertiti, il resoconto con «Come sono» e «Note», il tema scuro, la finestra stretta e il telefono (guardati, senza + difetti da correggere), uno zip di più di 20 fotogrammi durante una sessione. + ### Carattere e icone (dal 18 novembre 2026) Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre diff --git a/docs/stato.md b/docs/stato.md index 875887f..3f8c008 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -1,7 +1,7 @@ # Stato Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché. -Aggiornato il 27 novembre 2026 (tappa E2 Copie esterne; prima, E1 Schema unita in `main` con #69 e la catena della +Aggiornato il 28 novembre 2026 (tappa E3 Formati e fotogrammi; prima, E2 Copie esterne e E1 Schema unita in `main` con #69 e la catena della 0.3.0, #60 … #66), versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto @@ -9,6 +9,62 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte. ## In breve +**28 novembre 2026: tappa E3 «Formati e fotogrammi» dell'esportazione** (#58, ramo +`funzione/esportazione-formati`). Le undici domande nuove della tappa sono in §16 (righe 28–38) con la proposta +adottata, da confermare con Alberto. + +- **Foto** (`src/Febe.Core/Codecs/Images/`, `ImageConverter`): copie e libreria in JPG (qualità 92, 4:4:4, trasparenza + su bianco, «con perdita»), PNG o WEBP senza perdita; stesso formato = copia byte per byte (anche un WEBP con perdita + verso «WEBP senza perdita»). EXIF, ICC e XMP nei loro blocchi; ciò che non si tiene diventa una nota (elenco di + codici). Si copiano come sono, con una nota: HEIC, AVIF, raw, animate, illeggibili, CMYK o più di 8 bit verso + PNG/WEBP, oltre 40/100 MP o 16.384 px. Stessi byte a ogni conversione sullo stesso runtime (logaritmo a virgola fissa + nel WEBP). +- **Video**: rimuxaggio in MP4 (MOV, M4V, 3GP, Matroska/WebM con H.264 o HEVC e AAC/MP3) con campioni, tempi, edit + list, rotazione e lingua; ciò che non si rimuxa si copia intero con il motivo. **Fotogrammi esatti** (`VideoFrameReader`): + un istante, «uno ogni k secondi» da 0:00, «N in tutto» al centro di N parti; PNG di base; nomi `_t0m12s340` e `_f001`; + verso le destinazioni (segno «Solo fotogrammi», «Copiato in parte»), «Scarica» di un'immagine o di uno zip (fino a + 20 sempre, 21–500 fuori dalle sessioni del motore, oltre solo nella cartella delle copie). +- **Copie**: formato scelto da «Copia in…», poi dalla destinazione, poi dalle impostazioni; si converte prima dei + controlli di spazio e FAT32; adozione per lunghezza e SHA-256 della conversione; «già copiato» in qualunque forma + tranne il fotogramma; «Copia di nuovo» con l'identità esatta. Nessuna migrazione: bastano le tabelle di E1. +- **Conversione della libreria** (`LibraryConversionWorker`): un file convertito accanto all'originale, mai al suo + posto, con la riga di `media_conversion` sempre vera (anche dopo un arresto, un'eliminazione, un doppione, una + ricostruzione, un'importazione); permesso di sottofondo di `LongWorkGate` che cede al lavoro in primo piano; una + conversione alla volta nel processo; pausa con poco spazio o durante una sessione del motore; «Solo i nuovi» o + «Anche i N già in libreria», per tipo; mai nella dimostrazione. Nuove chiavi + `esportazione.libreria-formato-foto-dal` e `-video-dal` per sapere che cosa è «nuovo». +- **Interfaccia**: menu dei formati con «con perdita» in Impostazioni, destinazioni e «Copia in…» («Cambia»); dialogo + «Fotogrammi…» dal visualizzatore (all'istante del lettore, con anteprima) e dalla selezione; righe di copia e di + conversione nel visualizzatore; conteggio dei convertiti nella conferma di eliminazione. Nessun controllo di E4. +- **Revisione a più lenti**, due giri prima dell'unione: 16 rilievi confermati e corretti (`958cb71`), poi 4 sulle + correzioni stesse (`2efb408`). I più seri: un JPEG progressivo fra circa 57 e 100 MP segnato «illeggibile» per sempre + invece che «troppo grande»; «N in tutto» con N oltre la durata in ms perdeva istanti e spostava i nomi `_fNNN`; i video + di durata ignota sfuggivano ai limiti di 1.000 e 20.000 fotogrammi; il rimuxaggio mostrava la coda nascosta di un + video tagliato in fondo; «Riprova» riconvertiva in un formato spento; «Anche i N» di un tipo metteva in coda anche + l'altro; uno zip lento si interrompeva dopo 60 s; due cambi rapidi delle impostazioni ne perdevano uno. +- Documenti: SPECIFICA §4.10, §16 righe 28–38; righe del 28/11 in `decisioni.md`; guida `Esportazione.md`; + schermate 15–21 rifatte e sei nuove (22–26) con il confronto in `docs/schermate/differenze.md`. +- Controlli, su Windows: `dotnet build -warnaserror` 0 avvisi, 0 errori; `dotnet test tests/Febe.Tests` 3187 + superate, 110 ignorate (Chromium e Xvfb: solo nella CI), 0 non superate; `dotnet test tests/Febe.Tests.Windows` 24 + superate. Nella CI l'esecuzione 502 (prima delle correzioni) si è fermata 42 minuti con tutto il processo delle prove + (anche le prove H.265 da 1 s), e due prove d'interfaccia nuove sono scadute in quella pausa; la stessa revisione + nell'immagine della CI in locale è verde in 10 m 33 s e nel codice di E3 non c'è nulla che blocchi i thread. Se si + ripete, il prossimo passo è limitare i Chromium paralleli nelle prove (`UiBrowser`) e aggiungere `--blame-hang`. +- **Non verificato**: + - le sette prove d'interfaccia nuove (`ExportInterfaceTests.Formats.cs`) girano solo nella CI di Linux; nessuna + clicca «Scarica» o avvia un lavoro di fotogrammi o di video nella dimostrazione; + - file veri grandi: foto da 40–100 MP, video oltre 4 GiB (`co64`), HEVC di telefoni veri; le prove usano media + costruiti dalle prove; + - senza prova loro: più edit di seguito, AAC di Matroska vecchio stile, Opus, tracce Matroska codificate, un flusso + che comincia solo con CRA, una pausa in mezzo a un gruppo di fotogrammi, l'eliminazione di un account con file + convertiti su un disco vero; + - stessi byte fra versioni diverse di .NET (lo zlib del PNG è quello del runtime: scritto in `decisioni.md`); + - nessuna schermata di: veste Docker, «Uno ogni k secondi», riga «Convertito in PNG» del visualizzatore, conferma + di eliminazione, Resoconto; tema scuro e 390 px visti solo su prove scartate; + - nella dimostrazione «con perdita» non compare in «Copia in…» (le foto di esempio sono tutte JPEG) e nessuna + tessera ha il segno «Solo fotogrammi». +- **Prossima tappa**: E4 «Video fermi» oppure E5 «Esportazione automatica», a scelta di Alberto. + **27 novembre 2026: tappa E2 «Copie esterne» dell'esportazione** (#58). Decisione di Alberto di oggi: «Esporta questo account» senza una scelta registrata (nessuna riga in `export_account`) è **acceso**. Le altre sei domande della tappa sono in §16 (righe 22–27) con la proposta adottata, da confermare. diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index b7ac062..12951d9 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -14,6 +14,7 @@ using Febe.Core.Engine; using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Library; +using Febe.Core.Library.Conversion; using Febe.Core.Security; using Febe.Core.Storage; using Febe.Data; @@ -194,9 +195,12 @@ public sealed class FebeApp : IAsyncDisposable DataFolder = data.Root, Gate = longWork, }); + var idleConversion = new LibraryConversionWorker(new LibraryConversionEnvironment { Storage = Database, Layout = () => library.Layout, Clock = Clock, Gate = longWork }); await StartWebAsync(hooks, services => { services.AddSingleton(longWork); + services.AddSingleton(idleConversion); + services.AddSingleton(new LibraryConversionQueue(Database, Clock)); services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false)); services.AddSingleton(Database); services.AddSingleton(library); @@ -336,12 +340,28 @@ public sealed class FebeApp : IAsyncDisposable _telegram = new TelegramClient(hooks.TelegramHandler); var telegramChannel = new TelegramAlertChannel(_telegram); + // The conversion for the library (tappa E3, spec §4.10): one worker, started below in the background; it yields + // to import, copies and rebuild through the gate and never runs during an engine session. Never in the demo. + var sessionState = new RuntimeSessionState(services.Runtime); + var conversion = new LibraryConversionWorker(new LibraryConversionEnvironment + { + Storage = Database, + Layout = () => library.Layout, + Clock = Clock, + Gate = longWork, + Session = sessionState, + FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(), + Log = message => Log.Write(LogLevel.Warning, "conversione", message), + }); + await StartWebAsync(hooks, s => { s.AddSingleton(longWork); + s.AddSingleton(conversion); + s.AddSingleton(new LibraryConversionQueue(Database, Clock)); s.AddSingleton(exportRoot); s.AddSingleton(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts)); - s.AddSingleton(new RuntimeSessionState(services.Runtime)); + s.AddSingleton(sessionState); s.AddSingleton(Database); s.AddSingleton(library); s.AddSingleton(Clock); @@ -398,6 +418,7 @@ public sealed class FebeApp : IAsyncDisposable InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime)); InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime)); InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime)); + InBackground(() => conversion.RunAsync(lifetime)); } /// Runs in the background; the stop waits for it. diff --git a/src/Febe.Core/Abstractions/LongWorkGate.cs b/src/Febe.Core/Abstractions/LongWorkGate.cs index 92dd75a..7609544 100644 --- a/src/Febe.Core/Abstractions/LongWorkGate.cs +++ b/src/Febe.Core/Abstractions/LongWorkGate.cs @@ -13,19 +13,38 @@ public enum LongWorkKind /// «Ricostruisci il database dalla libreria» (spec §8.5). Rebuild, + + /// + /// The conversion for the library (tappa E3, spec §4.10): held only as a , + /// which any of the others pre-empts. + /// + LibraryConversion, + + /// A zip of 21 to 500 frames being prepared for «Scarica» (tappa E3, D14). + FrameDownload, } /// -/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole -/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing -/// it twice releases nothing more. +/// Lets only one of import, export, rebuild and frame download run at a time, in both directions. One instance is +/// shared by the whole process (the composition registers it once). A lease is taken when a job starts and disposed when +/// it ends; disposing it twice releases nothing more. +/// +/// The conversion for the library takes a instead (tappa E3, WP2.1): it runs only while +/// no foreground lease is held, and a foreground pre-empts it. Outside a commit the conversion +/// only reads an original and writes its own temporary file, so it simply stops; a commit (one rename and one +/// transaction) is waited for, at most . +/// /// public sealed class LongWorkGate { private readonly Lock _lock = new(); private Lease? _holder; + private BackgroundLease? _background; - /// Who holds the gate, or null when it is free. + /// How long a foreground waits for a commit of the background work to end. + public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10); + + /// Who holds the gate in the foreground, or null when it is free. The background lease does not count. public LongWorkKind? Busy { get @@ -37,12 +56,34 @@ public sealed class LongWorkGate } } + /// True while the background lease (the conversion for the library) is held and not pre-empted. + public bool BackgroundRunning + { + get + { + lock (_lock) + { + return _background is not null; + } + } + } + /// /// Takes the gate for . False, with set, when another job (of any - /// kind, the same one included) holds it. + /// kind, the same one included) holds it in the foreground. A background lease is pre-empted: its token is + /// cancelled and, if it is committing a file, the commit is waited for (at most ; past it, + /// false with ). /// public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith) { + if (kind == LongWorkKind.LibraryConversion) + { + throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind)); + } + + Lease taken; + BackgroundLease? preempted; + bool committing; lock (_lock) { if (_holder is { } holder) @@ -52,10 +93,47 @@ public sealed class LongWorkGate return false; } - var taken = new Lease(this, kind); + taken = new Lease(this, kind); _holder = taken; - lease = taken; - busyWith = null; + preempted = _background; + _background = null; + committing = preempted?.MarkPreempted() ?? false; + } + + if (preempted is not null) + { + // Outside the lock: the token's callbacks run synchronously and may take the gate's lock. + preempted.CancelPreempted(); + if (committing && !preempted.WaitForCommit(CommitWait)) + { + taken.Dispose(); + lease = null; + busyWith = LongWorkKind.LibraryConversion; + return false; + } + } + + lease = taken; + busyWith = null; + return true; + } + + /// + /// Takes the gate in the background for the conversion for the library. False while any foreground lease, or + /// another background lease, is held. + /// + public bool TryEnterBackground([NotNullWhen(true)] out BackgroundLease? lease) + { + lock (_lock) + { + if (_holder is not null || _background is not null) + { + lease = null; + return false; + } + + lease = new BackgroundLease(this); + _background = lease; return true; } } @@ -68,14 +146,20 @@ public sealed class LongWorkGate (LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.", (_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.", (_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.", - _ => "La ricostruzione del database è in corso: aspetta che finisca.", + (_, LongWorkKind.LibraryConversion) => "La conversione della libreria sta salvando un file: riprova fra un attimo.", + (_, LongWorkKind.FrameDownload) => $"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi {Verb(wanted)}.", + (_, LongWorkKind.Rebuild) => "La ricostruzione del database è in corso: aspetta che finisca.", + _ => "Un altro lavoro lungo è in corso: aspetta che finisca.", }; private static string Verb(LongWorkKind kind) => kind switch { LongWorkKind.Import => "importa", LongWorkKind.Export => "copia", - _ => "ricostruisci", + LongWorkKind.Rebuild => "ricostruisci", + LongWorkKind.FrameDownload => "scarica i fotogrammi", + LongWorkKind.LibraryConversion => "converti", + _ => "riprova", }; private void Release(Lease lease) @@ -89,6 +173,17 @@ public sealed class LongWorkGate } } + private void Release(BackgroundLease lease) + { + lock (_lock) + { + if (ReferenceEquals(_background, lease)) + { + _background = null; + } + } + } + private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable { private int _disposed; @@ -103,4 +198,112 @@ public sealed class LongWorkGate } } } + + /// + /// The background lease of the conversion for the library. is cancelled when a foreground + /// job wants the gate; a commit () is waited for by that job, and none begins once + /// pre-empted or disposed. + /// + public sealed class BackgroundLease : IDisposable + { + private readonly LongWorkGate _gate; + + // Neither is disposed: a foreground TryEnter may cancel or wait on them after the lease ended, and without a + // timer or a wait handle asked for they hold nothing but memory. + private readonly CancellationTokenSource _preempted = new(); + private readonly ManualResetEventSlim _noCommit = new(initialState: true); + private bool _isPreempted; + private bool _committing; + private int _disposed; + + internal BackgroundLease(LongWorkGate gate) + { + _gate = gate; + Preempted = _preempted.Token; + } + + /// Cancelled when a foreground job takes the gate. + public CancellationToken Preempted { get; } + + /// True once a foreground job asked for the gate (or the lease ended). + public bool IsPreempted + { + get + { + lock (_gate._lock) + { + return _isPreempted; + } + } + } + + /// + /// Begins a commit (a rename and its record) that a foreground job waits for. False once pre-empted or disposed, + /// or while another commit of this lease runs: then nothing may be renamed or recorded. + /// + public bool TryBeginCommit([NotNullWhen(true)] out IDisposable? commit) + { + lock (_gate._lock) + { + if (_isPreempted || _disposed != 0 || _committing) + { + commit = null; + return false; + } + + _committing = true; + _noCommit.Reset(); + commit = new Commit(this); + return true; + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + { + return; + } + + EndCommit(); + _gate.Release(this); + lock (_gate._lock) + { + _isPreempted = true; + } + } + + /// Under the gate's lock: marks the lease pre-empted and tells whether a commit is running. + internal bool MarkPreempted() + { + _isPreempted = true; + return _committing; + } + + internal void CancelPreempted() => _preempted.Cancel(); + + internal bool WaitForCommit(TimeSpan timeout) => _noCommit.Wait(timeout); + + private void EndCommit() + { + lock (_gate._lock) + { + _committing = false; + _noCommit.Set(); + } + } + + private sealed class Commit(BackgroundLease lease) : IDisposable + { + private int _disposed; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + lease.EndCommit(); + } + } + } + } } diff --git a/src/Febe.Core/Codecs/Containers/ContainerReader.cs b/src/Febe.Core/Codecs/Containers/ContainerReader.cs index 6aa585d..d9607f7 100644 --- a/src/Febe.Core/Codecs/Containers/ContainerReader.cs +++ b/src/Febe.Core/Codecs/Containers/ContainerReader.cs @@ -6,6 +6,12 @@ namespace Febe.Core.Codecs.Containers; /// public static class ContainerReader { + /// + /// A «now» far in the future, for readers that must not depend on the clock (frames, remux): every plausible date + /// in the file is accepted. + /// + internal static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero); + /// The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below. public const int MaxSampleSize = 64 * 1024 * 1024; diff --git a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs index 822574a..bb75dcd 100644 --- a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs +++ b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs @@ -39,6 +39,7 @@ public static class IsoBmffReader long position = 0; Span header = stackalloc byte[16]; Movie? movie = null; + string? brand = null; var pending = new List<(long Start, byte[] Body)>(); for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) { @@ -75,6 +76,12 @@ public static class IsoBmffReader } var type = header.Slice(4, 4); + if (type.SequenceEqual("ftyp"u8) && brand is null && size - headerSize >= 4) + { + stream.ReadExactly(header[..4]); // the size field is read already: its bytes can hold the brand + brand = System.Text.Encoding.Latin1.GetString(header[..4]); + } + if (type.SequenceEqual("moov"u8) && movie is null) { movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length); @@ -112,7 +119,7 @@ public static class IsoBmffReader throw new ContainerException("Manca il box moov."); } - return movie.Build(); + return movie.Build(brand); } private static byte[] ReadBody(Stream stream, long offset, long count) @@ -141,7 +148,11 @@ public static class IsoBmffReader case "mvhd": movie.ParseMvhd(body, now); break; + case "udta" or "meta": + movie.HasUserData = true; + break; case "trak": + movie.TrackCount++; try { movie.ParseTrak(moov, start, count); @@ -269,6 +280,12 @@ public static class IsoBmffReader internal byte[]? Hvcc; internal byte[]? Asc; internal long EditOffset; + internal bool HasEdits; + internal long EmptyEditMovie; + internal long EditSegmentMovie; + internal int EditCount; + internal string? Language; + internal int ObjectType; internal List Samples = []; internal long FragmentTime = -1; } @@ -279,6 +296,7 @@ public static class IsoBmffReader internal readonly Dictionary TrackDefaults = []; private readonly List tracks = []; private DateTimeOffset? created; + private DateTimeOffset? modified; private long timescale; private long duration; @@ -288,6 +306,12 @@ public static class IsoBmffReader /// fragment_duration of the mehd box, in movie units; 0 when absent. internal long FragmentDuration; + /// The trak boxes of the movie, of every kind. + internal int TrackCount; + + /// True when the movie has a udta or meta box. + internal bool HasUserData; + /// A fragmented movie whose headers give no duration: only its fragments tell it. internal bool NeedsFragmentsForDuration => Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0); @@ -295,15 +319,18 @@ public static class IsoBmffReader internal void ParseMvhd(ReadOnlySpan body, DateTimeOffset now) { ulong creation; + ulong modification; if (body[0] == 1) { creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]); + modification = BinaryPrimitives.ReadUInt64BigEndian(body[12..]); timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); } else { creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + modification = BinaryPrimitives.ReadUInt32BigEndian(body[8..]); timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); if (duration == uint.MaxValue) @@ -312,14 +339,22 @@ public static class IsoBmffReader } } - if (creation > 0 && creation < 400UL * 366 * 86400) + created = Plausible(creation, now); + modified = Plausible(modification, now); + } + + private static DateTimeOffset? Plausible(ulong seconds, DateTimeOffset now) + { + if (seconds > 0 && seconds < 400UL * 366 * 86400) { - var instant = Epoch1904.AddSeconds(creation); + var instant = Epoch1904.AddSeconds(seconds); if (instant >= Earliest && instant <= now.AddDays(1)) { - created = instant; + return instant; } } + + return null; } internal void ParseTrak(byte[] data, int start, int count) @@ -365,15 +400,34 @@ public static class IsoBmffReader var v1 = body[0] == 1; var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); var offset = 8; + var leading = true; for (var i = 0; i < entries && i < 16; i++) { + var segment = v1 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[offset..]), long.MaxValue / 4) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]); long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]); + var rate = BinaryPrimitives.ReadInt16BigEndian(body[(offset + (v1 ? 16 : 8))..]); offset += v1 ? 20 : 12; - if (mediaTime >= 0) + if (leading && mediaTime < 0) { - track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero - return; + track.EmptyEditMovie += segment; // a delayed start + continue; } + + if (leading) + { + leading = false; + track.HasEdits = true; + track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero + track.EditSegmentMovie = segment; // and how long it is shown (movie units; 0: to the end) + } + + // A rate other than 1 (a slowed or still segment) is not an ordinary edit either. + track.EditCount += rate == 1 ? 1 : 2; + } + + if (entries > 16) + { + track.EditCount += 2; } } @@ -397,6 +451,7 @@ public static class IsoBmffReader track.Duration = d == uint.MaxValue ? 0 : d; } + track.Language = Language(body[0] == 1 ? body[32..] : body[20..]); break; case "hdlr": track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4)); @@ -478,6 +533,39 @@ public static class IsoBmffReader } } + /// + /// The ISO 639-2/T code packed in an mdhd (three letters of five bits each); null for «und», for a + /// QuickTime Macintosh language code (below 0x400) or for a damaged value. + /// + private static string? Language(ReadOnlySpan field) + { + if (field.Length < 2) + { + return null; + } + + var packed = BinaryPrimitives.ReadUInt16BigEndian(field) & 0x7FFF; + if (packed < 0x400) + { + return null; + } + + Span code = stackalloc char[3]; + for (var i = 0; i < 3; i++) + { + var letter = (packed >> (10 - (5 * i))) & 0x1F; + if (letter is < 1 or > 26) + { + return null; + } + + code[i] = (char)('a' + letter - 1); + } + + var text = new string(code); + return text == "und" ? null : text; + } + private static void ParseStsd(byte[] data, int start, int count, Track track) { if (count < 16) @@ -524,16 +612,31 @@ public static class IsoBmffReader { if (t == "esds") { - track.Asc = EsdsConfig(data.AsSpan(s, c)); + (track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(s, c)); + } + else if (t == "wave" && track.ObjectType == 0) + { + // QuickTime keeps the esds of an mp4a entry inside a wave box (QTFF, sound sample description). + foreach (var (wt, ws, wc) in Children(data, s, c)) + { + if (wt == "esds") + { + (track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(ws, wc)); + } + } } } } } } - /// The DecoderSpecificInfo of an esds box (ISO/IEC 14496-1 descriptors). - private static byte[]? EsdsConfig(ReadOnlySpan body) + /// + /// The objectTypeIndication (0 when absent) and the DecoderSpecificInfo of an esds box (ISO/IEC 14496-1 + /// descriptors). + /// + private static (int ObjectType, byte[]? Config) EsdsConfig(ReadOnlySpan body) { + var objectType = 0; var p = 4; // version and flags while (p + 2 <= body.Length) { @@ -555,7 +658,7 @@ public static class IsoBmffReader { if (p + 3 > body.Length) { - return null; + return (objectType, null); } var flags = body[p + 2]; @@ -569,7 +672,7 @@ public static class IsoBmffReader { if (p >= body.Length) { - return null; + return (objectType, null); } p += 1 + body[p]; @@ -583,18 +686,23 @@ public static class IsoBmffReader break; } - case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children + case 0x04: // DecoderConfigDescriptor: objectTypeIndication and the other fixed fields, then the children + if (p < body.Length) + { + objectType = body[p]; + } + p += 13; break; case 0x05: - return p + length <= body.Length ? body.Slice(p, length).ToArray() : null; + return (objectType, p + length <= body.Length ? body.Slice(p, length).ToArray() : null); default: p += length; break; } } - return null; + return (objectType, null); } private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss) @@ -903,7 +1011,7 @@ public static class IsoBmffReader return total; } - internal MediaContainer Build() + internal MediaContainer Build(string? brand) { var video = tracks.Find(t => t.Handler == "vide"); var audio = tracks.Find(t => t.Handler == "soun"); @@ -932,6 +1040,11 @@ public static class IsoBmffReader AvcConfiguration = video.Avcc, HevcConfiguration = video.Hvcc, Samples = video.Samples, + EditMediaTime = video.HasEdits ? video.EditOffset : null, + EmptyEditDuration = EmptyEdit(video), + EditSegmentDuration = EditSegment(video), + EditCount = video.EditCount, + Language = video.Language, }; } @@ -942,6 +1055,8 @@ public static class IsoBmffReader { Codec = audio.Format switch { + // objectTypeIndication 0x69 and 0x6B are MPEG-1/2 audio (MP3) in an mp4a entry (ISO/IEC 14496-1 Table 5). + "mp4a" when audio.ObjectType is 0x69 or 0x6B => AudioCodec.Mp3, "mp4a" => AudioCodec.Aac, ".mp3" => AudioCodec.Mp3, "Opus" => AudioCodec.Opus, @@ -951,10 +1066,16 @@ public static class IsoBmffReader CodecTag = audio.Format, Channels = audio.Channels, SampleRate = audio.SampleRate, - AacConfiguration = audio.Asc, + AacConfiguration = audio.ObjectType is 0x69 or 0x6B ? null : audio.Asc, + AudioObjectType = audio.ObjectType is 0x69 or 0x6B ? null : AudioTrack.ObjectTypeOf(audio.Asc), Timescale = audio.Timescale > 0 ? audio.Timescale : 1, Duration = DurationOf(audio), Samples = audio.Samples, + EditMediaTime = audio.HasEdits ? audio.EditOffset : null, + EmptyEditDuration = EmptyEdit(audio), + EditSegmentDuration = EditSegment(audio), + EditCount = audio.EditCount, + Language = audio.Language, }; } @@ -965,7 +1086,45 @@ public static class IsoBmffReader total = Seconds(v.Seconds(v.Duration)); } - return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a }; + return new MediaContainer + { + Format = ContainerFormat.IsoBmff, + CreatedAt = created, + ModifiedAt = modified, + MajorBrand = brand, + TrackCount = TrackCount, + HasUserData = HasUserData, + Duration = total, + Video = v, + Audio = a, + }; + } + + /// + /// The segment of the first non-empty edit (movie units) in track units, rounded to the nearest; null when the + /// edit has none (0, as fragmented files write it) or the track has no edit list. + /// + private long? EditSegment(Track track) + { + if (!track.HasEdits || track.EditSegmentMovie <= 0 || timescale <= 0 || track.Timescale <= 0) + { + return null; + } + + var value = (((Int128)track.EditSegmentMovie * track.Timescale) + (timescale / 2)) / timescale; + return value > long.MaxValue / 4 ? null : (long)value; + } + + /// The leading empty edits of a track (movie units) in track units, rounded to the nearest. + private long EmptyEdit(Track track) + { + if (track.EmptyEditMovie <= 0 || timescale <= 0 || track.Timescale <= 0) + { + return 0; + } + + var value = (((Int128)track.EmptyEditMovie * track.Timescale) + (timescale / 2)) / timescale; + return value > long.MaxValue / 4 ? 0 : (long)value; } /// A duration in seconds; null when it is beyond what a video can last (a damaged header). diff --git a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs index 2493752..38af403 100644 --- a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs +++ b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs @@ -107,6 +107,9 @@ public static class MatroskaReader case TracksId: ParseTracks(reader, bodyEnd, state); break; + case TagsId: + state.HasTags = true; + break; case ClusterId: if (!samples) { @@ -214,6 +217,13 @@ public static class MatroskaReader case 0x23E383: track.DefaultDuration = (long)reader.Unsigned(tsize); break; + case 0x22B59C: + track.Language = reader.String(tsize); + break; + case 0x6D80: // ContentEncodings: the frames are compressed, stripped or encrypted + track.Encoded = true; + reader.Skip(tsize); + break; case 0x55EE: // MaxBlockAdditionID, and others: ignored reader.Skip(tsize); break; @@ -289,6 +299,7 @@ public static class MatroskaReader } stream.Position = Math.Min(entryEnd, stream.Length); + state.TrackCount++; if (track.Type == 1 && state.Video is null) { state.Video = track; @@ -498,6 +509,8 @@ public static class MatroskaReader internal double Roll; internal int SampleRate; internal int Channels; + internal string? Language; + internal bool Encoded; internal readonly List Samples = []; } @@ -509,6 +522,12 @@ public static class MatroskaReader internal TrackEntry? Video; internal TrackEntry? Audio; + /// Every TrackEntry of the file. + internal int TrackCount; + + /// True when the segment has a Tags element. + internal bool HasTags; + /// Nanoseconds of one unit of the sample times; fixed by the first block, 0 before. private long unit; @@ -599,12 +618,15 @@ public static class MatroskaReader Timescale = timescale, Duration = trackUnits, Samples = samples, + Language = Language(v.Language), + Encoded = v.Encoded, }; } AudioTrack? audio = null; if (Audio is { } a) { + var asc = a.CodecId == "A_AAC" ? a.CodecPrivate : a.CodecId.StartsWith("A_AAC/", StringComparison.Ordinal) ? LegacyAacConfig(a) : null; audio = new AudioTrack { Codec = a.CodecId switch @@ -619,16 +641,91 @@ public static class MatroskaReader CodecTag = a.CodecId, SampleRate = a.SampleRate, Channels = a.Channels, - AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null, + AacConfiguration = asc, + AudioObjectType = AudioTrack.ObjectTypeOf(asc), Timescale = timescale, Duration = trackUnits, Samples = a.Samples, + Language = Language(a.Language), + Encoded = a.Encoded, }; } var seconds = DurationTicks * TimecodeScale / 1e9; TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; - return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; + return new MediaContainer + { + Format = ContainerFormat.Matroska, + CreatedAt = Created, + Duration = duration, + Video = video, + Audio = audio, + TrackCount = TrackCount, + HasUserData = HasTags, + }; + } + + /// A three-letter ISO 639-2 language; null for «und», absent or malformed. + private static string? Language(string? code) => + code is { Length: 3 } && code != "und" && code.All(char.IsAsciiLetterLower) ? code : null; + + /// + /// The AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1) of a track with an old codec ID that names the profile + /// («A_AAC/MPEG4/LC», «A_AAC/MPEG2/MAIN», «…/SBR»...) instead of carrying the configuration in CodecPrivate: + /// object type, sampling frequency index (or the explicit frequency), channel configuration, then a + /// GASpecificConfig of zeros (1024-sample frames, no core coder, no extension). + /// + private static byte[]? LegacyAacConfig(TrackEntry track) + { + if (track.CodecPrivate is { Length: >= 2 }) + { + return track.CodecPrivate; + } + + var profile = track.CodecId[(track.CodecId.LastIndexOf('/') + 1)..]; + var objectType = profile switch + { + "MAIN" => 1, + "LC" or "SBR" => 2, // SBR is signalled implicitly: the core rate in SamplingFrequency + "SSR" => 3, + "LTP" => 4, + _ => 0, + }; + if (objectType == 0 || track.SampleRate <= 0 || track.Channels is < 1 or > 7) + { + return null; + } + + int[] rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + var index = Array.IndexOf(rates, track.SampleRate); + var bits = new List<(int Value, int Count)> { (objectType, 5) }; + if (index >= 0) + { + bits.Add((index, 4)); + } + else + { + bits.Add((15, 4)); + bits.Add((track.SampleRate & 0xFFFFFF, 24)); + } + + bits.Add((track.Channels, 4)); + bits.Add((0, 3)); + var total = bits.Sum(b => b.Count); + var config = new byte[(total + 7) / 8]; + var position = 0; + foreach (var (value, count) in bits) + { + for (var i = count - 1; i >= 0; i--, position++) + { + if (((value >> i) & 1) != 0) + { + config[position / 8] |= (byte)(0x80 >> (position % 8)); + } + } + } + + return config; } } diff --git a/src/Febe.Core/Codecs/Containers/MediaContainer.cs b/src/Febe.Core/Codecs/Containers/MediaContainer.cs index b1b7337..7cad5fd 100644 --- a/src/Febe.Core/Codecs/Containers/MediaContainer.cs +++ b/src/Febe.Core/Codecs/Containers/MediaContainer.cs @@ -94,6 +94,38 @@ public abstract class MediaTrack /// The four-character code or codec identifier of the container, for messages. public string CodecTag { get; init; } = string.Empty; + /// + /// The media time (track units) shown at the start of the presentation, from the first non-empty edit of an ISO edit + /// list; null when the track has no edit list (Matroska never has one). The reader's presentation times already + /// have it subtracted. + /// + public long? EditMediaTime { get; init; } + + /// + /// The empty edits before the first non-empty one (a delayed start), in track units; 0 when none. A sample is shown + /// at its plus this. + /// + public long EmptyEditDuration { get; init; } + + /// + /// How long the first non-empty edit shows the media from , in track units; null when the + /// edit runs to the end of the media (no segment written) or there is no edit list. Shorter than the media after + /// : the end of the media is hidden (a trim, the padding of AAC). + /// + public long? EditSegmentDuration { get; init; } + + /// The edits of the edit list after the leading empty ones (1 for an ordinary one, 0 without edit list). + public int EditCount { get; init; } + + /// The language of the track as an ISO 639-2 code («ita», «eng»); null when unknown or undetermined. + public string? Language { get; init; } + + /// + /// True when the frames of the track are stored transformed (Matroska ContentEncodings: compression, header + /// stripping, encryption): their bytes are not the codec's. + /// + public bool Encoded { get; init; } + /// Time in seconds of a value in track units. public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0; } @@ -143,6 +175,26 @@ public sealed class AudioTrack : MediaTrack /// The AudioSpecificConfig of an AAC track. public byte[]? AacConfiguration { get; init; } + + /// The audio object type of an AAC track (ISO/IEC 14496-3: 2 is AAC LC, 5 SBR, 29 PS); null when unknown. + public int? AudioObjectType { get; init; } + + /// The audio object type of an AudioSpecificConfig (5 bits, 31 escaping to 32 + 6 more). + internal static int? ObjectTypeOf(byte[]? asc) + { + if (asc is not { Length: > 0 }) + { + return null; + } + + var type = asc[0] >> 3; + if (type == 31) + { + return asc.Length > 1 ? 32 + (((asc[0] & 7) << 3) | (asc[1] >> 5)) : null; + } + + return type == 0 ? null : type; + } } /// What a container says: its creation time, duration and first video and audio tracks. @@ -153,6 +205,21 @@ public sealed class MediaContainer /// Creation time written in the container, when plausible. public DateTimeOffset? CreatedAt { get; init; } + /// Modification time written in the container (ISO mvhd), when plausible. + public DateTimeOffset? ModifiedAt { get; init; } + + /// The major brand of an ISO file («isom», «qt », «M4V », «3gp4»...), null for other containers or without ftyp. + public string? MajorBrand { get; init; } + + /// Tracks of every kind in the file (video, audio, timecode, subtitles...), of which only the first video and audio are read. + public int TrackCount { get; init; } + + /// + /// True when the file has metadata of its own that the readers do not interpret (ISO udta or meta + /// boxes, Matroska tags): a remux does not carry it. + /// + public bool HasUserData { get; init; } + /// Duration of the whole presentation. public TimeSpan? Duration { get; init; } diff --git a/src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs b/src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs new file mode 100644 index 0000000..2cff9e6 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs @@ -0,0 +1,337 @@ +namespace Febe.Core.Codecs.Containers; + +/// Why a video cannot be brought into MP4 without re-encoding it (tappa E3: then it is copied as it is). +public enum RemuxRefusal +{ + /// It can. + None, + + /// Not a video Febe recognises, or a file without a video track. + NotAVideo, + + /// Already an MP4 (an ISO file with an .mp4 name and a brand other than QuickTime's): copied byte for byte. + AlreadyMp4, + + /// A container whose frames MP4 cannot take as they are (AVI, ASF, FLV, MPEG-PS, Annex B streams). + ContainerNotRemuxable, + + /// A video codec other than H.264 and HEVC. + VideoCodec, + + /// An audio codec other than AAC and MP3. + AudioCodec, + + /// A track without the configuration record of its codec. + MissingConfiguration, + + /// A Matroska track whose frames are stored transformed (ContentEncodings). + EncodedTrack, + + /// A track with more than one edit (a cut or a still segment), which the writer does not reproduce. + EditList, + + /// A video track without samples. + NoSamples, + + /// A damaged or truncated file. + Unreadable, +} + +/// +/// A remux planned by : the source as +/// read, the MP4 to write (its exact length is ) and the note codes of what it does not keep. +/// +public sealed record RemuxPlan(MediaContainer Source, Mp4Layout Layout, IReadOnlyList Losses) +{ + /// Bytes of the MP4 that writes. + public long OutputLength => Layout.Length; + + /// The stream the sample writers of read from, set by . + internal RemuxSource Reading { get; init; } = new(); +} + +/// Where the samples of a planned remux are read from while it is written. +internal sealed class RemuxSource +{ + internal Stream? Stream { get; set; } +} + +/// +/// Brings a MOV, M4V, 3GP or Matroska video into MP4 by copying its samples (tappa E3, «MOV → MP4 solo rimuxaggio»): +/// one H.264 or HEVC video track and at most one AAC or MP3 audio track, with their configuration records, sync +/// samples, composition offsets, edit (the delayed start and the hidden AAC priming), rotation, language and dates. +/// Nothing is re-encoded; anything that would need it is refused with its reason. Only the tables and the +/// moov are in memory: the samples are read and written one at a time, and the same source always gives the +/// same bytes (the reader's «now» is fixed). +/// +public static class Mp4Remuxer +{ + /// Note code (with «:n») of the tracks left behind: timecode, subtitles, a second audio track... + public const string LostTracks = "LostTracks"; + + /// Note code of the metadata of the source the MP4 does not carry (ISO udta/meta, Matroska tags). + public const string LostVideoMetadata = "LostVideoMetadata"; + + /// Plans the remux of a seekable without knowing its name: never . + public static RemuxRefusal Check(Stream source, out RemuxPlan? plan, CancellationToken ct) => Check(source, null, out plan, ct); + + /// + /// Plans the remux of a seekable ; (or a path) tells an MP4 + /// already (). Never throws for a bad file. + /// + public static RemuxRefusal Check(Stream source, string? fileName, out RemuxPlan? plan, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(source); + plan = null; + MediaContainer? container; + try + { + container = ContainerReader.Read(source, ContainerReader.AnyDate, samples: true, ct); + } + catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException or ArgumentException + or IndexOutOfRangeException or OverflowException or InvalidDataException) + { + return RemuxRefusal.Unreadable; + } + + if (container is null) + { + return RemuxRefusal.NotAVideo; + } + + if (container.Format is not (ContainerFormat.IsoBmff or ContainerFormat.Matroska)) + { + return container.Video is null ? RemuxRefusal.NotAVideo : RemuxRefusal.ContainerNotRemuxable; + } + + if (container.Format == ContainerFormat.IsoBmff && container.MajorBrand != "qt " + && string.Equals(Path.GetExtension(fileName ?? string.Empty), ".mp4", StringComparison.OrdinalIgnoreCase)) + { + return RemuxRefusal.AlreadyMp4; + } + + if (container.Video is not { } video) + { + return RemuxRefusal.NotAVideo; + } + + var audio = container.Audio is { Samples.Count: > 0 } a ? a : null; + var refusal = Refusal(video, audio); + if (refusal != RemuxRefusal.None) + { + return refusal; + } + + var length = source.Length; + if (!InFile(video, length) || (audio is not null && !InFile(audio, length))) + { + return RemuxRefusal.Unreadable; + } + + var reading = new RemuxSource(); + var tracks = new List { VideoTrackOf(container, video, reading) }; + if (audio is not null) + { + tracks.Add(AudioTrackOf(container, audio, reading)); + } + + Mp4Layout layout; + try + { + layout = Mp4Writer.Prepare(tracks, new Mp4MovieInfo(container.CreatedAt, container.ModifiedAt)); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) + { + return RemuxRefusal.Unreadable; + } + + var losses = new List(); + var dropped = container.TrackCount - tracks.Count; + if (dropped > 0) + { + losses.Add(FormattableString.Invariant($"{LostTracks}:{dropped}")); + } + + if (container.HasUserData) + { + losses.Add(LostVideoMetadata); + } + + plan = new RemuxPlan(container, layout, losses) { Reading = reading }; + return RemuxRefusal.None; + } + + /// + /// Writes the MP4 of into , reading the samples from + /// (the same file the plan was made from, seekable). is checked + /// between samples. + /// + /// A sample lies outside the file (it changed since the plan). + public static void Write(RemuxPlan plan, Stream source, Stream output, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(output); + lock (plan.Reading) + { + plan.Reading.Stream = source; + try + { + plan.Layout.WriteTo(output, ct); + } + finally + { + plan.Reading.Stream = null; + } + } + } + + private static RemuxRefusal Refusal(VideoTrack video, AudioTrack? audio) + { + if (video.Encoded || audio?.Encoded == true) + { + return RemuxRefusal.EncodedTrack; + } + + if (video.Codec is not (VideoCodec.H264 or VideoCodec.Hevc)) + { + return RemuxRefusal.VideoCodec; + } + + if (video.AnnexB) + { + return RemuxRefusal.ContainerNotRemuxable; + } + + if ((video.Codec == VideoCodec.H264 ? video.AvcConfiguration : video.HevcConfiguration) is not { Length: > 0 }) + { + return RemuxRefusal.MissingConfiguration; + } + + if (video.Samples.Count == 0) + { + return RemuxRefusal.NoSamples; + } + + if (video.EditCount > 1) + { + return RemuxRefusal.EditList; + } + + if (audio is null) + { + return RemuxRefusal.None; + } + + if (audio.Codec is not (AudioCodec.Aac or AudioCodec.Mp3)) + { + return RemuxRefusal.AudioCodec; + } + + if (audio.Codec == AudioCodec.Aac && audio.AacConfiguration is not { Length: >= 2 }) + { + return RemuxRefusal.MissingConfiguration; + } + + return audio.EditCount > 1 ? RemuxRefusal.EditList : RemuxRefusal.None; + } + + private static bool InFile(MediaTrack track, long length) + { + foreach (var s in track.Samples) + { + if (s.Offset < 0 || s.Size < 0 || s.Size > ContainerReader.MaxSampleSize || s.Offset + s.Size > length) + { + return false; + } + } + + return true; + } + + private static Mp4OutputTrack VideoTrackOf(MediaContainer container, VideoTrack video, RemuxSource reading) + { + var (samples, edit) = Times(container, video); + return new Mp4OutputTrack + { + IsVideo = true, + Timescale = video.Timescale, + Samples = samples, + WriteSample = Writer(video, reading), + Width = video.Width, + Height = video.Height, + Rotation = video.Rotation, + AvcConfiguration = video.Codec == VideoCodec.H264 ? video.AvcConfiguration : null, + HevcConfiguration = video.Codec == VideoCodec.Hevc ? video.HevcConfiguration : null, + SampleEntryType = container.Format == ContainerFormat.IsoBmff ? video.CodecTag : null, + Language = video.Language, + EditMediaTime = edit, + EmptyEditDuration = video.EmptyEditDuration, + EditSegmentDuration = video.EditSegmentDuration, + LastSampleDuration = LastDuration(video), + }; + } + + private static Mp4OutputTrack AudioTrackOf(MediaContainer container, AudioTrack audio, RemuxSource reading) + { + var (samples, edit) = Times(container, audio); + return new Mp4OutputTrack + { + IsVideo = false, + Timescale = audio.Timescale, + Samples = samples, + WriteSample = Writer(audio, reading), + AacConfiguration = audio.Codec == AudioCodec.Aac ? audio.AacConfiguration : null, + IsMp3 = audio.Codec == AudioCodec.Mp3, + SampleRate = audio.SampleRate, + Channels = audio.Channels, + Language = audio.Language, + EditMediaTime = edit, + EmptyEditDuration = audio.EmptyEditDuration, + EditSegmentDuration = audio.EditSegmentDuration, + LastSampleDuration = LastDuration(audio), + }; + } + + /// + /// The samples with their composition times and the media time shown first: an ISO reader's presentation times + /// have the edit's media time taken off, so it is put back and becomes the edit of the output; without an edit + /// list (and in Matroska, whose block times are presentation times) the media time 0 is shown at 0. + /// + private static (Mp4OutputSample[] Samples, long Edit) Times(MediaContainer container, MediaTrack track) + { + var edit = container.Format == ContainerFormat.IsoBmff ? track.EditMediaTime ?? 0 : 0; + var samples = new Mp4OutputSample[track.Samples.Count]; + for (var i = 0; i < samples.Length; i++) + { + var s = track.Samples[i]; + samples[i] = new Mp4OutputSample(s.Size, s.DecodeTime, s.PresentationTime + edit, s.Key); + } + + return (samples, edit); + } + + /// The duration of the last sample from the track's duration, when it is plausible (else the writer's default). + private static long LastDuration(MediaTrack track) + { + var samples = track.Samples; + var last = track.Duration - samples[^1].DecodeTime; + if (last <= 0) + { + return 0; + } + + var before = samples.Count > 1 ? samples[^1].DecodeTime - samples[^2].DecodeTime : last; + return before > 0 && last > 4 * before ? 0 : last; + } + + private static Action Writer(MediaTrack track, RemuxSource reading) + { + var buffer = new byte[64 * 1024]; + return (i, output) => + { + var source = reading.Stream ?? throw new InvalidOperationException("Il rimuxaggio non ha la sua sorgente."); + output.Write(ContainerReader.ReadSample(source, track.Samples[i], ref buffer)); + }; + } +} diff --git a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs index 4c3838f..145c5ae 100644 --- a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs +++ b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs @@ -41,6 +41,135 @@ public sealed class Mp4OutputTrack /// Duration of the last sample, when the times cannot tell it (0: as the one before it). public long LastSampleDuration { get; init; } + + /// The ISO 639-2/T language of the mdhd («ita»); null writes «und». + public string? Language { get; init; } + + /// + /// The sample entry of a video track: «avc1» or «avc3» (H.264), «hvc1» or «hev1» (HEVC), as the source has it; + /// null writes «avc1» or «hvc1». + /// + public string? SampleEntryType { get; init; } + + /// + /// MPEG-1/2 audio layer III in an mp4a entry (objectTypeIndication 0x6B, or 0x69 at 24 kHz and below, + /// ISO/IEC 14496-1): it has no AudioSpecificConfig, so stays null. + /// + public bool IsMp3 { get; init; } + + /// + /// The media time, on the scale of , shown at the start of the + /// presentation (the source's edit, so that AAC priming stays hidden); null lets the writer start at the first + /// shown sample, as before tappa E3. + /// + public long? EditMediaTime { get; init; } + + /// A delayed start in track units: an empty edit before the media (0: none). + public long EmptyEditDuration { get; init; } + + /// + /// How long the edit shows the media, in track units (the source's segment: a trimmed end stays hidden); null shows + /// it from to the end. Never longer than the media. + /// + public long? EditSegmentDuration { get; init; } +} + +/// The dates of the movie header; the modification date falls back to the creation date. +public sealed record Mp4MovieInfo(DateTimeOffset? Created, DateTimeOffset? Modified); + +/// +/// An MP4 file planned by : its exact is known before a byte is +/// written, and streams it, one sample at a time. +/// +public sealed class Mp4Layout +{ + private readonly IReadOnlyList tracks; + private readonly List<(int Track, int First, int Count)> chunks; + private readonly byte[] head; + + internal Mp4Layout(IReadOnlyList tracks, List<(int Track, int First, int Count)> chunks, byte[] head, long payload) + { + this.tracks = tracks; + this.chunks = chunks; + this.head = head; + Length = head.LongLength + payload; + } + + /// Bytes of the whole file. + public long Length { get; } + + /// Writes the file into (from its current position). + /// A sample writer wrote another number of bytes than its size. + public void WriteTo(Stream output, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(output); + var counting = new CountingStream(output); + counting.Write(head); + foreach (var (track, first, count) in chunks) + { + for (var k = first; k < first + count; k++) + { + ct.ThrowIfCancellationRequested(); + var before = counting.Count; + tracks[track].WriteSample(k, counting); + if (counting.Count - before != tracks[track].Samples[k].Size) + { + throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata."); + } + } + } + + if (counting.Count != Length) + { + throw new InvalidOperationException("Il file scritto non ha la lunghezza prevista."); + } + } + + /// Counts the bytes written through it, whatever the stream below can tell. + private sealed class CountingStream(Stream inner) : Stream + { + public long Count { get; private set; } + + 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 => Count; + set => throw new NotSupportedException(); + } + + public override void Flush() => inner.Flush(); + + 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(); + + public override void Write(byte[] buffer, int offset, int count) + { + inner.Write(buffer, offset, count); + Count += count; + } + + public override void Write(ReadOnlySpan buffer) + { + inner.Write(buffer); + Count += buffer.Length; + } + + public override void WriteByte(byte value) + { + inner.WriteByte(value); + Count++; + } + } } /// @@ -57,6 +186,16 @@ public static class Mp4Writer public static void Write(Stream output, IReadOnlyList tracks, DateTimeOffset? created = null) { ArgumentNullException.ThrowIfNull(output); + Prepare(tracks, created is null ? null : new Mp4MovieInfo(created, created)).WriteTo(output); + } + + /// + /// Plans the file of : every box but the media data is built, so the length is known; + /// writes it. + /// + /// A track has no samples, no timescale or no codec configuration. + public static Mp4Layout Prepare(IReadOnlyList tracks, Mp4MovieInfo? info) + { ArgumentNullException.ThrowIfNull(tracks); if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0)) { @@ -65,7 +204,7 @@ public static class Mp4Writer foreach (var track in tracks) { - if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null) + if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null && !track.IsMp3) { throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks)); } @@ -84,7 +223,9 @@ public static class Mp4Writer var wideMdat = payload + 8 > uint.MaxValue; var ftyp = Ftyp(); - var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL; + var creation = info?.Created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL; + var modification = (info?.Modified ?? info?.Created) is { } m && m > Epoch1904 ? (ulong)(m - Epoch1904).TotalSeconds : 0UL; + var time = (creation, modification); // The moov box has the same size whatever the chunk offsets: build it once to know where the data starts. var co64 = false; @@ -110,40 +251,35 @@ public static class Mp4Writer } moov = Moov(tracks, timing, chunks, offsets, co64, time); - output.Write(ftyp); - output.Write(moov); - Span header = stackalloc byte[16]; + var head = new byte[ftyp.Length + moov.Length + (wideMdat ? 16 : 8)]; + ftyp.CopyTo(head, 0); + moov.CopyTo(head, ftyp.Length); + var header = head.AsSpan(ftyp.Length + moov.Length); if (wideMdat) { BinaryPrimitives.WriteUInt32BigEndian(header, 1); "mdat"u8.CopyTo(header[4..]); BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16)); - output.Write(header); } else { BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8)); "mdat"u8.CopyTo(header[4..]); - output.Write(header[..8]); } - foreach (var (track, first, count) in chunks) - { - for (var k = first; k < first + count; k++) - { - var before = output.CanSeek ? output.Position : -1; - tracks[track].WriteSample(k, output); - if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size) - { - throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata."); - } - } - } + return new Mp4Layout(tracks, chunks, head, payload); } - /// Times of a track as the boxes need them. - private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey) + /// + /// Times of a track as the boxes need them; , (the media + /// the edit shows, from ) and (where the last + /// sample stops being shown, in composition time) are in track units. + /// + private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown, long PresentationEnd) { + /// Whether the edit hides the end of the media (it must then be written). + public bool TrimsEnd => Shown < PresentationEnd - EditMediaTime; + internal static Timing Of(Mp4OutputTrack track) { var samples = track.Samples; @@ -180,9 +316,31 @@ public static class Mp4Writer total += d; } - // The edit list starts the presentation at the first shown sample. - var editTime = minPts - first + shift; - return new Timing(durations, offsets, total, editTime, allKey); + // The presentation ends where the sample shown last stops, in composition time: with B frames that is later + // than the decoding durations add up to (by the first composition offset), and the edit starts there too. + long presentationEnd = 0; + for (var i = 0; i < n; i++) + { + presentationEnd = Math.Max(presentationEnd, samples[i].DecodeTime - first + offsets[i] + durations[i]); + } + + // The edit list starts the presentation at the first shown sample, or where the track says; a start before + // the first sample becomes an empty edit. + var editTime = (track.EditMediaTime ?? minPts) - first + shift; + var empty = Math.Max(0, track.EmptyEditDuration); + if (editTime < 0) + { + empty += -editTime; + editTime = 0; + } + + var shown = Math.Max(0, presentationEnd - editTime); + if (track.EditSegmentDuration is { } segment && segment > 0) + { + shown = Math.Min(shown, segment); + } + + return new Timing(durations, offsets, total, editTime, allKey, empty, shown, presentationEnd); } } @@ -222,17 +380,17 @@ public static class Mp4Writer return box.ToArray(); } - private static byte[] Moov(IReadOnlyList tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) + private static byte[] Moov(IReadOnlyList tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time) { long movieDuration = 0; for (var t = 0; t < tracks.Count; t++) { - movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale)); + movieDuration = Math.Max(movieDuration, EmptyMovie(timing[t], tracks[t].Timescale) + ToMovie(timing[t].Shown, tracks[t].Timescale)); } var moov = new Box("moov"); var mvhd = new Box("mvhd"); - var wide = movieDuration > uint.MaxValue || time > uint.MaxValue; + var wide = movieDuration > uint.MaxValue || Wide(time); mvhd.U32(wide ? 0x01000000u : 0); Times(mvhd, wide, time, MovieTimescale, movieDuration); mvhd.U32(0x00010000); @@ -253,19 +411,25 @@ public static class Mp4Writer private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale); - private static void Times(Box box, bool wide, ulong time, long timescale, long duration) + /// The empty edit of a track in movie units, rounded to the nearest. + private static long EmptyMovie(Timing timing, long timescale) => + timing.EmptyEdit <= 0 ? 0 : (long)((((Int128)timing.EmptyEdit * MovieTimescale) + (timescale / 2)) / timescale); + + private static bool Wide((ulong Created, ulong Modified) time) => time.Created > uint.MaxValue || time.Modified > uint.MaxValue; + + private static void Times(Box box, bool wide, (ulong Created, ulong Modified) time, long timescale, long duration) { if (wide) { - box.U64(time); - box.U64(time); + box.U64(time.Created); + box.U64(time.Modified); box.U32((uint)timescale); box.U64((ulong)duration); } else { - box.U32((uint)time); - box.U32((uint)time); + box.U32((uint)time.Created); + box.U32((uint)time.Modified); box.U32((uint)timescale); box.U32((uint)duration); } @@ -293,25 +457,27 @@ public static class Mp4Writer } } - private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) + private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time) { var trak = new Box("trak"); - var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale); - var wide = duration > uint.MaxValue || time > uint.MaxValue; + var segment = ToMovie(timing.Shown, track.Timescale); + var empty = EmptyMovie(timing, track.Timescale); + var duration = empty + segment; + var wide = duration > uint.MaxValue || Wide(time); var tkhd = new Box("tkhd"); tkhd.U32((wide ? 0x01000000u : 0) | 3); if (wide) { - tkhd.U64(time); - tkhd.U64(time); + tkhd.U64(time.Created); + tkhd.U64(time.Modified); tkhd.U32((uint)index + 1); tkhd.U32(0); tkhd.U64((ulong)duration); } else { - tkhd.U32((uint)time); - tkhd.U32((uint)time); + tkhd.U32((uint)time.Created); + tkhd.U32((uint)time.Modified); tkhd.U32((uint)index + 1); tkhd.U32(0); tkhd.U32((uint)duration); @@ -327,13 +493,21 @@ public static class Mp4Writer tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0); trak.Child(tkhd); - if (timing.EditMediaTime != 0) + if (timing.EditMediaTime != 0 || empty > 0 || timing.TrimsEnd) { var edts = new Box("edts"); var elst = new Box("elst"); elst.U32(0x01000000); - elst.U32(1); - elst.U64((ulong)duration); + elst.U32(empty > 0 ? 2u : 1u); + if (empty > 0) + { + elst.U64((ulong)empty); + elst.U64(ulong.MaxValue); // media_time −1: an empty edit + elst.U16(1); + elst.U16(0); + } + + elst.U64((ulong)segment); elst.U64((ulong)timing.EditMediaTime); elst.U16(1); elst.U16(0); @@ -343,10 +517,10 @@ public static class Mp4Writer var mdia = new Box("mdia"); var mdhd = new Box("mdhd"); - var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue; + var mediaWide = timing.MediaDuration > uint.MaxValue || Wide(time); mdhd.U32(mediaWide ? 0x01000000u : 0); Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration); - mdhd.U16(0x55C4); // «und» + mdhd.U16(PackedLanguage(track.Language)); mdhd.U16(0); mdia.Child(mdhd); @@ -389,6 +563,17 @@ public static class Mp4Writer return trak; } + /// An ISO 639-2/T code packed in 15 bits (ISO/IEC 14496-12 §8.4.2.3); «und» for anything else. + private static ushort PackedLanguage(string? language) + { + if (language is not { Length: 3 } || !language.All(char.IsAsciiLetterLower)) + { + return 0x55C4; // «und» + } + + return (ushort)(((language[0] - 0x60) << 10) | ((language[1] - 0x60) << 5) | (language[2] - 0x60)); + } + private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64) { var stbl = new Box("stbl"); @@ -540,7 +725,10 @@ public static class Mp4Writer private static Box Avc1(Mp4OutputTrack track) { var hevc = track.HevcConfiguration is not null; - var entry = new Box(hevc ? "hvc1" : "avc1"); + var type = hevc + ? track.SampleEntryType is "hvc1" or "hev1" ? track.SampleEntryType : "hvc1" + : track.SampleEntryType is "avc1" or "avc3" ? track.SampleEntryType : "avc1"; + var entry = new Box(type); entry.Zero(6); entry.U16(1); entry.Zero(16); @@ -571,10 +759,11 @@ public static class Mp4Writer entry.U16(0); entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16); - var asc = track.AacConfiguration!; - var decoderSpecific = Descriptor(0x05, asc); + var decoderSpecific = track.IsMp3 ? [] : Descriptor(0x05, track.AacConfiguration!); var config = new byte[13 + decoderSpecific.Length]; - config[0] = 0x40; // MPEG-4 audio + // MPEG-4 audio, or layer III: MPEG-1 audio (ISO/IEC 11172-3, 32 to 48 kHz) or the MPEG-2 audio of the lower + // rates (ISO/IEC 13818-3, 16 to 24 kHz and the 8 to 12 kHz of «MPEG-2.5»): ISO/IEC 14496-1 Table 5. + config[0] = !track.IsMp3 ? (byte)0x40 : track.SampleRate is > 0 and <= 24000 ? (byte)0x69 : (byte)0x6B; config[1] = 0x15; // audio stream decoderSpecific.CopyTo(config, 13); byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])]; diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.cs b/src/Febe.Core/Codecs/H264/H264Decoder.cs index f11cf98..b32d4a2 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.cs @@ -216,6 +216,93 @@ public sealed partial class H264Decoder } } + /// + /// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0 and exact_match_flag + /// 1: decoding from it gives exact pictures from it on in output order, as from an IDR picture. Only the SEI before + /// the first slice counts. + /// + internal static bool HasExactRecoveryPoint(ReadOnlySpan accessUnit, int lengthSize) + { + var position = 0; + while (true) + { + Range unit; + var more = lengthSize == 0 + ? NalUnits.NextAnnexB(accessUnit, ref position, out unit) + : NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit); + if (!more) + { + return false; + } + + var nal = accessUnit[unit]; + var type = nal[0] & 0x1F; + if (type is 1 or 2 or 5) + { + return false; + } + + if (type != 6) + { + continue; + } + + try + { + var sei = NalUnits.Parse(nal); + var data = sei.Rbsp; + var length = sei.Length; + var p = sei.HeaderLength; + while (p < length - 1) + { + var payloadType = 0; + while (p < length && data[p] == 0xFF) + { + payloadType += 255; + p++; + } + + var payloadSize = 0; + if (p < length) + { + payloadType += data[p++]; + } + + while (p < length && data[p] == 0xFF) + { + payloadSize += 255; + p++; + } + + if (p >= length) + { + break; + } + + payloadSize += data[p++]; + if (payloadType == 6) + { + // recovery_frame_cnt 0, then exact_match_flag 1 (§D.2.8): with 0 the pictures from here may + // differ from those decoded from the IDR before, so it is no exact start. + if (payloadSize <= 0) + { + return false; + } + + var reader = new RbspReader(data, Math.Min(length, p + payloadSize), p); + return reader.ReadUe() == 0 && reader.BitsLeft > 0 && reader.ReadFlag(); + } + + p += payloadSize; + } + } + catch (H264Exception) + { + // A damaged SEI says nothing. + } + } + } + private void DecodeUnitsAnnexB(ReadOnlySpan stream) { var position = 0; diff --git a/src/Febe.Core/Codecs/H264/H264PcmWriter.cs b/src/Febe.Core/Codecs/H264/H264PcmWriter.cs new file mode 100644 index 0000000..6582402 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264PcmWriter.cs @@ -0,0 +1,322 @@ +using Febe.Core.Codecs.Containers; + +namespace Febe.Core.Codecs.H264; + +/// +/// One picture of an I_PCM stream in 4:2:0: is Width × Height luma samples, and +/// are Width/2 × Height/2, row by row. Width and height are multiples of 16. +/// +public sealed class H264PcmPicture +{ + public H264PcmPicture(int width, int height) + { + if (width <= 0 || height <= 0 || width % 16 != 0 || height % 16 != 0) + { + throw new ArgumentOutOfRangeException(nameof(width), "Larghezza e altezza devono essere multipli di 16."); + } + + Width = width; + Height = height; + Y = new byte[width * height]; + Cb = new byte[width / 2 * (height / 2)]; + Cr = new byte[width / 2 * (height / 2)]; + } + + public int Width { get; } + + public int Height { get; } + + public byte[] Y { get; } + + public byte[] Cb { get; } + + public byte[] Cr { get; } +} + +/// +/// Writes H.264 streams made only of IDR pictures of I_PCM macroblocks (ITU-T H.264 §7.3: Baseline parameter sets, one +/// slice per picture, every sample written as it is), muxed in MP4 with . Every pixel is known +/// and every picture is an exact start for a decoder: the demo's video (frames in --demo) and the tests use it. +/// Nothing is compressed, so the files are large (about 1,5 bytes per pixel per picture): for short, small videos only. +/// +public static class H264PcmWriter +{ + /// Width of the demo video (15 macroblocks, no cropping). + public const int DemoWidth = 240; + + /// Height of the demo video (27 macroblocks, no cropping). + public const int DemoHeight = 432; + + /// Pictures per second of the demo video. + public const int DemoFps = 8; + + /// Pictures of the demo video (two seconds). + public const int DemoPictures = 16; + + /// The sequence parameter set (RBSP with emulation prevention, no start code), POC type 2, no VUI. + public static byte[] Sps(int width, int height) + { + var bits = new Bits(); + bits.Write(66, 8); // profile_idc: Baseline + bits.Write(0, 8); // constraint_set flags + bits.Write(30, 8); // level_idc 3.0 + bits.Ue(0); // seq_parameter_set_id + bits.Ue(0); // log2_max_frame_num_minus4 + bits.Ue(2); // pic_order_cnt_type: output order = decoding order + bits.Ue(1); // max_num_ref_frames + bits.Write(0, 1); // gaps_in_frame_num_value_allowed_flag + bits.Ue((uint)(width / 16) - 1); // pic_width_in_mbs_minus1 + bits.Ue((uint)(height / 16) - 1); // pic_height_in_map_units_minus1 + bits.Write(1, 1); // frame_mbs_only_flag + bits.Write(1, 1); // direct_8x8_inference_flag + bits.Write(0, 1); // frame_cropping_flag + bits.Write(0, 1); // vui_parameters_present_flag + return Nal(0x67, bits); + } + + /// The picture parameter set (CAVLC, one slice group, deblocking control present). + public static byte[] Pps() + { + var bits = new Bits(); + bits.Ue(0); // pic_parameter_set_id + bits.Ue(0); // seq_parameter_set_id + bits.Write(0, 1); // entropy_coding_mode_flag: CAVLC + bits.Write(0, 1); // bottom_field_pic_order_in_frame_present_flag + bits.Ue(0); // num_slice_groups_minus1 + bits.Ue(0); // num_ref_idx_l0_default_active_minus1 + bits.Ue(0); // num_ref_idx_l1_default_active_minus1 + bits.Write(0, 1); // weighted_pred_flag + bits.Write(0, 2); // weighted_bipred_idc + bits.Se(0); // pic_init_qp_minus26 + bits.Se(0); // pic_init_qs_minus26 + bits.Se(0); // chroma_qp_index_offset + bits.Write(1, 1); // deblocking_filter_control_present_flag + bits.Write(0, 1); // constrained_intra_pred_flag + bits.Write(0, 1); // redundant_pic_cnt_present_flag + return Nal(0x68, bits); + } + + /// An IDR picture of I_PCM macroblocks (one slice, deblocking off), as a NAL unit without start code. + /// The samples. + /// idr_pic_id: two IDR pictures in a row must differ (0 and 1 alternate). + public static byte[] Idr(H264PcmPicture picture, int idrPicId) + { + ArgumentNullException.ThrowIfNull(picture); + var bits = new Bits(picture.Y.Length * 3 / 2 + 1024); + bits.Ue(0); // first_mb_in_slice + bits.Ue(7); // slice_type: I (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + bits.Write(0, 4); // frame_num + bits.Ue((uint)idrPicId); + bits.Write(0, 1); // no_output_of_prior_pics_flag + bits.Write(0, 1); // long_term_reference_flag + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + var mbWidth = picture.Width / 16; + var mbHeight = picture.Height / 16; + var chromaWidth = picture.Width / 2; + for (var my = 0; my < mbHeight; my++) + { + for (var mx = 0; mx < mbWidth; mx++) + { + bits.Ue(25); // mb_type: I_PCM + bits.Align(); // pcm_alignment_zero_bit + for (var y = 0; y < 16; y++) + { + bits.Bytes(picture.Y.AsSpan(((my * 16) + y) * picture.Width + (mx * 16), 16)); + } + + foreach (var plane in new[] { picture.Cb, picture.Cr }) + { + for (var y = 0; y < 8; y++) + { + bits.Bytes(plane.AsSpan(((my * 8) + y) * chromaWidth + (mx * 8), 8)); + } + } + } + } + + return Nal(0x65, bits); + } + + /// The avcC of a stream with these parameter sets (ISO/IEC 14496-15 §5.3.3.1), lengths on 4 bytes. + public static byte[] AvcConfiguration(byte[] sps, byte[] pps) + { + ArgumentNullException.ThrowIfNull(sps); + ArgumentNullException.ThrowIfNull(pps); + return + [ + 1, sps[1], sps[2], sps[3], 0xFF, 0xE1, + (byte)(sps.Length >> 8), (byte)sps.Length, .. sps, + 1, (byte)(pps.Length >> 8), (byte)pps.Length, .. pps, + ]; + } + + /// + /// Writes an MP4 of pictures at per second, picture i given by + /// , every one an IDR sync sample. + /// + /// Where the file goes (from its current position). + /// Width, a multiple of 16. + /// Height, a multiple of 16. + /// Pictures. + /// Pictures per second. + /// The samples of picture i (called once per picture, in order). + /// The creation date of the movie; null writes none. + public static void WriteMp4(Stream output, int width, int height, int count, int fps, Func picture, DateTimeOffset? created = null) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(picture); + ArgumentOutOfRangeException.ThrowIfLessThan(count, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(fps, 1); + var sps = Sps(width, height); + var pps = Pps(); + var samples = new List(count); + for (var i = 0; i < count; i++) + { + var p = picture(i); + if (p.Width != width || p.Height != height) + { + throw new ArgumentException("Ogni fotogramma deve avere le dimensioni del video.", nameof(picture)); + } + + var nal = Idr(p, i % 2); + var sample = new byte[nal.Length + 4]; + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(sample, nal.Length); + nal.CopyTo(sample, 4); + samples.Add(sample); + } + + const int Ticks = 1000; + var track = new Mp4OutputTrack + { + IsVideo = true, + Timescale = (long)fps * Ticks, + Samples = [.. samples.Select((s, i) => new Mp4OutputSample(s.Length, (long)i * Ticks, (long)i * Ticks, true))], + WriteSample = (i, s) => s.Write(samples[i]), + Width = width, + Height = height, + AvcConfiguration = AvcConfiguration(sps, pps), + LastSampleDuration = Ticks, + }; + Mp4Writer.Write(output, [track], created); + } + + /// + /// The demo's video: ×, pictures per second for + /// two seconds, a diagonal gradient that moves to the right with colours that change over time. + /// + public static byte[] DemoVideo() + { + using var output = new MemoryStream(); + WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, DemoPicture, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero)); + return output.ToArray(); + } + + /// Picture of the demo video (luma 16-235, chroma 16-240: no zero byte). + public static H264PcmPicture DemoPicture(int index) + { + var p = new H264PcmPicture(DemoWidth, DemoHeight); + var shift = index * 219 / DemoPictures; + for (var y = 0; y < DemoHeight; y++) + { + for (var x = 0; x < DemoWidth; x++) + { + var ramp = ((x * 219 / DemoWidth) + (y * 219 / DemoHeight / 2) + 219 - shift) % 219; + p.Y[(y * DemoWidth) + x] = (byte)(16 + ramp); + } + } + + var chromaWidth = DemoWidth / 2; + for (var y = 0; y < DemoHeight / 2; y++) + { + for (var x = 0; x < chromaWidth; x++) + { + p.Cb[(y * chromaWidth) + x] = (byte)(64 + (y * 128 / (DemoHeight / 2))); + p.Cr[(y * chromaWidth) + x] = (byte)(64 + ((x * 64 / chromaWidth) + (index * 64 / DemoPictures))); + } + } + + return p; + } + + /// A NAL unit (header byte, then the RBSP with its trailing bits and emulation prevention). + private static byte[] Nal(byte header, Bits bits) + { + bits.Write(1, 1); // rbsp_stop_one_bit + bits.Align(); + var rbsp = bits.ToArray(); + var output = new List(rbsp.Length + (rbsp.Length / 64) + 2) { header }; + var zeros = 0; + foreach (var b in rbsp) + { + // Never two zero bytes followed by a byte up to 3 (§7.4.1). + if (zeros >= 2 && b <= 3) + { + output.Add(3); + zeros = 0; + } + + output.Add(b); + zeros = b == 0 ? zeros + 1 : 0; + } + + return [.. output]; + } + + /// A big-endian bit writer for the RBSP. + private sealed class Bits(int capacity = 64) + { + private readonly List _bytes = new(capacity); + private int _current; + private int _used; + + public void Write(uint value, int count) + { + for (var i = count - 1; i >= 0; i--) + { + _current = (_current << 1) | (int)((value >> i) & 1); + if (++_used == 8) + { + _bytes.Add((byte)_current); + _current = 0; + _used = 0; + } + } + } + + public void Ue(uint value) + { + var code = value + 1; + var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code); + Write(0, length - 1); + Write(code, length); + } + + public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1)); + + public void Align() + { + while (_used != 0) + { + Write(0, 1); + } + } + + /// Whole bytes, after . + public void Bytes(ReadOnlySpan data) + { + if (_used != 0) + { + throw new InvalidOperationException("Bytes only at a byte boundary."); + } + + foreach (var b in data) + { + _bytes.Add(b); + } + } + + public byte[] ToArray() => _used == 0 ? [.. _bytes] : throw new InvalidOperationException("Not aligned."); + } +} diff --git a/src/Febe.Core/Codecs/Images/ExifOrientation.cs b/src/Febe.Core/Codecs/Images/ExifOrientation.cs index 762d145..3611d8c 100644 --- a/src/Febe.Core/Codecs/Images/ExifOrientation.cs +++ b/src/Febe.Core/Codecs/Images/ExifOrientation.cs @@ -71,6 +71,67 @@ internal static class ExifOrientation return 1; } + /// + /// Whether is a TIFF structure an encoder can carry: the «II*\0» or «MM\0*» header and a + /// first IFD whose entry count lies inside the block. A damaged EXIF block fails and is left behind by a conversion. + /// + public static bool IsTiff(ReadOnlySpan tiff) + { + if (tiff.Length < 8 || !(tiff.StartsWith("II*\0"u8) || tiff.StartsWith("MM\0*"u8))) + { + return false; + } + + var ifd = U32(tiff[4..], tiff[0] == (byte)'I'); + return ifd >= 8 && ifd <= (uint)(tiff.Length - 2); + } + + /// + /// The smallest EXIF block that carries : a TIFF header in the byte order asked, a + /// first IFD at offset 8 with the one Orientation entry (SHORT, count 1) and no next IFD. 26 bytes. + /// + public static byte[] Minimal(int orientation, bool littleEndian) + { + ArgumentOutOfRangeException.ThrowIfLessThan(orientation, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(orientation, 8); + var block = new byte[26]; + var b = block.AsSpan(); + b[0] = b[1] = littleEndian ? (byte)'I' : (byte)'M'; + W16(b[2..], 42, littleEndian); + W32(b[4..], 8, littleEndian); // the first IFD + W16(b[8..], 1, littleEndian); // one entry + W16(b[10..], OrientationTag, littleEndian); + W16(b[12..], 3, littleEndian); // SHORT + W32(b[14..], 1, littleEndian); // count + W16(b[18..], (ushort)orientation, littleEndian); // the value, left-justified in the 4-byte field + // Bytes 22-25: the offset of the next IFD, 0. + return block; + } + + private static void W16(Span b, ushort value, bool little) + { + if (little) + { + BinaryPrimitives.WriteUInt16LittleEndian(b, value); + } + else + { + BinaryPrimitives.WriteUInt16BigEndian(b, value); + } + } + + private static void W32(Span b, uint value, bool little) + { + if (little) + { + BinaryPrimitives.WriteUInt32LittleEndian(b, value); + } + else + { + BinaryPrimitives.WriteUInt32BigEndian(b, value); + } + } + private static ushort U16(ReadOnlySpan b, bool little) => little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b); diff --git a/src/Febe.Core/Codecs/Images/GifDecoder.cs b/src/Febe.Core/Codecs/Images/GifDecoder.cs index f383eec..63c25cd 100644 --- a/src/Febe.Core/Codecs/Images/GifDecoder.cs +++ b/src/Febe.Core/Codecs/Images/GifDecoder.cs @@ -77,7 +77,10 @@ public static class GifDecoder CanvasHeight, Math.Max(1, FrameCount), true, - Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments }); + Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments }) + { + IsAnimated = FrameCount > 1, + }; } private static GifFile Walk(ReadOnlySpan data, ImageLimits limits, bool countFrames) diff --git a/src/Febe.Core/Codecs/Images/ImageConverter.cs b/src/Febe.Core/Codecs/Images/ImageConverter.cs index a0c7f6a..9e132d0 100644 --- a/src/Febe.Core/Codecs/Images/ImageConverter.cs +++ b/src/Febe.Core/Codecs/Images/ImageConverter.cs @@ -33,6 +33,10 @@ public sealed record ImageConversionOptions /// /// The metadata written. /// What of the source's metadata the target could not take, in Italian, for the interface. +/// +/// The same as note codes (tappa E3, ), once each, in a fixed order: what the export +/// and the library conversion record. +/// public sealed record ImageConversionResult( byte[] Data, ImageFormat Source, @@ -41,7 +45,60 @@ public sealed record ImageConversionResult( int Height, bool Lossy, ImageMetadata Metadata, - IReadOnlyList NotCarried); + IReadOnlyList NotCarried, + IReadOnlyList Losses); + +/// What a conversion does with a source (tappa E3, decisions D5 and D6). +public enum ImageConversionAction +{ + /// The source is already in the target format: it is copied byte for byte, without a note. + CopyAsIs, + + /// The source is decoded and written in the target format. + Convert, + + /// The source cannot be converted without losing what matters: it is copied as it is, with a note. + CopyOriginal, +} + +/// The outcome of . +/// What to do. +/// The format of the source by its bytes; null when it is not recognised. +/// For , why (AsIsHeif, AsIsAnimated...). +public sealed record ImageConversionCheck(ImageConversionAction Action, ImageFormat? Source, string? NoteCode); + +/// The note codes of what a conversion copies as it is or does not keep (decision D19 of tappa E3). +public static class ImageConversionLosses +{ + public const string AsIsHeif = "AsIsHeif"; + public const string AsIsAvif = "AsIsAvif"; + public const string AsIsRaw = "AsIsRaw"; + public const string AsIsAnimated = "AsIsAnimated"; + public const string AsIsNotDecodable = "AsIsNotDecodable"; + public const string AsIsDeepColor = "AsIsDeepColor"; + public const string AsIsCmyk = "AsIsCmyk"; + public const string AsIsTooLarge = "AsIsTooLarge"; + + public const string LostTexts = "LostTexts"; + public const string LostColorChunks = "LostColorChunks"; + public const string LostIcc = "LostIcc"; + public const string LostIccTooLarge = "LostIccTooLarge"; + public const string LostExifTooLarge = "LostExifTooLarge"; + public const string LostXmpTooLarge = "LostXmpTooLarge"; + public const string LostExtendedXmp = "LostExtendedXmp"; + public const string LostExifUnreadable = "LostExifUnreadable"; + public const string LostIptc = "LostIptc"; + public const string LostOtherSegments = "LostOtherSegments"; + public const string LostCommentTooLarge = "LostCommentTooLarge"; + public const string TransparencyWhite = "TransparencyWhite"; + + /// The order in which the codes are listed, so that the same source always gives the same note. + internal static readonly string[] Order = + [ + TransparencyWhite, LostExifUnreadable, LostExifTooLarge, LostIcc, LostIccTooLarge, LostXmpTooLarge, LostExtendedXmp, + LostIptc, LostTexts, LostCommentTooLarge, LostColorChunks, LostOtherSegments, + ]; +} /// /// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is @@ -57,9 +114,101 @@ public sealed record ImageConversionResult( /// public static class ImageConverter { + /// The largest source a conversion reads into memory (decision D6 of tappa E3: 512 MiB). + public const long MaxSourceBytes = 512L * 1024 * 1024; + + /// The largest picture written as WebP (decision D6 of tappa E3: about 1.1 GB of working memory). + public const long MaxWebPPixels = 40_000_000; + /// The formats a conversion can write. public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP; + /// + /// What a conversion of to does, from its bytes and its header + /// only (tappa E3, D5 and D6): the same format is copied byte for byte (a lossy WebP to WebP too); HEIF, AVIF, TIFF + /// and raw files, animations, damaged or unknown files, CMYK and deep-colour sources to PNG or WebP and pictures + /// over the pixel budget of the target are copied as they are, with the reason. Never throws for a bad file. + /// + /// The target is not JPEG, PNG or WebP. + public static ImageConversionCheck Check(ReadOnlyMemory data, ImageFormat target, ImageConversionOptions? options = null) + { + if (!CanWrite(target)) + { + throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target)); + } + + options ??= ImageConversionOptions.Default; + var source = ImageFormatSniffer.Detect(data.Span); + if (source == target) + { + return new ImageConversionCheck(ImageConversionAction.CopyAsIs, source, null); + } + + string? asIs = source switch + { + ImageFormat.Heif => ImageConversionLosses.AsIsHeif, + ImageFormat.Avif => ImageConversionLosses.AsIsAvif, + ImageFormat.Tiff => ImageConversionLosses.AsIsRaw, // TIFF and the raw formats built on it (DNG, NEF, CR2...) + ImageFormat.Unknown => ImageConversionLosses.AsIsNotDecodable, + _ => null, + }; + if (asIs is null && data.Length > MaxSourceBytes) + { + asIs = ImageConversionLosses.AsIsTooLarge; + } + + if (asIs is null) + { + asIs = IdentifyOutcome(data, target, options.Limits); + } + + return asIs is null + ? new ImageConversionCheck(ImageConversionAction.Convert, source, null) + : new ImageConversionCheck(ImageConversionAction.CopyOriginal, source == ImageFormat.Unknown ? null : source, asIs); + } + + private static string? IdentifyOutcome(ReadOnlyMemory data, ImageFormat target, ImageLimits limits) + { + ImageInfo info; + try + { + info = ImageDecoder.Identify(data, limits); + } + catch (ImageLimitException) + { + return ImageConversionLosses.AsIsTooLarge; + } + catch (ImageDecodeException) + { + return ImageConversionLosses.AsIsNotDecodable; + } + + if (info.IsAnimated) + { + return ImageConversionLosses.AsIsAnimated; + } + + if (target != ImageFormat.Jpeg && info.IsCmyk) + { + return ImageConversionLosses.AsIsCmyk; + } + + if (target != ImageFormat.Jpeg && info.BitsPerSample > 8) + { + return ImageConversionLosses.AsIsDeepColor; + } + + var pixels = (long)info.Width * info.Height; + var tooLarge = target == ImageFormat.WebP + ? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension + : pixels > ImageLimits.Default.MaxPixels; + + // What the decoder will ask besides the pixels (a progressive JPEG keeps its coefficients): a file the decoder + // would refuse is too large for the conversion, never «not readable» (§4.10). + tooLarge |= info.DecodeWorkingBytes > limits.MaxWorkingBytes; + return tooLarge ? ImageConversionLosses.AsIsTooLarge : null; + } + /// 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. @@ -85,8 +234,58 @@ public static class ImageConverter lossy = true; } - var metadata = info.Metadata; + var losses = new HashSet(StringComparer.Ordinal); + var data = EncodeCore(image, target, info.Metadata, options, notCarried, losses, out var written); + return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried, Ordered(losses)); + } + + /// + /// Writes (straight RGBA) as with what of + /// the target can carry (none when null: the frames of tappa E3). A transparent image + /// to JPEG is first flattened over the background of the options, on a copy: is never + /// changed. + /// + /// The target is not JPEG, PNG or WebP, or a WebP side is over 16384. + public static byte[] Encode(RgbaImage image, ImageFormat target, ImageMetadata? metadata, ImageConversionOptions? options = null) + { + ArgumentNullException.ThrowIfNull(image); + if (!CanWrite(target)) + { + throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target)); + } + + options ??= ImageConversionOptions.Default; + if (target == ImageFormat.Jpeg && !image.IsOpaque()) + { + using var copy = new RgbaImage(image.Width, image.Height, image.ToArray()); + return EncodeCore(copy, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet(StringComparer.Ordinal), out _); + } + + return EncodeCore(image, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet(StringComparer.Ordinal), out _); + } + + /// The codes of in the order of . + private static string[] Ordered(HashSet losses) => + [.. ImageConversionLosses.Order.Where(losses.Contains)]; + + /// Encodes; flattens in place for a JPEG target that is not opaque. + private static byte[] EncodeCore( + RgbaImage image, + ImageFormat target, + ImageMetadata metadata, + ImageConversionOptions options, + List notCarried, + HashSet losses, + out ImageMetadata written) + { var exif = metadata.Exif; + if (exif is not null && !ExifOrientation.IsTiff(exif)) + { + notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)"); + losses.Add(ImageConversionLosses.LostExifUnreadable); + exif = OrientationOnly(metadata); + } + var icc = metadata.IccProfile; var iccName = metadata.IccProfileName; if (icc is not null && IccColorSpace(icc) != "RGB ") @@ -97,6 +296,7 @@ public static class ImageConverter "GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)", _ => "il profilo colore (non descrive pixel RGB)", }); + losses.Add(ImageConversionLosses.LostIcc); icc = null; iccName = null; } @@ -104,23 +304,49 @@ public static class ImageConverter foreach (var chunk in metadata.ColorChunks) { notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)"); + losses.Add(ImageConversionLosses.LostColorChunks); + } + + foreach (var block in metadata.Unread) + { + switch (block) + { + case "APP13": + notCarried.Add("i dati IPTC (segmento APP13)"); + losses.Add(ImageConversionLosses.LostIptc); + break; + case "ExtendedXmp": + notCarried.Add("l'XMP esteso"); + losses.Add(ImageConversionLosses.LostExtendedXmp); + break; + default: + notCarried.Add($"il blocco {block}"); + losses.Add(ImageConversionLosses.LostOtherSegments); + break; + } } var xmp = metadata.Xmp; var texts = metadata.Texts; + IReadOnlyList writtenTexts = 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; + var pngTexts = PngTexts(texts, notCarried, losses); + writtenTexts = pngTexts; + data = PngEncoder.Encode(image, new PngEncoderOptions + { + Exif = exif, + IccProfile = icc, + IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName, + Xmp = xmp, + Texts = pngTexts, + }); + break; + } + case ImageFormat.WebP: if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension) { @@ -130,8 +356,10 @@ public static class ImageConverter if (texts.Count > 0) { notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)"); + losses.Add(ImageConversionLosses.LostTexts); } + writtenTexts = []; data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp }); break; default: @@ -139,25 +367,47 @@ public static class ImageConverter 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; + losses.Add(ImageConversionLosses.LostExifTooLarge); + exif = OrientationOnly(metadata); } if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29) { notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)"); + losses.Add(ImageConversionLosses.LostXmpTooLarge); xmp = null; } - var comments = new List(); - foreach (var text in texts) + if (icc is not null && (icc.Length + JpegIccChunk - 1) / JpegIccChunk > 255) { - comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}"); + notCarried.Add($"il profilo colore ({icc.Length} byte, più di quanto entra in 255 segmenti JPEG)"); + losses.Add(ImageConversionLosses.LostIccTooLarge); + icc = null; + iccName = null; } + var comments = new List(); + var kept = new List(); + foreach (var text in texts) + { + var comment = text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}"; + if (Encoding.UTF8.GetByteCount(comment) > JpegMaxSegmentPayload) + { + notCarried.Add("un commento (più lungo di quanto entra in un segmento JPEG)"); + losses.Add(ImageConversionLosses.LostCommentTooLarge); + continue; + } + + comments.Add(comment); + kept.Add(text); + } + + writtenTexts = kept; if (!image.IsOpaque()) { ImageBackground.Flatten(image, options.JpegBackground); notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)"); + losses.Add(ImageConversionLosses.TransparencyWhite); } data = JpegEncoder.Encode(image, new JpegEncoderOptions @@ -173,18 +423,28 @@ public static class ImageConverter } } - var written = new ImageMetadata + written = new ImageMetadata { Exif = exif, - Orientation = metadata.Orientation, + Orientation = exif is null ? 1 : metadata.Orientation, IccProfile = icc, IccProfileName = icc is null ? null : iccName, Xmp = xmp, - Texts = target == ImageFormat.WebP ? [] : texts, + Texts = writtenTexts, }; - return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried); + return data; } + /// + /// In place of an EXIF block left behind, the smallest one that keeps its orientation (in the source's byte order), + /// or null when the orientation is 1: the pixels are never turned (§4.10), so without the tag the picture would + /// show turned. The loss stays in the notes. + /// + private static byte[]? OrientationOnly(ImageMetadata metadata) => + metadata.Orientation is > 1 and <= 8 + ? ExifOrientation.Minimal(metadata.Orientation, metadata.Exif is not { Length: > 0 } e || e[0] != (byte)'M') + : null; + /// 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) { @@ -211,6 +471,9 @@ public static class ImageConverter /// Bytes of payload in one JPEG marker segment (65535 less the two of the length). private const int JpegMaxSegmentPayload = 65533; + /// Bytes of an ICC profile in one APP2 segment (the payload less «ICC_PROFILE\0» and the two counters). + private const int JpegIccChunk = 65519; + private static string? ValidIccName(string? name) { if (string.IsNullOrEmpty(name) || name.Length > 79) @@ -229,7 +492,7 @@ public static class ImageConverter return name.Trim().Length == name.Length ? name : null; } - private static List PngTexts(IReadOnlyList texts, List notCarried) + private static List PngTexts(IReadOnlyList texts, List notCarried, HashSet losses) { var result = new List(texts.Count); foreach (var text in texts) @@ -238,6 +501,7 @@ public static class ImageConverter if (!PngEncoder.IsValidKeyword(keyword)) { notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)"); + losses.Add(ImageConversionLosses.LostTexts); continue; } @@ -248,6 +512,7 @@ public static class ImageConverter } } + /// Composites an image over a plain colour. public static class ImageBackground { diff --git a/src/Febe.Core/Codecs/Images/ImageMetadata.cs b/src/Febe.Core/Codecs/Images/ImageMetadata.cs index 571c1a0..56e4d12 100644 --- a/src/Febe.Core/Codecs/Images/ImageMetadata.cs +++ b/src/Febe.Core/Codecs/Images/ImageMetadata.cs @@ -39,6 +39,13 @@ public sealed class ImageMetadata /// not applied to the pixels and no encoder writes them, so a conversion says they are left behind. /// public IReadOnlyList ColorChunks { get; init; } = []; + + /// + /// Blocks of the file that hold data no reader of Febe interprets and no encoder writes, in file order and once + /// each: JPEG segments («APP13» for IPTC/Photoshop, «ExtendedXmp», «APP2» for MPF, other «APPn»), PNG ancillary + /// chunks («pHYs», «tIME»...), WebP chunks. A conversion reports them as not kept. + /// + public IReadOnlyList Unread { get; init; } = []; } /// What a file says about its image, read without decoding the pixels. @@ -55,4 +62,20 @@ public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int Fr /// 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; + + /// + /// Whether the file is an animation, by the presence of its marks (spec §4.10): a PNG with an acTL chunk + /// before its image data, a WebP with an ANIM or ANMF chunk, a GIF with more than one image. + /// + public bool IsAnimated { get; init; } + + /// Whether the pixels are stored as CMYK or YCCK (a JPEG with four components). + public bool IsCmyk { get; init; } + + /// + /// The working memory a full decode asks besides the decoded image, as the decoder checks it against + /// (a progressive or lossless JPEG keeps its coefficients or samples: + /// up to 9 bytes a pixel); 0 when the format's decoder needs none worth counting before it starts. + /// + public long DecodeWorkingBytes { get; init; } } diff --git a/src/Febe.Core/Codecs/Images/JpegFile.cs b/src/Febe.Core/Codecs/Images/JpegFile.cs index a9d5698..5d4f5ee 100644 --- a/src/Febe.Core/Codecs/Images/JpegFile.cs +++ b/src/Febe.Core/Codecs/Images/JpegFile.cs @@ -76,6 +76,7 @@ internal sealed partial class JpegFile : IDisposable private string? _xmp; private List<(int Sequence, int Count, byte[] Data)>? _iccChunks; private List? _texts; + private List? _unread; private bool _allocated; private bool _pooledArrays; @@ -320,7 +321,7 @@ internal sealed partial class JpegFile : IDisposable public ImageInfo ToInfo() { var icc = AssembleIcc(); - var metadata = _exif is null && icc is null && _xmp is null && _texts is null + var metadata = _exif is null && icc is null && _xmp is null && _texts is null && _unread is null ? ImageMetadata.Empty : new ImageMetadata { @@ -329,8 +330,14 @@ internal sealed partial class JpegFile : IDisposable IccProfile = icc, Xmp = _xmp, Texts = _texts ?? [], + Unread = _unread ?? [], }; - return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision }; + return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) + { + BitsPerSample = Precision, + IsCmyk = Components.Length == 4, + DecodeWorkingBytes = Height == 0 ? 0 : WorkingBytes(Progressive, 0), + }; } public JpegCoefficients ToCoefficients() @@ -476,6 +483,34 @@ internal sealed partial class JpegFile : IDisposable private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor; + /// + /// The working memory asks of the limits: the sample planes (reduced by + /// ), the coefficients when kept (a progressive file), the samples of a lossless one. + /// + private long WorkingBytes(bool keepCoefficients, int scaleShift) + { + 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); + } + } + + return bytes; + } + + private void ReadDnl(ReadOnlySpan p) { if (p.Length < 2) @@ -625,6 +660,12 @@ internal sealed partial class JpegFile : IDisposable return; } + if (marker is not (0xE1 or 0xE2)) + { + NotRead(marker == 0xED ? "APP13" : $"APP{marker - 0xE0}"); + return; + } + // Damaged or oversized metadata is skipped: it must never stop an image from being shown. if (marker == 0xE1) { @@ -644,8 +685,16 @@ internal sealed partial class JpegFile : IDisposable _xmp = Encoding.UTF8.GetString(packet); } } + else if (p.StartsWith(ExtendedXmpNamespace)) + { + NotRead("ExtendedXmp"); + } + else if (!(p.Length > 6 && p[..4].SequenceEqual("Exif"u8)) && !p.StartsWith(XmpNamespace)) + { + NotRead("APP1"); + } } - else if (marker == 0xE2 && p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8)) + else if (p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8)) { int sequence = p[12]; int count = p[13]; @@ -655,6 +704,22 @@ internal sealed partial class JpegFile : IDisposable (_iccChunks ??= []).Add((sequence, count, chunk.ToArray())); } } + else + { + NotRead("APP2"); // MPF and the like + } + } + + /// The namespace that starts an extended XMP APP1 segment (XMP part 3), with its terminating zero. + private static ReadOnlySpan ExtendedXmpNamespace => "http://ns.adobe.com/xmp/extension/\0"u8; + + private void NotRead(string name) + { + _unread ??= []; + if (!_unread.Contains(name)) + { + _unread.Add(name); + } } /// The namespace that starts an XMP APP1 segment, with its terminating zero. @@ -801,25 +866,7 @@ internal sealed partial class JpegFile : IDisposable _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); + _limits.CheckWorkingBytes(WorkingBytes(keepCoefficients, _scaleShift)); _pooledArrays = _mode == Mode.Pixels; foreach (var c in Components) { diff --git a/src/Febe.Core/Codecs/Images/PngDecoder.cs b/src/Febe.Core/Codecs/Images/PngDecoder.cs index 2fe7f0d..f69df1f 100644 --- a/src/Febe.Core/Codecs/Images/PngDecoder.cs +++ b/src/Febe.Core/Codecs/Images/PngDecoder.cs @@ -103,6 +103,8 @@ public static class PngDecoder public string? Xmp; public List? Texts; public List? ColorChunks; + public List? Unread; + public bool Animated; public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 }; @@ -114,7 +116,7 @@ public static class PngDecoder Height, FrameCount, ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha, - Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null + Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null && Unread is null ? ImageMetadata.Empty : new ImageMetadata { @@ -125,9 +127,11 @@ public static class PngDecoder Xmp = Xmp, Texts = Texts ?? [], ColorChunks = ColorChunks ?? [], + Unread = Unread ?? [], }) { BitsPerSample = ColorType == 3 ? 8 : BitDepth, + IsAnimated = Animated, }; } @@ -248,6 +252,7 @@ public static class PngDecoder break; case "acTL": + file.Animated |= idatState == 0; if (payload.Length >= 8 && idatState == 0) { var frames = BinaryPrimitives.ReadUInt32BigEndian(payload); @@ -272,12 +277,20 @@ public static class PngDecoder break; + case "fcTL" or "fdAT": + break; + default: if (critical) { throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name})."); } + if (readMetadata && !(file.Unread ??= []).Contains(name)) + { + file.Unread.Add(name); + } + break; } } diff --git a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs index 7e67ca8..6d48ae2 100644 --- a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs +++ b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs @@ -576,7 +576,7 @@ internal static class Vp8LEncoder private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan lengths) { var bestBits = 0; - var bestCost = double.MaxValue; + var bestCost = long.MaxValue; var green = new int[256 + NumLengthCodes + (1 << 10)]; var red = new int[256]; var blue = new int[256]; @@ -637,8 +637,10 @@ internal static class Vp8LEncoder 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) + // Bits to code the counts with an ideal code, plus a rough price for describing the code, in units of + // 2^-LogFractionBits bits: Σ c·log2(total / c) = total·log2(total) − Σ c·log2(c), in integers only, so that the + // choice never depends on the floating-point library of the platform (decision D9 of tappa E3). + internal static long Entropy(ReadOnlySpan counts) { long total = 0; var used = 0; @@ -650,19 +652,66 @@ internal static class Vp8LEncoder if (used <= 1) { - return 8; + return 8L << LogFractionBits; } - var bits = 0.0; + var bits = total * Log2Fixed((ulong)total); foreach (var c in counts) { if (c > 0) { - bits -= c * Math.Log2((double)c / total); + bits -= c * Log2Fixed((ulong)c); } } - return bits + (used * 4.0); + return bits + ((long)used * 4 << LogFractionBits); + } + + /// Fractional bits of . + internal const int LogFractionBits = 16; + + /// Base-2 logarithms of 1-4095 in fixed point, computed once by . + private static readonly long[] SmallLog2 = BuildSmallLog2(); + + private static long[] BuildSmallLog2() + { + var table = new long[4096]; + for (var i = 1; i < table.Length; i++) + { + table[i] = Log2Exact((ulong)i); + } + + return table; + } + + /// log2() in fixed point with fractional bits; 0 for 0. + internal static long Log2Fixed(ulong value) => value < (ulong)SmallLog2.Length ? SmallLog2[value] : Log2Exact(value); + + /// + /// log2 by integers only: the integer part from the highest bit, the fraction bit by bit by repeated squaring of + /// the mantissa (kept as a 1.31 fixed-point number), rounded down. + /// + private static long Log2Exact(ulong value) + { + if (value == 0) + { + return 0; + } + + var high = 63 - System.Numerics.BitOperations.LeadingZeroCount(value); + ulong mantissa = high >= 31 ? value >> (high - 31) : value << (31 - high); // in [2^31, 2^32): 1.0 ≤ m < 2.0 + long fraction = 0; + for (var bit = LogFractionBits - 1; bit >= 0; bit--) + { + mantissa = (mantissa * mantissa) >> 31; + if (mantissa >= 1UL << 32) + { + mantissa >>= 1; + fraction |= 1L << bit; + } + } + + return ((long)high << LogFractionBits) | fraction; } // Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length diff --git a/src/Febe.Core/Codecs/Images/WebPDecoder.cs b/src/Febe.Core/Codecs/Images/WebPDecoder.cs index b96bdc6..fcf8ef1 100644 --- a/src/Febe.Core/Codecs/Images/WebPDecoder.cs +++ b/src/Febe.Core/Codecs/Images/WebPDecoder.cs @@ -96,6 +96,8 @@ public static class WebPDecoder public byte[]? Exif; public byte[]? Icc; public string? Xmp; + public bool Animated; + public List? Unread; public ImageInfo ToInfo() => new( ImageFormat.WebP, @@ -103,9 +105,12 @@ public static class WebPDecoder Height, FrameCount, HasAlpha, - Exif is null && Icc is null && Xmp is null + Exif is null && Icc is null && Xmp is null && Unread is null ? ImageMetadata.Empty - : new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp }); + : new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp, Unread = Unread ?? [] }) + { + IsAnimated = Animated, + }; } private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata) @@ -174,7 +179,11 @@ public static class WebPDecoder var chunk = chunks[i]; switch (chunk.Type) { + case Anim: + file.Animated = true; + break; case Anmf: + file.Animated = true; if (frames++ == 0) { file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height); @@ -200,6 +209,25 @@ public static class WebPDecoder 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; + case Iccp or Exif or Xmp: + break; + default: + if (readMetadata) + { + var name = string.Create(4, chunk.Type, static (c, t) => + { + for (var k = 0; k < 4; k++) + { + c[k] = (char)(byte)(t >> (8 * k)); + } + }).TrimEnd(); + if (!(file.Unread ??= []).Contains(name)) + { + file.Unread.Add(name); + } + } + break; } } diff --git a/src/Febe.Core/Export/ExportConversion.cs b/src/Febe.Core/Export/ExportConversion.cs new file mode 100644 index 0000000..92c1f11 --- /dev/null +++ b/src/Febe.Core/Export/ExportConversion.cs @@ -0,0 +1,87 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; + +namespace Febe.Core.Export; + +/// +/// The conversion of a library file for a copy (tappa E3, WP1.6b): with the files of the +/// export environment, and the hash of content that is only known once written (a remux). +/// +internal static class ExportConversion +{ + /// Prepares the library file at in (never Original). + /// A photo's bytes are not those of . + public static Task PrepareAsync(ExportEnvironment env, string source, Media media, ExportFormat target, string sha256, CancellationToken ct) => + MediaConverter.PrepareAsync(() => env.FileSystem.OpenRandomAccess(source), media.RelativePath!, media.Kind, target, sha256, env.Throttle, ct); + + /// The SHA-256 (lowercase hex) and length of what writes, written nowhere. + public static async Task<(string Sha256, long Length)> HashAsync(Func produce, CancellationToken ct) + { + await using var sink = new HashingSink(); + await produce(sink, ct).ConfigureAwait(false); + return (sink.Finish(), sink.Length); + } + + /// A stream that only hashes and counts what is written to it. + private sealed class HashingSink : Stream + { + private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + private long length; + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => length; + + public override long Position + { + get => length; + set => throw new NotSupportedException(); + } + + public string Finish() => Convert.ToHexStringLower(hash.GetHashAndReset()); + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + hash.AppendData(buffer); + length += buffer.Length; + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + Write(buffer.Span); + return ValueTask.CompletedTask; + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override void Flush() + { + } + + 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 (disposing) + { + hash.Dispose(); + } + + base.Dispose(disposing); + } + } +} diff --git a/src/Febe.Core/Export/ExportConversions.cs b/src/Febe.Core/Export/ExportConversions.cs new file mode 100644 index 0000000..ffdef0c --- /dev/null +++ b/src/Febe.Core/Export/ExportConversions.cs @@ -0,0 +1,99 @@ +using Febe.Core.Domain; +using Febe.Core.Library.Conversion; + +namespace Febe.Core.Export; + +/// What the plan expects of a file in a format, from its name only (tappa E3: the copy decides on the bytes). +public enum ExportPrediction +{ + /// Copied byte for byte: Original, or already in the format asked. + Whole, + + /// Converted into the format asked. + Converted, + + /// Copied as it is with a note (HEIC, AVIF, raw, GIF, WebM). + AsIs, +} + +/// +/// The format of a copy (spec §4.10 «Conversione del formato», decisions D1, D2 and D5-D7 of tappa E3): which format a +/// file gets in a destination, and what the plan predicts of it from its name. +/// +public static class ExportConversions +{ + /// + /// The format of a file of : the «Copia in…» override of this request, else the destination's, + /// else the general settings' (D1). A value that does not belong to the kind counts as not set. + /// + public static ExportFormat Resolve(MediaKind kind, ExportFormatChoice? request, ExportDestination destination, ExportSettings settings) + { + ArgumentNullException.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(settings); + Func fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat : ExportFormats.IsVideoFormat; + var chosen = kind == MediaKind.Photo + ? new[] { request?.Photo, destination.PhotoFormat, settings.PhotoFormat } + : [request?.Video, destination.VideoFormat, settings.VideoFormat]; + foreach (var format in chosen) + { + if (format is { } f && fits(f)) + { + return f; + } + } + + return ExportFormat.Original; + } + + /// The variant a format asks for: Whole for Original, Converted otherwise. + public static ExportVariant VariantOf(ExportFormat format) => format == ExportFormat.Original ? ExportVariant.Whole : ExportVariant.Converted; + + /// + /// What the plan expects, by extension («circa»): Original, or the same format (.jpg/.jpeg, .png, + /// .webp, .mp4) → Whole; HEIC, HEIF, AVIF, raw, GIF and WebM → AsIs; anything else → Converted. + /// + public static ExportPrediction Predict(string relativePath, MediaKind kind, ExportFormat target) + { + ArgumentNullException.ThrowIfNull(relativePath); + if (target == ExportFormat.Original) + { + return ExportPrediction.Whole; + } + + var extension = Path.GetExtension(relativePath).ToLowerInvariant(); + var same = target switch + { + ExportFormat.Jpg => extension is ".jpg" or ".jpeg", + ExportFormat.Png => extension == ".png", + ExportFormat.WebpLossless => extension == ".webp", + ExportFormat.Mp4 => extension == ".mp4", + _ => false, + }; + if (same) + { + return ExportPrediction.Whole; + } + + return AsIsLabel(relativePath) is not null ? ExportPrediction.AsIs : ExportPrediction.Converted; + } + + /// The kind of a file copied as it is, for «3 HEIC copiati come sono»: «HEIC», «AVIF», «raw», «GIF», «WebM»; null otherwise. + public static string? AsIsLabel(string relativePath) + { + ArgumentNullException.ThrowIfNull(relativePath); + var extension = Path.GetExtension(relativePath).ToLowerInvariant(); + return extension switch + { + ".heic" or ".heif" => "HEIC", + ".avif" => "AVIF", + ".gif" => "GIF", + ".webm" => "WebM", + _ when MediaConverter.IsRawExtension(extension) => "raw", + _ => null, + }; + } + + /// The effective identity the plan expects (D2): (Converted, format) when predicted converted, else (Whole, Original). + public static (ExportVariant Variant, ExportFormat Format) PredictedIdentity(string relativePath, MediaKind kind, ExportFormat target) => + Predict(relativePath, kind, target) == ExportPrediction.Converted ? (ExportVariant.Converted, target) : (ExportVariant.Whole, ExportFormat.Original); +} diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs index 0084b56..5099b4e 100644 --- a/src/Febe.Core/Export/ExportCopier.cs +++ b/src/Febe.Core/Export/ExportCopier.cs @@ -1,5 +1,8 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; using Febe.Core.Domain; using Febe.Core.Library; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -18,6 +21,9 @@ namespace Febe.Core.Export; /// nothing is copied during an engine session: the job waits; /// resumable: every file has its state, and the target path is recorded before its .part exists. /// +/// Tappa E3: a file is converted (before the space check) into the format its item asks, or copied as it is with a +/// note; a file already copied in any form but a frame is «già copiato» (D3); the frames of a video are taken in one +/// batch, each one with its exact instant as identity (D4, D12). /// public sealed class ExportCopier(ExportEnvironment env) { @@ -66,6 +72,8 @@ public sealed class ExportCopier(ExportEnvironment env) x.SetFileTime = library.SetFileTimeToPublication; x.OneOnly = settings.SamePost == SamePostCopies.OneOnly; x.CopyAgain = await ExportRunSettings.GetCopyAgainAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); + x.Frames = await ExportRunSettings.GetFramesAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); + x.Exact = await ExportRunSettings.GetExactAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); x.Effective = await new ExportDestinations(_env).ResolveAllAsync(ct).ConfigureAwait(false); var summary = await store.GetRunSummaryAsync(runId, ct).ConfigureAwait(false); x.FilesTotal = summary.Total; @@ -73,47 +81,41 @@ public sealed class ExportCopier(ExportEnvironment env) x.ByState = new Dictionary(summary.ByState); x.BytesTotal = await PendingBytesAsync(runId, ct).ConfigureAwait(false); - var groupFiles = 0; - long groupBytes = 0; - long after = 0; - while (true) + var pending = new PendingItems(store, runId); + while (await pending.PeekAsync(ct).ConfigureAwait(false) is { } item) { - var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); - if (page.Count == 0) + ct.ThrowIfCancellationRequested(); + if (item.Variant == ExportVariant.Frame) { - break; + // The following frames of the same video and format are one batch, also across pages (WP1.7). + var batch = new List { pending.Take() }; + while (await pending.PeekAsync(ct).ConfigureAwait(false) is { Variant: ExportVariant.Frame } next + && next.MediaId == item.MediaId && next.Format == item.Format) + { + batch.Add(pending.Take()); + } + + if (await ProcessFrameBatchAsync(x, batch, ct).ConfigureAwait(false) is { } paused) + { + return await PauseAsync(x, paused).ConfigureAwait(false); + } + + continue; } - after = page[^1].Id; - foreach (var item in page) + pending.Take(); + if (await BeforeItemAsync(x, ct).ConfigureAwait(false) is { } problem) { - ct.ThrowIfCancellationRequested(); - if (groupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) - { - return await PauseAsync(x, problem).ConfigureAwait(false); - } - - await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false); - var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false); - if (result.Pause is { } pause) - { - return await PauseAsync(x, pause).ConfigureAwait(false); - } - - x.FilesDone++; - x.BytesDone += result.Bytes; - x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1); - x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1; - groupFiles++; - groupBytes += result.Bytes; - if (groupFiles >= Math.Max(1, _env.GroupFiles) || groupBytes >= _env.GroupBytes) - { - groupFiles = 0; - groupBytes = 0; - } - - x.Report(_env, ExportPhase.Copying, result.Path); + return await PauseAsync(x, problem).ConfigureAwait(false); } + + var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false); + if (result.Pause is { } pause) + { + return await PauseAsync(x, pause).ConfigureAwait(false); + } + + Account(x, result); } var final = await store.GetRunSummaryAsync(runId, none).ConfigureAwait(false); @@ -176,6 +178,36 @@ public sealed class ExportCopier(ExportEnvironment env) return problem; } + /// Before a file: the probe at the start of each group, then the wait for the end of an engine session. + private async Task BeforeItemAsync(RunContext x, CancellationToken ct) + { + if (x.GroupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return problem; + } + + await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false); + return null; + } + + /// The counts of one finished item: progress, states, and the group of the probe. + private void Account(RunContext x, ItemResult result) + { + x.FilesDone++; + x.BytesDone += result.Bytes; + x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1); + x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1; + x.GroupFiles++; + x.GroupBytes += result.Written ?? result.Bytes; + if (x.GroupFiles >= Math.Max(1, _env.GroupFiles) || x.GroupBytes >= _env.GroupBytes) + { + x.GroupFiles = 0; + x.GroupBytes = 0; + } + + x.Report(_env, ExportPhase.Copying, result.Path); + } + private async Task PauseAsync(RunContext x, string message) { x.Destination = await ExportPause.PauseAsync(_env, x.Destination, message).ConfigureAwait(false); @@ -194,6 +226,7 @@ public sealed class ExportCopier(ExportEnvironment env) } } + /// The library bytes of the pending files (frames count nothing: their size is not known before). private async Task PendingBytesAsync(long runId, CancellationToken ct) { long total = 0; @@ -209,7 +242,7 @@ public sealed class ExportCopier(ExportEnvironment env) after = page[^1].Id; foreach (var item in page) { - if (item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes }) + if (item.Variant != ExportVariant.Frame && item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes }) { total += bytes; } @@ -217,18 +250,17 @@ public sealed class ExportCopier(ExportEnvironment env) } } - private async Task ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct) + /// + /// a. The library file of an item, as the job may use it now: present, of its account, still going to this + /// destination (decisions D2, D3 of tappa E2: «Esporta questo account» off skips every copy). Otherwise the state + /// and note the item ends with. + /// + private async Task SourceAsync(RunContext x, ExportItem item, CancellationToken ct) { var storage = _env.Storage; - var exports = storage.Exports; - var none = CancellationToken.None; - var destination = x.Destination; - var root = destination.RootPath; - - // a. No longer in the library. if (item.AccountId is not { } accountId || await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is not { } account) { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.AccountRemoved, LastError = null }, 0, null).ConfigureAwait(false); + return new SourceCheck(null, ExportItemState.Skipped, ExportText.Notes.AccountRemoved, 0); } var media = item.MediaId is { } mediaId ? await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) : null; @@ -238,138 +270,577 @@ public sealed class ExportCopier(ExportEnvironment env) : null; if (source is null || media is null || entry is null) { - return await FinishAsync(item with { State = ExportItemState.Missing, Note = ExportText.Notes.SourceMissing, LastError = null }, 0, null).ConfigureAwait(false); + return new SourceCheck(null, ExportItemState.Missing, ExportText.Notes.SourceMissing, 0); } - // The account may have been switched off, or got another folder, or the destination stopped taking this type - // since the job was planned (decisions D2, D3 of tappa E2): «Esporta questo account» off skips every copy. var (title, inHighlight) = await HighlightAsync(entry, ct).ConfigureAwait(false); - if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != destination.Id + if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != x.Destination.Id || !effective.Wants(ExportPaths.TypeOf(entry.Kind, media.Kind, inHighlight))) { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.NotExported, LastError = null }, media.Bytes ?? 0, null).ConfigureAwait(false); + return new SourceCheck(null, ExportItemState.Skipped, ExportText.Notes.NotExported, item.Variant == ExportVariant.Frame ? 0 : media.Bytes ?? 0); + } + + var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0; + return new SourceCheck(new LibraryFile(account, entry, media, source, media.Sha256!, bytes, title, inHighlight), ExportItemState.Pending, null, bytes); + } + + private async Task ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + + var check = await SourceAsync(x, item, ct).ConfigureAwait(false); + if (check.File is not { } library) + { + return await FinishAsync(item with { State = check.State, Note = check.Note, LastError = null }, check.Bytes, null).ConfigureAwait(false); } // b. The file may have changed since the job was planned. - var sha = media.Sha256!; + var sha = library.Sha256; if (!string.Equals(item.SourceSha256, sha, StringComparison.Ordinal)) { item = item with { SourceSha256 = sha }; } - var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0; - var identity = new ExportCopyIdentity(destination.Id, accountId, sha, ExportVariant.Whole, ExportFormat.Original, null); - var file = new FileContext(account, entry, media, source, sha, bytes, identity, title, inHighlight); + // The form asked (D2): the effective one is known once the file is prepared; until then the plan's prediction. + var target = item.Variant == ExportVariant.Whole ? ExportFormat.Original : item.Format; + var predicted = x.Exact ? (item.Variant, item.Format) : ExportConversions.PredictedIdentity(library.Media.RelativePath!, library.Media.Kind, target); + var file = new FileContext(library, new ExportCopyIdentity(destination.Id, library.Account.Id, sha, predicted.Item1, predicted.Item2, null)); // c. Already copied, removed, superseded, copied for another account, or failed before. - var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false); - ExportCopy? failed = null; - if (current is { State: ExportCopyState.Copied }) + var done = x.Exact + ? await ExactLookupAsync(x, item, file, ct).ConfigureAwait(false) + : await AnyFormLookupAsync(x, item, file, predicted, ct).ConfigureAwait(false); + if (done is not null) { - if (current.RelativePath is { } copied && Exists(root, copied)) - { - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = copied, Note = null, LastError = null }, bytes, copied).ConfigureAwait(false); - } - - // The file is not there: «Tolto», unless the whole destination went away meanwhile. A root that was away - // for a moment and answers the probe again is asked once more for the file before it is called «Tolto». - if (!Directory.Exists(root)) - { - if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone) - { - return ItemResult.Paused(gone); - } - - if (current.RelativePath is { } back && Exists(root, back)) - { - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = back, Note = null, LastError = null }, bytes, back).ConfigureAwait(false); - } - } - - await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); - if (!x.CopyAgain) - { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, bytes, current.RelativePath).ConfigureAwait(false); - } - } - else if (current is { State: ExportCopyState.Failed }) - { - failed = current; - } - else if (!x.CopyAgain) - { - var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false); - if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) - { - var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, bytes, latest.RelativePath).ConfigureAwait(false); - } - - if (await exports.FindReplacedCopyAsync(destination.Id, accountId, sha, ct).ConfigureAwait(false) is { } replaced) - { - return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, bytes, replaced.RelativePath).ConfigureAwait(false); - } + return done; } if (x.OneOnly - && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, accountId, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere - && await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where + && await exports.FindCopiedElsewhereAsync(sha, library.Account.Id, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere + && await x.DestinationAsync(_env.Storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where && Exists(where.RootPath, elsewherePath)) { return await FinishAsync( item with { State = ExportItemState.AlreadyCopied, Note = ExportText.Notes.CopiedForAnotherAccount, CopyId = elsewhere.Id, LastError = null }, - bytes, + library.Bytes, null).ConfigureAwait(false); } - return await WriteAsync(x, item, file, failed, ct).ConfigureAwait(false); + // d. The conversion, before the space check (D17): its length is what the destination gets. + MediaConversionResult? conversion = null; + Output output; + if (target == ExportFormat.Original) + { + output = Output.Whole(library, []); + } + else + { + try + { + conversion = await ExportConversion.PrepareAsync(_env, library.Source, library.Media, target, sha, ct).ConfigureAwait(false); + } + catch (ContentChangedException ex) + { + return await FailUnpreparedAsync(item, file, ex.Message, ExportText.Notes.SourceChanged).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return await FailUnpreparedAsync(item, file, ExportText.ErrorText(ex), null).ConfigureAwait(false); + } + + output = conversion.Variant == ExportVariant.Whole + ? Output.Whole(library, conversion.Notes) + : new Output(conversion.Variant, conversion.Format, null, conversion.Extension, null, conversion.Length, conversion.Sha256, conversion.Produce, conversion.Notes); + } + + using (conversion) + { + var effective = file.Identity with { Variant = output.Variant, Format = output.Format }; + file = file with { Identity = effective }; + ExportCopy? failed = null; + var current = await exports.FindCurrentCopyAsync(effective, ct).ConfigureAwait(false); + if (current is { State: ExportCopyState.Copied }) + { + // Another form was asked and the bytes gave this one (an «Exact» of a form that is now copied as it is). + var (present, gone) = await PresentCopyAsync(x, [current], ct).ConfigureAwait(false); + if (gone is not null) + { + return ItemResult.Paused(gone); + } + + if (present is not null) + { + await exports.ClearFailedAsync(destination.Id, library.Account.Id, sha, effective, none).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, library.Bytes, present.RelativePath).ConfigureAwait(false); + } + + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + if (!x.CopyAgain) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, library.Bytes, current.RelativePath).ConfigureAwait(false); + } + } + else if (current is { State: ExportCopyState.Failed }) + { + failed = current; + } + + var result = await WriteAsync(x, item, file, output, failed, ct).ConfigureAwait(false); + if (result.State is ExportItemState.Copied or ExportItemState.Adopted or ExportItemState.AlreadyCopied && result.Pause is null) + { + // A copy of the file is there now: the «Non riuscito» rows of its other forms have no file and no use. + await exports.ClearFailedAsync(destination.Id, library.Account.Id, sha, effective, none).ConfigureAwait(false); + } + + return result; + } } - /// d. and e.: the path, the limits of the disk, adoption, the safe write and its record. - private async Task WriteAsync(RunContext x, ExportItem item, FileContext file, ExportCopy? failed, CancellationToken ct) + /// + /// «Già copiato» in any form but a frame (D3 of tappa E3, the rule of the plan and of the «Copie» filter): a Copied + /// copy whose file is there ends the item; copies whose file is gone become «Tolto» (after the root answered); a + /// «Non riuscito» copy is tried again; otherwise the newest copy «Tolto» or «Superato», or a copy superseded by this + /// file, skips it unless «Copia di nuovo» was asked. Null: the file is to be written. + /// + private async Task AnyFormLookupAsync(RunContext x, ExportItem item, FileContext file, (ExportVariant Variant, ExportFormat Format) predicted, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + var library = file.Library; + var current = await exports.ListCurrentCopiesAnyFormAsync(destination.Id, library.Account.Id, library.Sha256, ct).ConfigureAwait(false); + var copied = current.Where(c => c.State == ExportCopyState.Copied).ToList(); + if (copied.Count > 0) + { + var (present, gone) = await PresentCopyAsync(x, copied, ct).ConfigureAwait(false); + if (gone is not null) + { + return ItemResult.Paused(gone); + } + + if (present is not null) + { + var note = present.Variant == predicted.Variant && present.Format == predicted.Format ? null : ExportText.Notes.CopiedInAnotherFormat; + if (present.Identity is { } kept) + { + await exports.ClearFailedAsync(destination.Id, library.Account.Id, library.Sha256, kept, none).ConfigureAwait(false); + } + + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = note, LastError = null }, library.Bytes, present.RelativePath).ConfigureAwait(false); + } + + foreach (var copy in copied) + { + await exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + } + + return x.CopyAgain + ? null + : await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = copied[0].Id, LastError = null }, library.Bytes, copied[0].RelativePath).ConfigureAwait(false); + } + + if (current.Count > 0 || x.CopyAgain) + { + return null; // a «Non riuscito» copy is tried again; «Copia di nuovo» writes the current form + } + + var latest = await exports.FindLatestCopyAnyFormAsync(destination.Id, library.Account.Id, library.Sha256, ct).ConfigureAwait(false); + if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) + { + var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, library.Bytes, latest.RelativePath).ConfigureAwait(false); + } + + if (await exports.FindReplacedCopyAsync(destination.Id, library.Account.Id, library.Sha256, ct).ConfigureAwait(false) is { } replaced) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, library.Bytes, replaced.RelativePath).ConfigureAwait(false); + } + + return null; + } + + /// «Copia di nuovo» of one copy row (D11 of tappa E3): the rules of tappa E2 on its exact identity only. + private async Task ExactLookupAsync(RunContext x, ExportItem item, FileContext file, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var library = file.Library; + var current = await exports.FindCurrentCopyAsync(file.Identity, ct).ConfigureAwait(false); + if (current is { State: ExportCopyState.Copied }) + { + var (present, gone) = await PresentCopyAsync(x, [current], ct).ConfigureAwait(false); + if (gone is not null) + { + return ItemResult.Paused(gone); + } + + if (present is not null) + { + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, library.Bytes, present.RelativePath).ConfigureAwait(false); + } + + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + return x.CopyAgain + ? null + : await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, library.Bytes, current.RelativePath).ConfigureAwait(false); + } + + if (current is not null || x.CopyAgain) + { + return null; + } + + var latest = await exports.FindLatestCopyAsync(file.Identity, ct).ConfigureAwait(false); + if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) + { + var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, library.Bytes, latest.RelativePath).ConfigureAwait(false); + } + + if (await exports.FindReplacedCopyAsync(file.Identity.DestinationId, library.Account.Id, library.Sha256, ct).ConfigureAwait(false) is { } replaced) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, library.Bytes, replaced.RelativePath).ConfigureAwait(false); + } + + return null; + } + + /// + /// The first of whose file is in the destination. When none is, and the root itself is + /// away, the destination is probed: a root that answers again is asked once more for the files (a file is «Tolto» + /// only when the destination is there); one that does not answer gives the reason of the pause. + /// + private async Task<(ExportCopy? Present, string? Pause)> PresentCopyAsync(RunContext x, IReadOnlyList copies, CancellationToken ct) + { + var root = x.Destination.RootPath; + foreach (var copy in copies) + { + if (copy.RelativePath is { } path && Exists(root, path)) + { + return (copy, null); + } + } + + if (Directory.Exists(root)) + { + return (null, null); + } + + if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone) + { + return (null, gone); + } + + return (copies.FirstOrDefault(c => c.RelativePath is { } back && Exists(root, back)), null); + } + + /// The file could not be prepared: the item fails, recorded under the form the plan expected. + private async Task FailUnpreparedAsync(ExportItem item, FileContext file, string error, string? note) + { + var current = await _env.Storage.Exports.FindCurrentCopyAsync(file.Identity, CancellationToken.None).ConfigureAwait(false); + return current is { State: ExportCopyState.Copied } + ? await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error }, file.Library.Bytes, item.RelativePath).ConfigureAwait(false) + : await FailAsync(item, file, current, error, note).ConfigureAwait(false); + } + + /// + /// The frames of one video in one format (D12 of tappa E3): the video is opened once, each frame's exact instant is + /// found, a frame already copied at that instant is «Già copiato» (one copy per sample in the batch), the others are + /// decoded in decoding order and written one at a time. A pause leaves the rest of the batch pending. Returns the + /// reason of a pause, or null. + /// + private async Task ProcessFrameBatchAsync(RunContext x, List batch, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + if (await BeforeItemAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return problem; + } + + async Task EndAllAsync(IEnumerable items, ExportItemState state, string? note, string? error) + { + foreach (var item in items) + { + Account(x, await FinishAsync(item with { State = state, Note = note, LastError = error }, 0, null).ConfigureAwait(false)); + } + } + + var check = await SourceAsync(x, batch[0], ct).ConfigureAwait(false); + if (check.File is not { } library) + { + await EndAllAsync(batch, check.State, check.Note, null).ConfigureAwait(false); + return null; + } + + var sha = library.Sha256; + batch = batch.Select(i => string.Equals(i.SourceSha256, sha, StringComparison.Ordinal) ? i : i with { SourceSha256 = sha }).ToList(); + var format = batch[0].Format; + var (mode, count) = x.Frames ?? (FrameMode.At, 1); + var firstId = mode == FrameMode.Count + ? await exports.FirstItemIdAsync(x.Run.Id, library.Media.Id, ExportVariant.Frame, format, ct).ConfigureAwait(false) ?? batch[0].Id + : 0; + + Stream stream; + try + { + // The frames are of the file recorded: hashed once before they are taken (WP1.6b). + if (!string.Equals(await _env.FileSystem.ComputeSha256Async(library.Source, ct).ConfigureAwait(false), sha, StringComparison.Ordinal)) + { + await EndAllAsync(batch, ExportItemState.Failed, ExportText.Notes.SourceChanged, SourceChangedText).ConfigureAwait(false); + return null; + } + + stream = _env.FileSystem.OpenRandomAccess(library.Source); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + await EndAllAsync(batch, ExportItemState.Failed, null, ExportText.ErrorText(ex)).ConfigureAwait(false); + return null; + } + + await using (stream.ConfigureAwait(false)) + { + var knownLength = library.Media.Duration; + var (reader, info, length) = await Task.Run( + () => + { + // «N in tutto» names a frame by its position among the N instants, from the length the job used + // (the library's, or the one read from the file when the library has none: ExportService). + var probed = knownLength; + if (mode == FrameMode.Count && probed is null) + { + probed = VideoFrameReader.ProbeDuration(stream); + stream.Position = 0; + } + + var opened = VideoFrameReader.Open(stream, out var found); + return (opened, found, probed); + }, + ct).ConfigureAwait(false); + IReadOnlyList spread = mode == FrameMode.Count && length is { } d && d > TimeSpan.Zero && count is >= 1 and <= ExportFrames.MaxCount + ? ExportFrames.Spread(d, count) + : []; + using (reader) + { + var targets = info.Available ? reader.Locate([.. batch.Select(i => i.FrameAt ?? TimeSpan.Zero)]) : []; + if (targets.Count != batch.Count) + { + await EndAllAsync(batch, ExportItemState.Skipped, ExportText.Notes.FrameNotAvailable, null).ConfigureAwait(false); + return null; + } + + // The exact identity of each frame; frames on one sample follow the first of them (one copy). + var plans = new FramePlan?[batch.Count]; + var leaderOf = new Dictionary(); + var followers = new Dictionary>(); + var toWrite = new List(); + for (var k = 0; k < batch.Count; k++) + { + var target = targets[k]; + if (leaderOf.TryGetValue(target.Sample, out var leader)) + { + followers[leader].Add(k); + continue; + } + + leaderOf[target.Sample] = k; + followers[k] = []; + var at = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual)); + var identity = new ExportCopyIdentity(destination.Id, library.Account.Id, sha, ExportVariant.Frame, format, at); + // The position among the N instants (two on one millisecond are one item: ids skip nothing then); + // by the ids only when the instant is not one of them (the library's length changed meanwhile). + var index = mode == FrameMode.Count + ? ExportFrames.IndexOf(spread, batch[k].FrameAt ?? TimeSpan.Zero) ?? (int)Math.Clamp(batch[k].Id - firstId, 0, int.MaxValue) + : k; + var plan = new FramePlan(identity, ExportFrames.Suffix(mode, target.Actual, index, count), null); + var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false); + if (current is { State: ExportCopyState.Copied }) + { + var (present, gone) = await PresentCopyAsync(x, [current], ct).ConfigureAwait(false); + if (gone is not null) + { + return gone; // nothing of the batch was finished yet + } + + if (present is not null) + { + plans[k] = plan with { Present = present }; + continue; + } + + // A frame asked again is written again (D14): its old row says «Tolto». + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + } + else if (current is { State: ExportCopyState.Failed }) + { + plan = plan with { Failed = current }; + } + + plans[k] = plan; + toWrite.Add(k); + } + + async Task EndFollowersAsync(int leader, ExportItem done) + { + foreach (var k in followers[leader]) + { + var follower = done.State is ExportItemState.Copied or ExportItemState.Adopted or ExportItemState.AlreadyCopied && done.CopyId is not null + ? batch[k] with { State = ExportItemState.AlreadyCopied, CopyId = done.CopyId, RelativePath = done.RelativePath, Note = null, LastError = null } + : batch[k] with { State = done.State, Note = done.Note, LastError = done.LastError }; + Account(x, await FinishAsync(follower, 0, follower.RelativePath).ConfigureAwait(false)); + } + } + + for (var k = 0; k < batch.Count; k++) + { + if (plans[k]?.Present is { } present) + { + var done = await FinishAsync(batch[k] with { State = ExportItemState.AlreadyCopied, CopyId = present.Id, RelativePath = present.RelativePath, Note = null, LastError = null }, 0, present.RelativePath).ConfigureAwait(false); + Account(x, done); + await EndFollowersAsync(k, done.Item!).ConfigureAwait(false); + } + } + + var written = new HashSet(); + var fresh = true; + using (var frames = reader.Decode([.. toWrite.Select(k => targets[k])], ct).GetEnumerator()) + { + while (await Task.Run(frames.MoveNext, ct).ConfigureAwait(false)) + { + using var frame = frames.Current; + var k = frame.Index; + if (!fresh && await BeforeItemAsync(x, ct).ConfigureAwait(false) is { } paused) + { + return paused; + } + + fresh = false; + written.Add(k); + var result = await WriteFrameAsync(x, batch[k], library, plans[k]!, frame, ct).ConfigureAwait(false); + if (result.Pause is { } pause) + { + return pause; + } + + Account(x, result); + await EndFollowersAsync(k, result.Item!).ConfigureAwait(false); + } + } + + // A sample that gave no picture (a damaged stream): no copy row. + foreach (var k in toWrite.Where(k => !written.Contains(k))) + { + var done = await FinishAsync(batch[k] with { State = ExportItemState.Skipped, Note = ExportText.Notes.FrameNotAvailable, LastError = null }, 0, null).ConfigureAwait(false); + Account(x, done); + await EndFollowersAsync(k, done.Item!).ConfigureAwait(false); + } + } + } + + return null; + } + + /// One frame: encoded without metadata (D12 of tappa E3) under the conversion throttle, then written as any copy. + private async Task WriteFrameAsync(RunContext x, ExportItem item, LibraryFile library, FramePlan plan, VideoFrame frame, CancellationToken ct) + { + var format = plan.Identity.Format; + var file = new FileContext(library with { Bytes = 0 }, plan.Identity); + byte[] data; + try + { + var image = MediaConverter.ImageFormatOf(format)!.Value; + data = await _env.Throttle.RunAsync(_ => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is ImageDecodeException or ArgumentException) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.FrameNotAvailable, LastError = null }, 0, null).ConfigureAwait(false); + } + + var output = new Output( + ExportVariant.Frame, + format, + plan.Identity.FrameAt, + MediaConverter.ExtensionOf(format), + plan.Suffix, + data.Length, + Convert.ToHexStringLower(SHA256.HashData(data)), + (stream, token) => stream.WriteAsync(data, token).AsTask(), + []); + return await WriteAsync(x, item, file, output, plan.Failed, ct).ConfigureAwait(false); + } + + /// + /// e.: the path, the limits of the disk, adoption, the safe write and its record, for any output: the library file + /// byte for byte, a converted file, a frame. + /// + private async Task WriteAsync(RunContext x, ExportItem item, FileContext file, Output output, ExportCopy? failed, CancellationToken ct) { var exports = _env.Storage.Exports; var none = CancellationToken.None; var destination = x.Destination; var root = destination.RootPath; + var library = file.Library; string planned; try { + var name = output.Extension is null && output.Suffix is null ? null : new ExportNameOptions(output.Extension, output.Suffix); planned = ExportPaths.RelativePathFor( destination, - ExportPaths.Segments(destination, x.Naming!, file.Account, file.Entry, file.Media, file.HighlightTitle, file.InHighlight, _env.Clock.LocalZone), - MaxPath); + ExportPaths.Segments(destination, x.Naming!, library.Account, library.Entry, library.Media, library.HighlightTitle, library.InHighlight, _env.Clock.LocalZone, name), + MaxPath, + output.Suffix); } catch (PathTooLongException ex) { return await FailAsync(item, file, failed, ex.Message, null).ConfigureAwait(false); } - if (_env.Disk.MaxFileBytes(root) is { } max && file.Bytes > max) + if (_env.Disk.MaxFileBytes(root) is { } max && output.Length > max) { - return await FailAsync(item, file, failed, ExportText.TooLarge(file.Bytes), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false); + return await FailAsync(item, file, failed, ExportText.TooLarge(output.Length), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false); } - if (_env.Disk.FreeBytes(root) is { } free && free < file.Bytes + ExportSpace.Margin) + if (_env.Disk.FreeBytes(root) is { } free && free < output.Length + ExportSpace.Margin) { - return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), file.Bytes)); + return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), output.Length)); } - // Adoption by path: the planned file, and after a crash the name it was given («nome (2).jpg», …). - foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath)) + // Adoption by path (D10 of tappa E3): the planned file, and after a crash the name it was given («nome (2).jpg», + // …), when its length and then its SHA-256 are those of this output. Never by size alone. + string? expected = output.Sha256; + foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath, output.Suffix)) { var full = LibraryLayout.FullPath(root, candidate); - if (_env.FileSystem.FileLength(full) != file.Bytes - || !string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), file.Sha256, StringComparison.Ordinal)) + if (_env.FileSystem.FileLength(full) != output.Length) + { + continue; + } + + if (expected is null) + { + // A remux: its bytes are known once written, so they are written nowhere first (the length matched). + var (hash, length) = await ExportConversion.HashAsync(output.Produce!, ct).ConfigureAwait(false); + if (length != output.Length) + { + break; + } + + expected = hash; + } + + if (!string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), expected, StringComparison.Ordinal)) { continue; } var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false); - if (holder is null || (holder.AccountId is null && string.Equals(holder.SourceSha256, file.Sha256, StringComparison.Ordinal))) + if (holder is null || (holder.AccountId is null && SameForm(holder, file, expected))) { - return await RecordAsync(item, file, failed, holder, candidate, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false); + return await RecordAsync(item, file, failed, holder, candidate, output.Length, expected, ExportCopyOrigin.Adopted, Notes(output, null)).ConfigureAwait(false); } if (holder.Identity == file.Identity) @@ -378,10 +849,10 @@ public sealed class ExportCopier(ExportEnvironment env) { // Our own bytes, recorded as superseded (the file came back to the library without the change that // would have revived the row): the copy is copied, not superseded, and must not stay stuck. - return await ReviveAsync(item, file, failed, holder, candidate).ConfigureAwait(false); + return await ReviveAsync(item, file, failed, holder, candidate, output, expected).ConfigureAwait(false); } - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Bytes, candidate).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, library.Bytes, candidate).ConfigureAwait(false); } // The same bytes, recorded for another copy: not ours to take. @@ -390,7 +861,7 @@ public sealed class ExportCopier(ExportEnvironment env) // The name the record can take: free on the disk and in the database. A path recorded for another copy whose // file is gone is free again («Tolto»); one whose file is there under another letter case (a case-sensitive // disk) is not, and the next numbered name is tried. - var chosen = await ChooseNameAsync(destination, planned, ct).ConfigureAwait(false); + var chosen = await ChooseNameAsync(destination, planned, output.Suffix, ct).ConfigureAwait(false); // The intent, in its own transaction, before the .part exists (WP1.8 cleans only the folders of items). item = item with { RelativePath = planned }; @@ -400,21 +871,50 @@ public sealed class ExportCopier(ExportEnvironment env) try { var directory = planned.Contains('/', StringComparison.Ordinal) ? planned[..planned.LastIndexOf('/')] : string.Empty; - await using var content = _env.FileSystem.OpenRead(file.Source); - saved = (await new SafeFileWriter(MaxPath).SaveAsync( - content, - root, - directory, - (digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal) - ? ValueTask.FromResult(chosen) - : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."), - new SafeWriteOptions - { - RequireExistingRoot = true, - VerifyFromDisk = true, - LastWriteTime = x.SetFileTime ? file.Entry.PublishedAt : null, - }, - ct).ConfigureAwait(false))!; + var options = new SafeWriteOptions + { + RequireExistingRoot = true, + VerifyFromDisk = true, + LastWriteTime = x.SetFileTime ? library.Entry.PublishedAt : null, + KeepSuffix = output.Suffix, + }; + var writer = new SafeFileWriter(MaxPath); + if (output.Produce is null) + { + await using var content = _env.FileSystem.OpenRead(library.Source); + saved = (await writer.SaveAsync( + content, + root, + directory, + (digest, _) => string.Equals(digest.Sha256, library.Sha256, StringComparison.Ordinal) + ? ValueTask.FromResult(chosen) + : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."), + options, + ct).ConfigureAwait(false))!; + } + else + { + saved = (await writer.SaveAsync( + output.Produce, + root, + directory, + async (digest, token) => + { + if (output.Sha256 is { } known) + { + return string.Equals(digest.Sha256, known, StringComparison.Ordinal) + ? chosen + : throw new ContentChangedException("Il file scritto non corrisponde alla conversione."); + } + + // A remux was read from the library while written: the library file must still be the one recorded. + return string.Equals(await _env.FileSystem.ComputeSha256Async(library.Source, token).ConfigureAwait(false), library.Sha256, StringComparison.Ordinal) + ? chosen + : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."); + }, + options, + ct).ConfigureAwait(false))!; + } } catch (ContentChangedException ex) { @@ -425,7 +925,7 @@ public sealed class ExportCopier(ExportEnvironment env) if (IsDiskFull(ex)) { return ItemResult.Paused(_env.Disk.FreeBytes(root) is { } left - ? ExportText.NoSpace(destination, left, Path.GetFileName(planned), file.Bytes) + ? ExportText.NoSpace(destination, left, Path.GetFileName(planned), output.Length) : ExportText.DiskFull(destination)); } @@ -442,21 +942,32 @@ public sealed class ExportCopier(ExportEnvironment env) // The writer moved the file onto a name where no file was: a row still holding that path is stale (decision of // 2026-11-27), also when the name is the one chosen, since a row could appear meanwhile. await ReleaseStalePathAsync(destination, saved.RelativePath, justWritten: true, ct).ConfigureAwait(false); - return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false); + return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, saved.Sha256, ExportCopyOrigin.Written, Notes(output, taken)).ConfigureAwait(false); } + /// An orphan row is adopted only when it records this very copy: same bytes, variant, format and instant (D10). + private static bool SameForm(ExportCopy holder, FileContext file, string copySha256) => + string.Equals(holder.SourceSha256, file.Library.Sha256, StringComparison.Ordinal) + && string.Equals(holder.CopySha256 ?? holder.SourceSha256, copySha256, StringComparison.Ordinal) + && holder.Variant == file.Identity.Variant + && holder.Format == file.Identity.Format + && holder.FrameAt == file.Identity.FrameAt; + + /// The note codes of an item (D19 of tappa E3): those of its output, then «nome occupato». + private static string? Notes(Output output, string? taken) => ExportText.JoinNotes([.. output.Notes, taken]); + /// /// The first of the planned path and its numbered names (numbered as the writer numbers them) that is free on the /// disk and free, or stale, in the database; the planned path when none is found (the writer then decides). /// - private async Task ChooseNameAsync(ExportDestination destination, string planned, CancellationToken ct) + private async Task ChooseNameAsync(ExportDestination destination, string planned, string? keepSuffix, CancellationToken ct) { for (var attempt = 1; attempt <= MaxSiblings; attempt++) { string name; try { - name = ExportPaths.NumberedName(destination.RootPath, planned, attempt, MaxPath); + name = ExportPaths.NumberedName(destination.RootPath, planned, attempt, MaxPath, keepSuffix); } catch (PathTooLongException) { @@ -508,23 +1019,23 @@ public sealed class ExportCopier(ExportEnvironment env) /// A Superseded row of this very identity whose bytes are at its path: it becomes the Copied row again. When the /// identity has a current «Non riuscito» row, that one becomes the Copied row and the old one stays as history. /// - private async Task ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path) + private async Task ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path, Output output, string copySha256) { var exports = _env.Storage.Exports; var none = CancellationToken.None; var now = _env.Clock.Now; if (failed is null && await exports.FindCurrentCopyAsync(file.Identity, none).ConfigureAwait(false) is null) { - await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false); - return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Bytes, path).ConfigureAwait(false); + await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Library.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Library.Bytes, path).ConfigureAwait(false); } await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Removed, StateChangedAt = now }, none).ConfigureAwait(false); - return await RecordAsync(item, file, failed, null, path, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false); + return await RecordAsync(item, file, failed, null, path, output.Length, copySha256, ExportCopyOrigin.Adopted, Notes(output, null)).ConfigureAwait(false); } /// Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names. - private IEnumerable AdoptionCandidates(string root, string planned, string? previous) + private IEnumerable AdoptionCandidates(string root, string planned, string? previous, string? keepSuffix) { var seen = new HashSet(StringComparer.OrdinalIgnoreCase); if (seen.Add(planned) && Exists(root, planned)) @@ -542,7 +1053,7 @@ public sealed class ExportCopier(ExportEnvironment env) string name; try { - name = ExportPaths.NumberedName(root, previous, attempt, MaxPath); + name = ExportPaths.NumberedName(root, previous, attempt, MaxPath, keepSuffix); } catch (PathTooLongException) { @@ -561,11 +1072,12 @@ public sealed class ExportCopier(ExportEnvironment env) } } - private async Task RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, ExportCopyOrigin origin, string? note) + private async Task RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, string copySha256, ExportCopyOrigin origin, string? note) { var exports = _env.Storage.Exports; var none = CancellationToken.None; var now = _env.Clock.Now; + var identity = file.Identity; ExportCopy copy; try { @@ -577,34 +1089,35 @@ public sealed class ExportCopier(ExportEnvironment env) Origin = origin, RelativePath = path, Bytes = bytes, - CopySha256 = file.Sha256, + CopySha256 = copySha256, CopiedAt = now, StateChangedAt = now, LastError = null, - MediaId = file.Media.Id, + MediaId = file.Library.Media.Id, }; await exports.UpdateCopyAsync(copy, none).ConfigureAwait(false); } else if (orphan is not null) { - copy = await exports.RelinkOrphanCopyAsync(orphan.Id, file.Identity.AccountId, file.Media.Id, now, none).ConfigureAwait(false); + copy = await exports.RelinkOrphanCopyAsync(orphan.Id, identity.AccountId, file.Library.Media.Id, now, none).ConfigureAwait(false); } else { copy = await exports.AddCopyAsync( new ExportCopy { - DestinationId = file.Identity.DestinationId, - AccountId = file.Identity.AccountId, - MediaId = file.Media.Id, - SourceSha256 = file.Sha256, - Variant = ExportVariant.Whole, - Format = ExportFormat.Original, + DestinationId = identity.DestinationId, + AccountId = identity.AccountId, + MediaId = file.Library.Media.Id, + SourceSha256 = identity.SourceSha256, + Variant = identity.Variant, + Format = identity.Format, + FrameAt = identity.FrameAt, State = ExportCopyState.Copied, Origin = origin, RelativePath = path, Bytes = bytes, - CopySha256 = file.Sha256, + CopySha256 = copySha256, CopiedAt = now, }, none).ConfigureAwait(false); @@ -613,11 +1126,11 @@ public sealed class ExportCopier(ExportEnvironment env) catch (DuplicateRecordException) { // Taken meanwhile by another record. The file written stays where it is: nothing is ever removed. - return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Bytes, path).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Library.Bytes, path, bytes).ConfigureAwait(false); } var state = origin == ExportCopyOrigin.Adopted ? ExportItemState.Adopted : ExportItemState.Copied; - return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Bytes, path).ConfigureAwait(false); + return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Library.Bytes, path, bytes).ConfigureAwait(false); } /// f.: the item fails, and its copy is «Non riuscito» (the viewer shows it), the job goes on. @@ -625,24 +1138,26 @@ public sealed class ExportCopier(ExportEnvironment env) { var exports = _env.Storage.Exports; var none = CancellationToken.None; + var identity = file.Identity; long? copyId = failed?.Id; try { if (failed is not null) { - await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Media.Id }, none).ConfigureAwait(false); + await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Library.Media.Id }, none).ConfigureAwait(false); } else { copyId = (await exports.AddCopyAsync( new ExportCopy { - DestinationId = file.Identity.DestinationId, - AccountId = file.Identity.AccountId, - MediaId = file.Media.Id, - SourceSha256 = file.Sha256, - Variant = ExportVariant.Whole, - Format = ExportFormat.Original, + DestinationId = identity.DestinationId, + AccountId = identity.AccountId, + MediaId = file.Library.Media.Id, + SourceSha256 = identity.SourceSha256, + Variant = identity.Variant, + Format = identity.Format, + FrameAt = identity.FrameAt, State = ExportCopyState.Failed, CopiedAt = _env.Clock.Now, LastError = error, @@ -655,13 +1170,13 @@ public sealed class ExportCopier(ExportEnvironment env) // The identity got a current row meanwhile: that one tells the state. } - return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Bytes, item.RelativePath).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Library.Bytes, item.RelativePath).ConfigureAwait(false); } - private async Task FinishAsync(ExportItem item, long bytes, string? path) + private async Task FinishAsync(ExportItem item, long bytes, string? path, long? written = null) { await _env.Storage.Exports.UpdateItemsAsync([item], CancellationToken.None).ConfigureAwait(false); - return new ItemResult(item.State, bytes, path, null); + return new ItemResult(item.State, bytes, path, null, written) { Item = item }; } private async Task<(string? Title, bool InHighlight)> HighlightAsync(Entry entry, CancellationToken ct) @@ -693,14 +1208,87 @@ public sealed class ExportCopier(ExportEnvironment env) && (io.HResult is unchecked((int)0x80070070) or unchecked((int)0x80070027) or 28 || io.Message.Contains("No space left on device", StringComparison.OrdinalIgnoreCase)); - private sealed record FileContext(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, ExportCopyIdentity Identity, string? HighlightTitle, bool InHighlight); + /// The error of a library file that changed before its frames were taken. + private const string SourceChangedText = "Il file della libreria non corrisponde a quello registrato."; + + /// A library file the job may copy now. + private sealed record LibraryFile(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, string? HighlightTitle, bool InHighlight); + + /// The library file of an item, or why the item ends ( null). + private sealed record SourceCheck(LibraryFile? File, ExportItemState State, string? Note, long Bytes); + + /// A library file with the identity of the copy it gives (the prediction until the output is known). + private sealed record FileContext(LibraryFile Library, ExportCopyIdentity Identity); + + /// A frame to take: its exact identity, its suffix, a copy already there, a «Non riuscito» row to reuse. + private sealed record FramePlan(ExportCopyIdentity Identity, string Suffix, ExportCopy? Failed) + { + public ExportCopy? Present { get; init; } + } + + /// + /// What is written: the effective form, the name it changes (extension, frame suffix), its length, its SHA-256 when + /// known before writing, how to write it (null: the library file byte for byte, read and checked as in tappa E2), and + /// its notes. + /// + private sealed record Output( + ExportVariant Variant, + ExportFormat Format, + TimeSpan? FrameAt, + string? Extension, + string? Suffix, + long Length, + string? Sha256, + Func? Produce, + IReadOnlyList Notes) + { + public static Output Whole(LibraryFile library, IReadOnlyList notes) => + new(ExportVariant.Whole, ExportFormat.Original, null, null, null, library.Bytes, library.Sha256, null, notes); + } /// What happened to an item; stops the job with the destination paused. - private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause) + /// Library bytes, for the progress. + /// Bytes written to the destination, for the group of the probe; null: . + private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause, long? Written = null) { + /// The item as stored. + public ExportItem? Item { get; init; } + public static ItemResult Paused(string message) => new(ExportItemState.Pending, 0, null, message); } + /// The pending items of a job, a page at a time, with a look at the next one (a batch may cross pages). + private sealed class PendingItems(IExportStore store, long runId) + { + private readonly Queue _buffer = new(); + private long _after; + private bool _done; + + public async Task PeekAsync(CancellationToken ct) + { + if (_buffer.Count == 0 && !_done) + { + var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = _after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + _done = true; + } + else + { + _after = page[^1].Id; + foreach (var item in page) + { + _buffer.Enqueue(item); + } + } + } + + return _buffer.Count > 0 ? _buffer.Peek() : null; + } + + public ExportItem Take() => _buffer.Dequeue(); + } + private sealed class RunContext(ExportRun run, ExportDestination destination, IProgress? progress) { private readonly Dictionary _destinations = []; @@ -717,6 +1305,12 @@ public sealed class ExportCopier(ExportEnvironment env) public bool CopyAgain { get; set; } + /// The frames request of a frames job (mode, and N of «N in tutto»). + public (FrameMode Mode, int Count)? Frames { get; set; } + + /// «Copia di nuovo» of one copy row: only its exact identity is looked up. + public bool Exact { get; set; } + public IReadOnlyDictionary Effective { get; set; } = new Dictionary(); public int FilesDone { get; set; } @@ -727,6 +1321,11 @@ public sealed class ExportCopier(ExportEnvironment env) public long BytesTotal { get; set; } + /// Files of the current group since its probe. + public int GroupFiles { get; set; } + + public long GroupBytes { get; set; } + public Dictionary ByState { get; set; } = []; public async Task DestinationAsync(IFebeStorage storage, long id, CancellationToken ct) diff --git a/src/Febe.Core/Export/ExportDestinations.cs b/src/Febe.Core/Export/ExportDestinations.cs index 52a8131..bc33dd6 100644 --- a/src/Febe.Core/Export/ExportDestinations.cs +++ b/src/Febe.Core/Export/ExportDestinations.cs @@ -15,6 +15,8 @@ namespace Febe.Core.Export; /// Scheme of profile pictures; null: «Come la libreria». /// «Automatica»: stored only in tappa E2 (tappa E5 acts on it). /// «Solo i nuovi» when «Automatica» is turned on. +/// Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1). +/// Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali». public sealed record DestinationSpec( ExportScope Scope, long? AccountId, @@ -25,7 +27,9 @@ public sealed record DestinationSpec( string? HighlightNamingScheme, string? ProfileNamingScheme, bool Automatic = false, - bool OnlyNew = true); + bool OnlyNew = true, + ExportFormat? PhotoFormat = null, + ExportFormat? VideoFormat = null); /// A saved destination and the warnings of its naming schemes (shown, they do not block). public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList Warnings); @@ -347,6 +351,17 @@ public sealed class ExportDestinations(ExportEnvironment env) throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec)); } + // A change of format is not a new folder: the copies already made stay «già copiato» (D3 of tappa E3). + if (spec.PhotoFormat is { } photo && !ExportFormats.IsPhotoFormat(photo)) + { + throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(spec)); + } + + if (spec.VideoFormat is { } video && !ExportFormats.IsVideoFormat(video)) + { + throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(spec)); + } + var errors = new List(); var warnings = new List(); void Check(string? text, NamingSchemeUse use) @@ -392,6 +407,8 @@ public sealed class ExportDestinations(ExportEnvironment env) NamingScheme = Clean(spec.NamingScheme), HighlightNamingScheme = Clean(spec.HighlightNamingScheme), ProfileNamingScheme = Clean(spec.ProfileNamingScheme), + PhotoFormat = spec.PhotoFormat, + VideoFormat = spec.VideoFormat, Automatic = spec.Automatic, CreatedAt = createdAt, }; diff --git a/src/Febe.Core/Export/ExportEnvironment.cs b/src/Febe.Core/Export/ExportEnvironment.cs index ad90087..91bd374 100644 --- a/src/Febe.Core/Export/ExportEnvironment.cs +++ b/src/Febe.Core/Export/ExportEnvironment.cs @@ -2,6 +2,7 @@ using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Library; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -61,6 +62,9 @@ public sealed record ExportEnvironment /// …or this many planned bytes, whichever comes first. public long GroupBytes { get; init; } = 1L << 30; + /// One conversion at a time in the process (tappa E3, D16): shared with the library conversion. + public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared; + /// The checker of destination folders of this environment. public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe); @@ -101,6 +105,12 @@ public interface IExportFileSystem /// Opens a file for reading only. Stream OpenRead(string path); + /// + /// Opens a file for reading at any position (a video to remux or to take frames from, tappa E3). By default the + /// stream of , which can seek. + /// + Stream OpenRandomAccess(string path) => OpenRead(path); + /// SHA-256 (lowercase hex) of a file as it is on disk now. Task ComputeSha256Async(string path, CancellationToken ct); @@ -121,8 +131,13 @@ public sealed class ExportFileSystem : IExportFileSystem public static ExportFileSystem Instance { get; } = new(); + // FileShare.Delete: a long read never blocks «Elimina dalla libreria» on Windows (tappa E3). public Stream OpenRead(string path) => - new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + + /// As ContainerReader.OpenRead: shared for reading, writing and deleting, read at random positions. + public Stream OpenRandomAccess(string path) => + new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, BufferSize, FileOptions.RandomAccess); public async Task ComputeSha256Async(string path, CancellationToken ct) { diff --git a/src/Febe.Core/Export/ExportFrames.cs b/src/Febe.Core/Export/ExportFrames.cs new file mode 100644 index 0000000..a856732 --- /dev/null +++ b/src/Febe.Core/Export/ExportFrames.cs @@ -0,0 +1,170 @@ +using System.Globalization; + +namespace Febe.Core.Export; + +/// +/// The instants, names and labels of frames (spec §4.10 «Fotogrammi», decisions D12 and D13 of tappa E3): which instants +/// a request asks for, the suffix a frame file gets, and how an instant is shown. +/// +public static class ExportFrames +{ + /// The shortest step of «Uno ogni k secondi». + public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100); + + /// The most frames of «N in tutto». + public const int MaxCount = 1000; + + /// The most frames taken from one video. + public const int MaxPerVideo = 1000; + + /// The most frames of one request. + public const int MaxPerRequest = 20000; + + /// Why a request over is refused. + public const string OverCapMessage = "Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo"; + + /// The suffix of the single frame of «Salva il fotogramma» (tappa E4). + public const string SingleSuffix = "_fotogramma"; + + /// How many frames asks of a video of . + public static long FrameCount(TimeSpan duration, ExportFramesRequest request) + { + ArgumentNullException.ThrowIfNull(request); + return request.Mode switch + { + FrameMode.At => 1, + FrameMode.Every => EveryCount(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))), + FrameMode.Count => request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request)), + _ => throw new ArgumentOutOfRangeException(nameof(request)), + }; + } + + /// + /// The instants asks of a video of , in increasing order. + /// Refused ( with ) over . + /// + public static IReadOnlyList Instants(TimeSpan duration, ExportFramesRequest request) + { + ArgumentNullException.ThrowIfNull(request); + return request.Mode switch + { + FrameMode.At => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero], + FrameMode.Every => Every(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))), + FrameMode.Count => Spread(duration, request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request))), + _ => throw new ArgumentOutOfRangeException(nameof(request)), + }; + } + + /// «Uno ogni k secondi»: 0, k, 2k… before (only 0 for a video without length). + public static IReadOnlyList Every(TimeSpan duration, TimeSpan step) + { + if (step < MinEvery) + { + throw new ArgumentOutOfRangeException(nameof(step), "L'intervallo minimo è 0,1 secondi."); + } + + var count = EveryCount(duration, step); + if (count > MaxPerVideo) + { + throw new ArgumentException(OverCapMessage, nameof(step)); + } + + var instants = new TimeSpan[count]; + for (var i = 0; i < count; i++) + { + instants[i] = WholeMs(TimeSpan.FromTicks(step.Ticks * i)); + } + + return instants; + } + + /// + /// «N in tutto»: (i + ½) · duration / N for i = 0…N − 1, rounded up to the millisecond: the item, the preview and + /// the download locate the same instant. On a video shorter than N milliseconds neighbours can share one. + /// + public static IReadOnlyList Spread(TimeSpan duration, int count) + { + if (count is < 1 or > MaxCount) + { + throw new ArgumentOutOfRangeException(nameof(count), "Da 1 a 1.000 fotogrammi."); + } + + var length = (Int128)Math.Max(0, duration.Ticks); + var instants = new TimeSpan[count]; + for (var i = 0; i < count; i++) + { + instants[i] = WholeMs(TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count)))); + } + + return instants; + } + + /// + /// The suffix of a frame file, appended to the stem: _t0m12s340 (the actual instant: minutes, seconds on two + /// digits, milliseconds on three) for «Questo istante» and «Uno ogni k secondi»; _f001 (the position among + /// the instants, at least three digits) for «N in tutto». + /// + /// 0-based position of the instant in the request. + public static string Suffix(FrameMode mode, TimeSpan actual, int index, int count) + { + if (mode == FrameMode.Count) + { + var digits = Math.Max(3, Math.Max(1, count).ToString(CultureInfo.InvariantCulture).Length); + return "_f" + (index + 1).ToString("D" + digits.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); + } + + var ms = ActualMs(actual); + return string.Create(CultureInfo.InvariantCulture, $"_t{ms / 60000}m{ms / 1000 % 60:D2}s{ms % 1000:D3}"); + } + + /// + /// An instant as the viewer and the dialog show it: m:ss («0:01»), followed by a comma and the milliseconds + /// without trailing zeros only when it is not a whole second («0:01,25»). + /// + public static string Label(TimeSpan actual) + { + var ms = ActualMs(actual); + var label = string.Create(CultureInfo.InvariantCulture, $"{ms / 60000}:{ms / 1000 % 60:D2}"); + var fraction = ms % 1000; + return fraction == 0 + ? label + : label + "," + fraction.ToString("D3", CultureInfo.InvariantCulture).TrimEnd('0'); + } + + /// + /// The position of among (the first of those on the same + /// millisecond, as the items keep them), or null when it is not one of them. + /// + public static int? IndexOf(IReadOnlyList instants, TimeSpan requested) + { + ArgumentNullException.ThrowIfNull(instants); + var ms = (long)requested.TotalMilliseconds; + for (var i = 0; i < instants.Count; i++) + { + if ((long)instants[i].TotalMilliseconds == ms) + { + return i; + } + } + + return null; + } + + /// An instant rounded up to the whole millisecond (never before the instant computed). + private static TimeSpan WholeMs(TimeSpan at) => TimeSpan.FromMilliseconds(ActualMs(at)); + + /// The identity of a frame's instant: its shown time in milliseconds, rounded up. + public static long ActualMs(TimeSpan shown) => + shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond; + + private static long EveryCount(TimeSpan duration, TimeSpan step) + { + if (step <= TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException(nameof(step)); + } + + // 0, k, 2k… strictly before the end: ceil(duration / k), and at least the frame at 0. + return duration <= TimeSpan.Zero ? 1 : Math.Max(1, (duration.Ticks + step.Ticks - 1) / step.Ticks); + } +} diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs index e21e4bb..67ca130 100644 --- a/src/Febe.Core/Export/ExportModels.cs +++ b/src/Febe.Core/Export/ExportModels.cs @@ -23,8 +23,43 @@ public abstract record ExportSelection public sealed record Account(long AccountId) : ExportSelection; } +/// How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»). +public enum FrameMode +{ + /// «Questo istante»: one frame at . + At, + + /// «Uno ogni k secondi»: at 0, k, 2k… before the end. + Every, + + /// «N in tutto»: N frames spread over the video, each in the middle of its share. + Count, +} + +/// A request of frames of videos, in a photo format (Jpg, Png or WebpLossless). +public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format); + +/// +/// The formats of «Copia in…» for this request only (tappa E3, D1): null keeps the destination's (or the general +/// settings'). A photo format or Original for photos; Mp4 or Original for videos. +/// +public sealed record ExportFormatChoice(ExportFormat? Photo, ExportFormat? Video); + +/// «Copia di nuovo» of one copy row (tappa E3, D11): the form of that row, looked up only by its exact identity. +/// The instant of a frame row; null otherwise. +public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt); + /// A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked. -public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual); +/// The formats of this request («Copia in…» → «Cambia»); null: those of the destination. +/// Not null: a frames job («Fotogrammi…» → «Nella cartella delle copie»), videos only. +/// «Copia di nuovo» of one copy row, only with a selection of one file. +public sealed record ExportJobRequest( + ExportSelection Selection, + bool CopyAgain = false, + ExportRunOrigin Origin = ExportRunOrigin.Manual, + ExportFormatChoice? Formats = null, + ExportFramesRequest? Frames = null, + ExportCopyRequest? Exact = null); /// /// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective @@ -55,8 +90,35 @@ public sealed record ExportPlan( bool HasDestination = true) { public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []); + + /// + /// Files predicted to be copied as they are, by kind («3 HEIC copiati come sono»): a prediction from the names + /// («circa»), the copy decides on the bytes (tappa E3). + /// + public IReadOnlyList AsIs { get; init; } = []; + + /// Files predicted to be converted. + public int Converted { get; init; } + + /// «Con perdita»: at least one file predicted converted to JPG, or JPG frames (D7 of tappa E3). + public bool Lossy { get; init; } + + /// Frames job: the due videos. + public int Videos { get; init; } + + /// Frames job: the photos of the selection, skipped («Le 4 foto si saltano»). + public int PhotosSkipped { get; init; } + + /// Frames job: the frames to write (also in ); «circa» for a video of unknown length. + public int Frames { get; init; } + + /// Frames job: videos that would give more than frames (the job is refused). + public int OverCap { get; init; } } +/// Files of a plan copied as they are, of one kind («HEIC», «AVIF», «raw», «GIF», «WebM»). +public sealed record ExportPlanAsIs(string Label, int Files); + /// A destination of a plan. /// The account of an own folder; null for the general folder. /// Files to write there. diff --git a/src/Febe.Core/Export/ExportPaths.cs b/src/Febe.Core/Export/ExportPaths.cs index d085b1f..be93271 100644 --- a/src/Febe.Core/Export/ExportPaths.cs +++ b/src/Febe.Core/Export/ExportPaths.cs @@ -4,6 +4,12 @@ using Febe.Core.Library; namespace Febe.Core.Export; +/// +/// How the file name of a copy differs from the library's (tappa E3): the extension of the effective format +/// («.jpg»; null keeps the source's) and the suffix of a frame («_t0m12s340»; null for none), appended to the stem. +/// +public sealed record ExportNameOptions(string? Extension, string? Suffix); + /// Paths and content types of the export (spec §4.10). public static class ExportPaths { @@ -63,7 +69,8 @@ public static class ExportPaths Media media, string? highlightTitle, bool inHighlight, - TimeZoneInfo zone) + TimeZoneInfo zone, + ExportNameOptions? name = null) { ArgumentNullException.ThrowIfNull(d); ArgumentNullException.ThrowIfNull(library); @@ -106,22 +113,42 @@ public static class ExportPaths segments = scheme.Render(values, zone); } + segments = Renamed(segments, name); return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments; } + /// The last segment with the suffix appended to its stem and the extension of . + private static IReadOnlyList Renamed(IReadOnlyList segments, ExportNameOptions? name) + { + if (name is null || segments.Count == 0 || (name.Extension is null && string.IsNullOrEmpty(name.Suffix))) + { + return segments; + } + + var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); + var fileName = WindowsFileNames.SanitizeSegment(stem + (name.Suffix ?? string.Empty) + (name.Extension ?? extension)); + return [.. segments.Take(segments.Count - 1), fileName]; + } + /// The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root. + /// The destination. + /// The segments of . + /// The longest full path. + /// The frame suffix of the file name, never cut by the shortening. /// Even shortened, the path does not fit. - public static string RelativePathFor(ExportDestination d, IReadOnlyList segments, int maxPath = WindowsFileNames.MaxPathLength) + public static string RelativePathFor(ExportDestination d, IReadOnlyList segments, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null) { ArgumentNullException.ThrowIfNull(d); - return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath)); + return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath, keepSuffix)); } /// /// The name the safe writer gives a file at its -th try when the planned name is taken - /// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. + /// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. With + /// (a frame suffix, ) the number comes after + /// it and both survive the shortening: «x_f001 (2).png». /// - public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength) + public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null) { ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries); @@ -132,7 +159,8 @@ public static class ExportPaths var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}")); - return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath)); + var keep = keepSuffix is null ? null : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})"); + return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath, keep)); } /// The scheme that names an entry kind. diff --git a/src/Febe.Core/Export/ExportPlanner.cs b/src/Febe.Core/Export/ExportPlanner.cs index f087ef2..43a346e 100644 --- a/src/Febe.Core/Export/ExportPlanner.cs +++ b/src/Febe.Core/Export/ExportPlanner.cs @@ -6,8 +6,10 @@ namespace Febe.Core.Export; /// /// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the -/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are -/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog. +/// effective destination of its account; a file already copied there, in any form but a frame, is «già copiato» +/// (decision D3 of tappa E3); «Tolti» and «Superati» are skipped unless «Copia di nuovo» was asked. The format of each +/// file is resolved and predicted from its name (D1, «circa»); a frames job plans one frame per instant of each due +/// video. The only look at a destination is whether it answers, for the dialog. /// public sealed class ExportPlanner(ExportEnvironment env) { @@ -16,9 +18,11 @@ public sealed class ExportPlanner(ExportEnvironment env) private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); /// The plan of a request, for the «Copia in…» dialog. + /// The request is not valid (Italian message). public async Task PlanAsync(ExportJobRequest request, CancellationToken ct) { ArgumentNullException.ThrowIfNull(request); + Validate(request); var destinations = new ExportDestinations(_env); var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false); var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); @@ -31,17 +35,108 @@ public sealed class ExportPlanner(ExportEnvironment env) return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false); } + /// The checks of a request (tappa E3, WP1.1), with Italian messages. + /// What is wrong. + public static void Validate(ExportJobRequest request) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request.Selection, nameof(request)); + if (request.Frames is not null && request.Formats is not null) + { + throw new ArgumentException("I fotogrammi non si chiedono insieme ai formati delle copie.", nameof(request)); + } + + if (request.Exact is { } exact) + { + if (request.Selection is not ExportSelection.Media { MediaIds.Count: 1 }) + { + throw new ArgumentException("«Copia di nuovo» di una copia vale per un file solo.", nameof(request)); + } + + if (request.Frames is not null || request.Formats is not null) + { + throw new ArgumentException("«Copia di nuovo» di una copia rifà la sua forma: niente altri formati né fotogrammi.", nameof(request)); + } + + var valid = exact.Variant switch + { + ExportVariant.Whole => exact.Format == ExportFormat.Original && exact.FrameAt is null, + ExportVariant.Converted => exact.Format != ExportFormat.Original && exact.FrameAt is null, + ExportVariant.Frame => IsFrameFormat(exact.Format) && exact.FrameAt is { } at && at >= TimeSpan.Zero, + _ => false, + }; + if (!valid) + { + throw new ArgumentException("La forma della copia da rifare non è valida.", nameof(request)); + } + } + + if (request.Formats is { } formats) + { + if (formats.Photo is { } photo && !ExportFormats.IsPhotoFormat(photo)) + { + throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(request)); + } + + if (formats.Video is { } video && !ExportFormats.IsVideoFormat(video)) + { + throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(request)); + } + } + + if (request.Frames is { } frames) + { + if (!IsFrameFormat(frames.Format)) + { + throw new ArgumentException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.", nameof(request)); + } + + switch (frames.Mode) + { + case FrameMode.At when frames.At is not { } at || at < TimeSpan.Zero: + throw new ArgumentException("Scegli l'istante del fotogramma.", nameof(request)); + case FrameMode.Every when frames.Every is not { } every || every < ExportFrames.MinEvery: + throw new ArgumentException("L'intervallo minimo è 0,1 secondi.", nameof(request)); + case FrameMode.Count when frames.Count is not ({ } count and >= 1 and <= ExportFrames.MaxCount): + throw new ArgumentException("Da 1 a 1.000 fotogrammi.", nameof(request)); + case FrameMode.At or FrameMode.Every or FrameMode.Count: + break; + default: + throw new ArgumentException("Modo dei fotogrammi sconosciuto.", nameof(request)); + } + } + } + + /// JPG, PNG or WEBP senza perdita: the formats of a frame. + internal static bool IsFrameFormat(ExportFormat format) => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless; + /// - /// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an - /// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with - /// «Una copia sola» the same file counts once across accounts. + /// Every candidate of the request with what to do with it, in media id order (a frames job: one planned file per + /// instant of each video, in instant order). Within one plan the same file of an account in one destination counts + /// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts + /// once across accounts. /// + /// + /// Frames job: the length of a video the library does not know, read from its file (null when unreadable); without + /// it such a video is one planned file without instants (, the dialog). + /// internal async IAsyncEnumerable EnumerateAsync( ExportJobRequest request, IReadOnlyDictionary effective, ExportSettings settings, - [EnumeratorCancellation] CancellationToken ct) + [EnumeratorCancellation] CancellationToken ct, + Func>? lengthOf = null) { + if (request.Frames is { } frames) + { + await foreach (var frame in EnumerateFramesAsync(request, frames, effective, lengthOf, ct).ConfigureAwait(false)) + { + yield return frame; + } + + yield break; + } + var exports = _env.Storage.Exports; var oneOnly = settings.SamePost == SamePostCopies.OneOnly; var seen = new HashSet<(long Destination, long Account, string Sha256)>(); @@ -70,9 +165,12 @@ public sealed class ExportPlanner(ExportEnvironment env) } var states = new Dictionary>(); - foreach (var (destination, set) in keys) + if (request.Exact is null) { - states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false); + foreach (var (destination, set) in keys) + { + states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false); + } } foreach (var c in page) @@ -91,25 +189,45 @@ public sealed class ExportPlanner(ExportEnvironment env) var sha = c.Sha256!; var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha); - var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null; + var form = Form(c, request, effective[c.AccountId].Destination!, settings); + ExportCopyState? state; + if (request.Exact is { } exact) + { + // «Copia di nuovo» of one row: only its exact identity counts (D11 of tappa E3). + var identity = new ExportCopyIdentity(destination, c.AccountId, sha, exact.Variant, exact.Format, exact.FrameAt); + if (await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false) is { } current) + { + state = current.State; + } + else + { + var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false); + state = latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded } ? latest.State : null; + } + } + else + { + state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : null; + } + PlannedFile planned; if (state == ExportCopyState.Copied) { - planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied }; } else if (state is ExportCopyState.Removed or ExportCopyState.Superseded) { planned = request.CopyAgain - ? new PlannedFile(c, destination, PlannedCopy.Write, Again: true) - : new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded); + ? form with { DestinationId = destination, Action = PlannedCopy.Write, Again = true } + : form with { DestinationId = destination, Action = PlannedCopy.RemovedOrSuperseded }; } - else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, c.AccountId, ct).ConfigureAwait(false) is not null) + else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, c.AccountId, ct).ConfigureAwait(false) is not null) { - planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied }; } else { - planned = new PlannedFile(c, destination, PlannedCopy.Write); + planned = form with { DestinationId = destination, Action = PlannedCopy.Write }; } if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key)) @@ -122,6 +240,128 @@ public sealed class ExportPlanner(ExportEnvironment env) } } + /// + /// A frames job (D12, D14 of tappa E3): photos are skipped, videos not due are counted as in «Copia in…», each due + /// video gives one planned frame per instant of the request. A video of unknown length is measured by + /// (the job: before anything is recorded, so that its frames count against the caps of + /// D12) or, without it, gives one planned file without an instant (, the + /// dialog). One that cannot be read gets one instant, and the copy says «Fotogramma non disponibile per questo + /// video». Frames are not checked for «già copiato» here: the copy looks at each one's exact instant. + /// + private async IAsyncEnumerable EnumerateFramesAsync( + ExportJobRequest request, + ExportFramesRequest frames, + IReadOnlyDictionary effective, + Func>? lengthOf, + [EnumeratorCancellation] CancellationToken ct) + { + var exports = _env.Storage.Exports; + var seen = new HashSet<(long Destination, long Account, string Sha256, long Ms, ExportFormat Format)>(); + long after = 0; + while (true) + { + var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false); + if (page.Count == 0) + { + yield break; + } + + after = page[^1].MediaId; + foreach (var c in page) + { + if (!IsPresent(c)) + { + yield return new PlannedFile(c, null, PlannedCopy.Missing); + continue; + } + + if (c.MediaKind != MediaKind.Video) + { + yield return new PlannedFile(c, null, PlannedCopy.PhotoSkipped); + continue; + } + + if (Due(c, effective) is not { } destination) + { + yield return new PlannedFile(c, null, PlannedCopy.NotExported); + continue; + } + + var frame = new PlannedFile(c, destination, PlannedCopy.Write) + { + Variant = ExportVariant.Frame, + Format = frames.Format, + Prediction = ExportPrediction.Converted, + FirstOfVideo = true, + }; + var duration = c.Duration ?? TimeSpan.Zero; + if (frames.Mode != FrameMode.At && c.Duration is null) + { + if (lengthOf is null) + { + yield return frame with { UnknownDuration = true }; + continue; + } + + if (await lengthOf(c, ct).ConfigureAwait(false) is not { } measured || measured <= TimeSpan.Zero) + { + var unreadable = frame with { FrameAt = TimeSpan.Zero }; + yield return seen.Add((destination, c.AccountId, c.Sha256!, 0, frames.Format)) + ? unreadable + : unreadable with { Action = PlannedCopy.AlreadyCopied }; + continue; + } + + duration = measured; + } + + if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo) + { + yield return frame with { Action = PlannedCopy.OverCap }; + continue; + } + + var first = true; + foreach (var at in ExportFrames.Instants(duration, frames)) + { + var planned = frame with { FrameAt = at, FirstOfVideo = first }; + first = false; + // By the millisecond the item keeps (ux_export_item_file): two instants on one are one item. + if (!seen.Add((destination, c.AccountId, c.Sha256!, (long)at.TotalMilliseconds, frames.Format))) + { + planned = planned with { Action = PlannedCopy.AlreadyCopied }; + } + + yield return planned; + } + } + } + } + + /// The form a file is asked in (D1, D2): the request's identity, and what its name predicts. + private static PlannedFile Form(ExportCandidate c, ExportJobRequest request, ExportDestination destination, ExportSettings settings) + { + if (request.Exact is { } exact) + { + var prediction = exact.Variant == ExportVariant.Whole ? ExportPrediction.Whole : ExportConversions.Predict(c.RelativePath!, c.MediaKind, exact.Format); + return new PlannedFile(c, null, PlannedCopy.Write) + { + Variant = exact.Variant, + Format = exact.Format, + FrameAt = exact.FrameAt, + Prediction = exact.Variant == ExportVariant.Frame ? ExportPrediction.Converted : prediction, + }; + } + + var target = ExportConversions.Resolve(c.MediaKind, request.Formats, destination, settings); + return new PlannedFile(c, null, PlannedCopy.Write) + { + Variant = ExportConversions.VariantOf(target), + Format = target, + Prediction = ExportConversions.Predict(c.RelativePath!, c.MediaKind, target), + }; + } + /// A file present in the library, with its SHA-256 and path. internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath); @@ -135,7 +375,26 @@ public sealed class ExportPlanner(ExportEnvironment env) /// A candidate with what the plan does with it. /// Where it goes; null when not exported or missing. /// Written although «Tolto» or «Superato», because «Copia di nuovo» was asked. -internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false); +internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false) +{ + /// The variant asked (the request, D2 of tappa E3): Whole, Converted or Frame. + public ExportVariant Variant { get; init; } = ExportVariant.Whole; + + /// The format asked. + public ExportFormat Format { get; init; } = ExportFormat.Original; + + /// The instant asked of a frame. + public TimeSpan? FrameAt { get; init; } + + /// What the name predicts («circa»). + public ExportPrediction Prediction { get; init; } = ExportPrediction.Whole; + + /// Frames job: the first planned file of its video (the videos are counted on it). + public bool FirstOfVideo { get; init; } + + /// Frames job: a video of unknown length, without instants yet («circa» one frame). + public bool UnknownDuration { get; init; } +} internal enum PlannedCopy { @@ -144,12 +403,19 @@ internal enum PlannedCopy RemovedOrSuperseded, NotExported, Missing, + + /// Frames job: a photo of the selection. + PhotoSkipped, + + /// Frames job: a video over frames. + OverCap, } /// Counts of a plan while its files go by. internal sealed class PlanTally { private readonly Dictionary _byDestination = []; + private readonly Dictionary _asIs = new(StringComparer.Ordinal); public int Files { get; private set; } @@ -163,8 +429,25 @@ internal sealed class PlanTally public int Missing { get; private set; } + public int Converted { get; private set; } + + public bool Lossy { get; private set; } + + public int Videos { get; private set; } + + public int PhotosSkipped { get; private set; } + + public int Frames { get; private set; } + + public int OverCap { get; private set; } + public void Add(PlannedFile file) { + if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing)) + { + Videos++; + } + switch (file.Action) { case PlannedCopy.Missing: @@ -173,6 +456,13 @@ internal sealed class PlanTally case PlannedCopy.NotExported: NotExported++; return; + case PlannedCopy.PhotoSkipped: + PhotosSkipped++; + return; + case PlannedCopy.OverCap: + OverCap++; + Videos++; + return; case PlannedCopy.AlreadyCopied: AlreadyCopied++; break; @@ -180,7 +470,8 @@ internal sealed class PlanTally RemovedOrSuperseded++; break; case PlannedCopy.Write: - var bytes = file.Candidate.Bytes ?? 0; + var frame = file.Variant == ExportVariant.Frame; + var bytes = frame ? 0 : file.Candidate.Bytes ?? 0; Files++; Bytes += bytes; if (file.Again) @@ -188,6 +479,21 @@ internal sealed class PlanTally RemovedOrSuperseded++; } + if (frame) + { + Frames++; + Lossy |= file.Format == ExportFormat.Jpg; + } + else if (file.Prediction == ExportPrediction.Converted) + { + Converted++; + Lossy |= file.Format == ExportFormat.Jpg; + } + else if (file.Prediction == ExportPrediction.AsIs && ExportConversions.AsIsLabel(file.Candidate.RelativePath!) is { } label) + { + _asIs[label] = _asIs.GetValueOrDefault(label) + 1; + } + var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value); _byDestination[file.DestinationId.Value] = (f + 1, b + bytes); return; @@ -230,7 +536,16 @@ internal sealed class PlanTally } var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0; - return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any); + return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any) + { + AsIs = _asIs.OrderByDescending(p => p.Value).ThenBy(p => p.Key, StringComparer.Ordinal).Select(p => new ExportPlanAsIs(p.Key, p.Value)).ToList(), + Converted = Converted, + Lossy = Lossy, + Videos = Videos, + PhotosSkipped = PhotosSkipped, + Frames = Frames, + OverCap = OverCap, + }; } /// Destinations that get a run: those with files to write, already copied, or «tolti o superati». diff --git a/src/Febe.Core/Export/ExportReports.cs b/src/Febe.Core/Export/ExportReports.cs index c8bc328..9fc17c6 100644 --- a/src/Febe.Core/Export/ExportReports.cs +++ b/src/Febe.Core/Export/ExportReports.cs @@ -12,10 +12,24 @@ public sealed record ExportReport( IReadOnlyDictionary ByState, long BytesCopied, IReadOnlyList Accounts, - IReadOnlyList Problems); + IReadOnlyList Problems) +{ + /// + /// Tappa E3: at most files copied or adopted with a note (copied as they + /// are, what a conversion did not keep, a free name). + /// + public IReadOnlyList Notes { get; init; } = []; +} /// The files of one account in a job («Copiato» counts written and adopted files). -public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed); +public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed) +{ + /// + /// Tappa E3: the files copied as they are, by kind («HEIC», «AVIF», «raw», «animata», «video», «altro»): the exact + /// counts of the job, where the plan's are predictions. + /// + public IReadOnlyDictionary AsIs { get; init; } = new Dictionary(); +} /// A file of the report, with its reason in Italian. public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text); @@ -45,6 +59,8 @@ public sealed class ExportReports(ExportEnvironment env) var accounts = new Dictionary(); var problems = new List(); + var notes = new List(); + var asIs = new Dictionary>(); long bytes = 0; long after = 0; while (true) @@ -68,6 +84,21 @@ public sealed class ExportReports(ExportEnvironment env) { case ExportItemState.Copied or ExportItemState.Adopted: row[0]++; + if (AsIsLabel(item.Note) is { } label) + { + if (!asIs.TryGetValue(key, out var kinds)) + { + asIs[key] = kinds = new Dictionary(StringComparer.Ordinal); + } + + kinds[label] = kinds.GetValueOrDefault(label) + 1; + } + + if (item.Note is not null && notes.Count < MaxProblems && ExportText.Note(item.Note) is { } noted) + { + notes.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, noted)); + } + if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b }) { bytes += b; @@ -98,9 +129,42 @@ public sealed class ExportReports(ExportEnvironment env) } var perAccount = accounts - .Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3])) + .Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3]) + { + AsIs = asIs.TryGetValue(a.Key, out var kinds) ? kinds : new Dictionary(), + }) .OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase) .ToList(); - return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems); + return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems) { Notes = notes }; + } + + /// The kind of a file copied as it is, from the codes of its note; null when it was not. + internal static string? AsIsLabel(string? note) + { + if (string.IsNullOrWhiteSpace(note)) + { + return null; + } + + foreach (var code in note.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + var name = code.Split(':', 2)[0]; + var label = name switch + { + ExportText.Notes.AsIsHeif => "HEIC", + ExportText.Notes.AsIsAvif => "AVIF", + ExportText.Notes.AsIsRaw => "raw", + ExportText.Notes.AsIsAnimated => "animata", + ExportText.Notes.AsIsNotRemuxable => "video", + _ when name.StartsWith("AsIs", StringComparison.Ordinal) => "altro", + _ => null, + }; + if (label is not null) + { + return label; + } + } + + return null; } } diff --git a/src/Febe.Core/Export/ExportRunSettings.cs b/src/Febe.Core/Export/ExportRunSettings.cs index de8e04b..f6f6a4b 100644 --- a/src/Febe.Core/Export/ExportRunSettings.cs +++ b/src/Febe.Core/Export/ExportRunSettings.cs @@ -11,6 +11,53 @@ internal static class ExportRunSettings { public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo"); + /// How the frames of a frames job were asked (tappa E3): Istante, Ogni or Numero:N. + public static string FramesKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.fotogrammi"); + + /// «Copia di nuovo» of one copy row: only its exact identity is looked up (decision D11 of tappa E3). + public static string ExactKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.esatta"); + + /// The frames request of a job, or null for a job of whole or converted files. + public static async Task<(FrameMode Mode, int Count)?> GetFramesAsync(ISettingsStore store, long runId, CancellationToken ct) + { + var text = (await store.GetAsync(FramesKey(runId), ct).ConfigureAwait(false))?.Trim(); + if (text is null) + { + return null; + } + + if (string.Equals(text, "Istante", StringComparison.Ordinal)) + { + return (FrameMode.At, 1); + } + + if (string.Equals(text, "Ogni", StringComparison.Ordinal)) + { + return (FrameMode.Every, 0); + } + + return text.StartsWith("Numero:", StringComparison.Ordinal) + && int.TryParse(text.AsSpan("Numero:".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var count) && count > 0 + ? (FrameMode.Count, count) + : null; + } + + public static Task SetFramesAsync(ISettingsStore store, long runId, FrameMode mode, int count, CancellationToken ct) => + store.SetAsync( + FramesKey(runId), + mode switch + { + FrameMode.At => "Istante", + FrameMode.Every => "Ogni", + _ => string.Create(CultureInfo.InvariantCulture, $"Numero:{count}"), + }, + ct); + + public static async Task GetExactAsync(ISettingsStore store, long runId, CancellationToken ct) => + string.Equals((await store.GetAsync(ExactKey(runId), ct).ConfigureAwait(false))?.Trim(), "1", StringComparison.Ordinal); + + public static Task SetExactAsync(ISettingsStore store, long runId, CancellationToken ct) => store.SetAsync(ExactKey(runId), "1", ct); + /// «Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9). public static async Task GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct) { @@ -21,6 +68,14 @@ internal static class ExportRunSettings public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) => store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct); + /// Every key of the job, in one transaction (a run id can be used again after DeleteRunAsync). public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) => - store.SetAsync(CopyAgainKey(runId), null, ct); + store.SetManyAsync( + new Dictionary + { + [CopyAgainKey(runId)] = null, + [FramesKey(runId)] = null, + [ExactKey(runId)] = null, + }, + ct); } diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs index 16896a1..f8c22d9 100644 --- a/src/Febe.Core/Export/ExportService.cs +++ b/src/Febe.Core/Export/ExportService.cs @@ -15,6 +15,9 @@ namespace Febe.Core.Export; public sealed class ExportService : IAsyncDisposable { private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila."; + + /// A frames request over . + public const string TooManyFramesText = "Più di 20.000 fotogrammi in una richiesta: scegli meno video o un intervallo più lungo"; private const int ItemBatch = 2000; private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250); @@ -114,9 +117,13 @@ public sealed class ExportService : IAsyncDisposable /// recorded and nothing starts. /// /// A copy, an import or a rebuild is running. + /// + /// The request is not valid, or a frames request asks more than 1.000 frames of a video or 20.000 in all (Italian message). + /// public async Task StartAsync(ExportJobRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); + ExportPlanner.Validate(request); var held = new LeaseHolder(); lock (_gate) { @@ -160,12 +167,48 @@ public sealed class ExportService : IAsyncDisposable var runs = new Dictionary(); var pending = new List(); var exports = _env.Storage.Exports; + // Frames job: the videos whose length the library does not know are measured once, in the first pass, so that + // their frames count against the caps; the recording pass reuses the lengths (they cannot disagree). + var lengths = new Dictionary(); + Func>? lengthOf = request.Frames is null + ? null + : async (candidate, token) => + { + if (!lengths.TryGetValue(candidate.MediaId, out var length)) + { + length = await ProbeLengthAsync(candidate, token).ConfigureAwait(false); + lengths[candidate.MediaId] = length; + } + + return length; + }; + if (request.Frames is not null) + { + // Refused before anything is recorded (D12 of tappa E3): a video over 1.000 frames, more than 20.000 in all. + var count = new PlanTally(); + await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false)) + { + count.Add(file); + } + + if (count.OverCap > 0) + { + throw new ArgumentException(ExportFrames.OverCapMessage, nameof(request)); + } + + if (count.Frames > ExportFrames.MaxPerRequest) + { + throw new ArgumentException(TooManyFramesText, nameof(request)); + } + } + + var frameItems = 0; try { - await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) + await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false)) { tally.Add(file); - if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported) + if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap) { continue; } @@ -176,10 +219,14 @@ public sealed class ExportService : IAsyncDisposable new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); runs[destination] = run; - if (request.CopyAgain) - { - await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false); - } + await RecordRunSettingsAsync(run.Id, request).ConfigureAwait(false); + } + + // Frame items of one video are added together, in instant order (the copy takes them as one batch). + // The first pass already refused more than 20.000: this only guards that it saw the same files. + if (file.Variant == ExportVariant.Frame && file.Action == PlannedCopy.Write && ++frameItems > ExportFrames.MaxPerRequest) + { + throw new ArgumentException(TooManyFramesText, nameof(request)); } pending.Add(new ExportItem @@ -188,10 +235,12 @@ public sealed class ExportService : IAsyncDisposable MediaId = file.Candidate.MediaId, AccountId = file.Candidate.AccountId, SourceSha256 = file.Candidate.Sha256, - Variant = ExportVariant.Whole, - Format = ExportFormat.Original, + Variant = file.Variant, + Format = file.Format, + FrameAt = file.FrameAt, State = ExportItemState.Pending, }); + if (pending.Count >= ItemBatch) { await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false); @@ -235,6 +284,65 @@ public sealed class ExportService : IAsyncDisposable return new ExportStart(ordered, plan); } + /// + /// The keys of a new job: cleared first (a run id can be used again after DeleteRunAsync), then what a resume + /// needs to know (WP1.2 of tappa E3): «Copia di nuovo», the frames request, the exact identity of «Copia di nuovo» + /// of one copy. + /// + private async Task RecordRunSettingsAsync(long runId, ExportJobRequest request) + { + var store = _env.Storage.Settings; + var none = CancellationToken.None; + await ExportRunSettings.ClearAsync(store, runId, none).ConfigureAwait(false); + if (request.CopyAgain) + { + await ExportRunSettings.SetCopyAgainAsync(store, runId, true, none).ConfigureAwait(false); + } + + if (request.Frames is { } frames) + { + await ExportRunSettings.SetFramesAsync(store, runId, frames.Mode, frames.Count ?? 0, none).ConfigureAwait(false); + } + else if (request.Exact is { Variant: ExportVariant.Frame }) + { + await ExportRunSettings.SetFramesAsync(store, runId, FrameMode.At, 1, none).ConfigureAwait(false); + } + + if (request.Exact is not null) + { + await ExportRunSettings.SetExactAsync(store, runId, none).ConfigureAwait(false); + } + } + + /// + /// The length of a video the library does not know, from its headers (only the library file, never the + /// destination); null when it cannot be read now (the job then gives it one instant, and the copy tells). + /// + private async Task ProbeLengthAsync(ExportCandidate candidate, CancellationToken ct) + { + var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false); + var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false); + if (media is null || account is null || _env.ResolveSourcePath(account, media) is not { } path) + { + return null; + } + + try + { + return await Task.Run( + () => + { + using var stream = _env.FileSystem.OpenRandomAccess(path); + return VideoFrameReader.ProbeDuration(stream); + }, + ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; // not readable now: one instant, the copy tells + } + } + /// /// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a /// paused one checks its destination first and pauses again if it still does not answer). diff --git a/src/Febe.Core/Export/ExportSettings.cs b/src/Febe.Core/Export/ExportSettings.cs index 2e2d1b9..2e3ac4a 100644 --- a/src/Febe.Core/Export/ExportSettings.cs +++ b/src/Febe.Core/Export/ExportSettings.cs @@ -68,18 +68,19 @@ public sealed record ExportSettings( public Task SaveAsync(ISettingsStore store, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(store); - return store.SetManyAsync( - new Dictionary - { - [ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(), - [ExportSettingKeys.VideoFormat] = VideoFormat.ToString(), - [ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(), - [ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(), - [ExportSettingKeys.SamePost] = SamePost.ToString(), - }, - ct); + return store.SetManyAsync(Values(), ct); } + /// The five keys with their stored values (for a write that stores more with them). + public Dictionary Values() => new(StringComparer.Ordinal) + { + [ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(), + [ExportSettingKeys.VideoFormat] = VideoFormat.ToString(), + [ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(), + [ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(), + [ExportSettingKeys.SamePost] = SamePost.ToString(), + }; + /// The settings from stored values: exact, case-sensitive names; anything else gives the key's default. internal static ExportSettings From(IReadOnlyDictionary values) { diff --git a/src/Febe.Core/Export/ExportSupersession.cs b/src/Febe.Core/Export/ExportSupersession.cs index 77377a7..4d6e775 100644 --- a/src/Febe.Core/Export/ExportSupersession.cs +++ b/src/Febe.Core/Export/ExportSupersession.cs @@ -1,4 +1,5 @@ using Febe.Core.Domain; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -25,6 +26,7 @@ public static class ExportSupersession } var old = oldSha256.ToLowerInvariant(); + await LibraryConversionsChangedAsync(storage, accountId, old, newSha256.ToLowerInvariant(), at).ConfigureAwait(false); var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false); if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State))) { @@ -33,4 +35,31 @@ public static class ExportSupersession return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false); } + + /// + /// The conversions for the library of the account's file that now has (tappa E3, + /// WP2.4): a converted file of the old bytes is «Superato» (it stays), the queue and the failures take the new bytes, + /// and the file is queued again in the library formats set now. + /// + private static async Task LibraryConversionsChangedAsync(IFebeStorage storage, long accountId, string oldSha256, string newSha256, DateTimeOffset at) + { + var none = CancellationToken.None; + var changed = await storage.Conversions.SupersedeAsync(accountId, oldSha256, newSha256, at, none).ConfigureAwait(false); + if (changed.Count == 0) + { + return; + } + + var media = new List(); + foreach (var id in changed) + { + if (await storage.Media.GetAsync(id, none).ConfigureAwait(false) is { } m) + { + media.Add(m); + } + } + + await LibraryConversionQueue.EnqueueEntryAsync(storage, media, at, none).ConfigureAwait(false); + LibraryConversionQueue.Signal(); + } } diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs index 384dfc1..ed1edd8 100644 --- a/src/Febe.Core/Export/ExportText.cs +++ b/src/Febe.Core/Export/ExportText.cs @@ -1,5 +1,8 @@ +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.Images; using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Export; @@ -24,6 +27,22 @@ public static class ExportText public const string NameTaken = "NameTaken"; public const string PathTaken = "PathTaken"; public const string NotExported = "NotExported"; + + // Tappa E3 (D19): an item's note is a list of codes separated by spaces, «Code» or «Code:Arg». + public const string AsIsHeif = ImageConversionLosses.AsIsHeif; + public const string AsIsAvif = ImageConversionLosses.AsIsAvif; + public const string AsIsRaw = ImageConversionLosses.AsIsRaw; + public const string AsIsAnimated = ImageConversionLosses.AsIsAnimated; + public const string AsIsNotDecodable = ImageConversionLosses.AsIsNotDecodable; + public const string AsIsDeepColor = ImageConversionLosses.AsIsDeepColor; + public const string AsIsCmyk = ImageConversionLosses.AsIsCmyk; + public const string AsIsTooLarge = ImageConversionLosses.AsIsTooLarge; + public const string AsIsNotRemuxable = MediaConversionResult.AsIsNotRemuxable; + public const string FrameNotAvailable = "FrameNotAvailable"; + public const string TransparencyWhite = ImageConversionLosses.TransparencyWhite; + public const string CopiedInAnotherFormat = "CopiedInAnotherFormat"; + public const string LostTracks = Mp4Remuxer.LostTracks; + public const string LostVideoMetadata = Mp4Remuxer.LostVideoMetadata; } /// Name of the state of a file of a job. @@ -49,21 +68,95 @@ public static class ExportText _ => state.ToString(), }; - /// The Italian text of a note code; null for none; an unknown code is shown as it is. - public static string? Note(string? code) => code switch + /// + /// The Italian text of a note: its codes (separated by spaces, D19 of tappa E3) each in Italian, joined with « · »; + /// null for none; an unknown code is shown as it is. + /// + public static string? Note(string? note) + { + if (string.IsNullOrWhiteSpace(note)) + { + return null; + } + + var codes = note.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + return string.Join(" · ", codes.Select(One)); + } + + /// The codes as one note (D19 of tappa E3): the non-empty ones, without repeats, separated by spaces; null for none. + public static string? JoinNotes(IEnumerable codes) + { + ArgumentNullException.ThrowIfNull(codes); + var list = codes.Where(c => !string.IsNullOrWhiteSpace(c)).Select(c => c!.Trim()).Distinct(StringComparer.Ordinal).ToList(); + return list.Count == 0 ? null : string.Join(' ', list); + } + + /// The reason of «non si porta in MP4», from the code of . + private static string RemuxReason(string reason) => reason switch + { + nameof(RemuxRefusal.NotAVideo) => "Febe non lo riconosce come video", + nameof(RemuxRefusal.ContainerNotRemuxable) => "contenitore", + nameof(RemuxRefusal.VideoCodec) => "codec video", + nameof(RemuxRefusal.AudioCodec) => "codec audio", + nameof(RemuxRefusal.MissingConfiguration) => "configurazione del codec mancante", + nameof(RemuxRefusal.EncodedTrack) => "tracce codificate", + nameof(RemuxRefusal.EditList) => "elenco di modifiche", + nameof(RemuxRefusal.NoSamples) => "nessun fotogramma", + nameof(RemuxRefusal.Unreadable) => "file rovinato", + _ => reason, + }; + + private static string One(string code) + { + var colon = code.IndexOf(':', StringComparison.Ordinal); + var name = colon < 0 ? code : code[..colon]; + var arg = colon < 0 ? null : code[(colon + 1)..]; + const string AsIsVideo = "Video copiato com'è: non si porta in MP4 senza ricodificarlo"; + return name switch + { + Notes.AsIsNotRemuxable => arg is { Length: > 0 } ? $"{AsIsVideo} ({RemuxReason(arg)})" : AsIsVideo, + Notes.LostTracks => arg is { Length: > 0 } ? $"Tracce tolte: {arg}" : "Tracce tolte", + _ when arg is null => Note1(code) ?? code, + _ => code, + }; + } + + private static string? Note1(string code) => code switch { - null or "" => null, Notes.SourceMissing => "File non presente in libreria", Notes.AccountRemoved => "L'account è stato rimosso", Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)", Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo", Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)", - Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato", + Notes.SourceChanged => "Il file della libreria è cambiato durante la copia", Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta", Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero", Notes.PathTaken => "Percorso preso nel frattempo: riprova", Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella", - _ => code, + Notes.AsIsHeif => "HEIC copiato com'è", + Notes.AsIsAvif => "AVIF copiato com'è", + Notes.AsIsRaw => "Raw copiato com'è", + Notes.AsIsAnimated => "Immagine animata copiata com'è: convertita perderebbe i fotogrammi dopo il primo", + Notes.AsIsNotDecodable => "Copiato com'è: Febe non riesce a leggere l'immagine", + Notes.AsIsDeepColor => "Copiato com'è: più di 8 bit per colore", + Notes.AsIsCmyk => "Copiato com'è: immagine CMYK", + Notes.AsIsTooLarge => "Copiato com'è: troppo grande per il formato scelto", + Notes.FrameNotAvailable => "Fotogramma non disponibile per questo video", + Notes.TransparencyWhite => "La trasparenza è diventata bianco", + Notes.CopiedInAnotherFormat => "Già copiato in un altro formato", + ImageConversionLosses.LostTexts => "Non tenuti: testi", + ImageConversionLosses.LostColorChunks => "Non tenuti: dati del colore", + ImageConversionLosses.LostIcc => "Non tenuto: profilo ICC", + ImageConversionLosses.LostIccTooLarge => "Non tenuto: profilo ICC troppo grande", + ImageConversionLosses.LostExifTooLarge => "Non tenuto: EXIF troppo grande per JPG", + ImageConversionLosses.LostXmpTooLarge => "Non tenuto: XMP troppo grande", + ImageConversionLosses.LostExifUnreadable => "Non tenuto: EXIF rovinato", + ImageConversionLosses.LostIptc => "Non tenuti: IPTC", + ImageConversionLosses.LostOtherSegments => "Non tenuti: altri blocchi", + ImageConversionLosses.LostCommentTooLarge => "Non tenuto: commento troppo lungo", + ImageConversionLosses.LostExtendedXmp => "Non tenuto: XMP esteso", + Notes.LostVideoMetadata => "Non tenuti: metadati del video", + _ => null, }; /// «1 file copiato», «1.204 file copiati». diff --git a/src/Febe.Core/Import/ImportComparer.cs b/src/Febe.Core/Import/ImportComparer.cs index 03eff3b..f97e3bb 100644 --- a/src/Febe.Core/Import/ImportComparer.cs +++ b/src/Febe.Core/Import/ImportComparer.cs @@ -7,6 +7,9 @@ namespace Febe.Core.Import; /// What the comparison decided for one file. internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note); +/// A file of the source that is a converted copy of a library file; its original when known. +internal sealed record ConvertedCopyMatch(long? MediaId); + /// /// The comparison with the library (spec §9.3), for one analysis session. In this order: /// @@ -39,6 +42,9 @@ internal sealed class ImportComparer private readonly Dictionary _sourceIdentity = new(StringComparer.Ordinal); private readonly PerceptualHashIndex _sourceHashes = new(); + // The SHA-256 of the converted copies and frames written in destinations (one read per run, tappa E3, Q37). + private IReadOnlySet _copyShas = new HashSet(StringComparer.Ordinal); + private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func now) { _storage = storage; @@ -69,6 +75,7 @@ internal sealed class ImportComparer } var comparer = new ImportComparer(storage, library, now); + comparer._copyShas = await storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false); var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false); foreach (var entry in identifiers.Entries) { @@ -141,6 +148,13 @@ internal sealed class ImportComparer return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto); } + // A converted file of the library, or a converted copy or a frame of a destination: already in the library as + // its original, never a probable duplicate of it (tappa E3, Q37). + if (await IsConvertedCopyAsync(_storage, _copyShas, file.Sha256, ct).ConfigureAwait(false) is { } converted) + { + return new Comparison(ImportOutcome.AlreadyInLibrary, converted.MediaId, null, ImportText.NoteConvertedCopy); + } + // 2. Same bytes earlier in the source. if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id) { @@ -177,6 +191,21 @@ internal sealed class ImportComparer return new Comparison(ImportOutcome.New, null, null, null); } + /// + /// Whether is the SHA-256 of a converted file of the library (with its original's media + /// id) or of a converted copy or frame written in a destination (media id null); null when it is neither. + /// + internal static async Task IsConvertedCopyAsync(IFebeStorage storage, IReadOnlySet copyShas, string sha256, CancellationToken ct) + { + var conversions = await storage.Conversions.FindBySha256Async(sha256, ct).ConfigureAwait(false); + if (conversions.Count > 0) + { + return new ConvertedCopyMatch(conversions[0].MediaId); + } + + return copyShas.Contains(sha256) ? new ConvertedCopyMatch(null) : null; + } + private async Task MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct) { var candidates = new List<(EntryIdentity Entry, long? MediaId)>(); diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index e053946..c1b6e53 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -258,6 +258,14 @@ public sealed class ImportCopier(ImportEnvironment env) return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false); } + // A converted copy of a library file written since the analysis (tappa E3, Q37): never imported as a new file. + context.CopyShas ??= await env.Storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false); + if (file.EntryId is null && await ImportComparer.IsConvertedCopyAsync(env.Storage, context.CopyShas, file.Sha256!, ct).ConfigureAwait(false) is { } converted) + { + tally.Skipped++; + return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = converted.MediaId, LastError = ImportText.NoteConvertedCopy }).ConfigureAwait(false); + } + var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false) ?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella."); var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath)); @@ -790,7 +798,11 @@ public sealed class ImportCopier(ImportEnvironment env) } } - private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest); + private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest) + { + /// The SHA-256 of converted copies and frames in destinations, read once per run when first needed. + public IReadOnlySet? CopyShas { get; set; } + } private sealed class Tally { diff --git a/src/Febe.Core/Import/ImportText.cs b/src/Febe.Core/Import/ImportText.cs index 50f13fb..7fb5bdd 100644 --- a/src/Febe.Core/Import/ImportText.cs +++ b/src/Febe.Core/Import/ImportText.cs @@ -139,6 +139,9 @@ public static class ImportText internal const string NoteLargerInSource = "Hai scelto di tenere il più grande: è un altro file della sorgente, che prende il posto di quello in libreria."; internal const string NoteNotRecognized = "Né foto né video: ignorato."; internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato."; + + /// A converted file of the library, a converted copy or a frame written in a destination (tappa E3, Q37). + internal const string NoteConvertedCopy = "È una copia convertita (o un fotogramma) di un file già in libreria."; internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto."; internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella."; internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria."; diff --git a/src/Febe.Core/Library/Conversion/ConversionThrottle.cs b/src/Febe.Core/Library/Conversion/ConversionThrottle.cs new file mode 100644 index 0000000..6a41961 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/ConversionThrottle.cs @@ -0,0 +1,29 @@ +namespace Febe.Core.Library.Conversion; + +/// +/// One conversion at a time across the process (tappa E3, decision D16): a photo conversion holds a decoded picture +/// and its encoder state (up to about a gigabyte for 40 megapixels), so the export and the library conversion take +/// turns, each off the calling thread. +/// +public sealed class ConversionThrottle +{ + private readonly SemaphoreSlim gate = new(1, 1); + + /// The throttle every conversion of the process shares. + public static ConversionThrottle Shared { get; } = new(); + + /// Runs on the thread pool once no other conversion runs. + public async Task RunAsync(Func work, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(work); + await gate.WaitAsync(ct).ConfigureAwait(false); + try + { + return await Task.Run(() => work(ct), ct).ConfigureAwait(false); + } + finally + { + gate.Release(); + } + } +} diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs b/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs new file mode 100644 index 0000000..73374b2 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionQueue.cs @@ -0,0 +1,242 @@ +using System.Globalization; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; + +namespace Febe.Core.Library.Conversion; + +/// What «Anche i N già in libreria» would queue: files and the bytes of their originals («circa», D17). +public sealed record LibraryConversionPreview(int Files, long Bytes); + +/// +/// The queue of the conversion for the library (tappa E3, D15, WP2.2): what enters it and when. A new file enters after +/// its line of _febe.jsonl (); the files already in the library +/// only when Alberto answers «Anche i N già in libreria» to the question asked when the conversion is turned on (Q29); +/// a format turned off or changed empties its queue, the converted files stay where they are. +/// +public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock) +{ + /// «In pausa» (1): the worker converts nothing until it is resumed. + public const string PausedKey = "esportazione.libreria-sospesa"; + + /// + /// Since when (Unix milliseconds) the library format of photos is the one set now: «Solo i nuovi» means the files + /// stored in the library from then on (), the others only with «Anche i N». + /// + public const string PhotoSinceKey = "esportazione.libreria-formato-foto-dal"; + + /// As , for videos. + public const string VideoSinceKey = "esportazione.libreria-formato-video-dal"; + + private static readonly Lock SignalGate = new(); + private static TaskCompletionSource _signal = NewSignal(); + + /// The files «Anche i N già in libreria» would queue for the library formats of . + public Task PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + return PreviewExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct); + } + + /// + /// The files «Anche i N già in libreria» would queue in these formats, one per kind (null: that kind is not asked + /// about, as when only the other one is being turned on). + /// + public async Task PreviewExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default) + { + var (files, bytes) = await storage.Conversions.CountExistingAsync(photo, video, ct).ConfigureAwait(false); + return new LibraryConversionPreview(files, bytes); + } + + /// «Anche i N già in libreria» for both library formats of . Returns how many. + public Task EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + return EnqueueExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct); + } + + /// + /// «Anche i N già in libreria»: queues the present files that convert, in one statement per kind, only for the kinds + /// given (null: that kind keeps what was answered for it, «Solo i nuovi» included). Returns how many. + /// + public async Task EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default) + { + var added = await storage.Conversions.EnqueueExistingAsync(photo, video, clock.Now, ct).ConfigureAwait(false); + if (added > 0) + { + Signal(); + } + + return added; + } + + /// + /// Saves the settings (they were ) with what a change of a library + /// format brings, in one transaction: the format, since when it is set () and the + /// emptied queue of the format it replaces. A request aborted, a crash or a file stored at that moment never sees + /// the new format without its «dal» key, nor the old failures left behind (D17, Q29). + /// Turning one on queues nothing here: the interface asks, then calls only for + /// «Anche i N già in libreria». + /// + public Task SaveSettingsAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(before); + ArgumentNullException.ThrowIfNull(after); + var values = after.Values(); + var (since, formats) = Changes(before, after); + foreach (var (key, value) in since) + { + values[key] = value; + } + + return storage.Conversions.SaveSettingsAndDeleteQueuesAsync(values, formats, ct); + } + + /// + /// The settings were saved by another way: a library format turned off or changed loses its queue and its failures + /// that «Riprova» would put back (its converted files and rows stay), and its «dal» key is set, in one transaction. + /// stores the settings with them. + /// + public Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(before); + ArgumentNullException.ThrowIfNull(after); + var (since, formats) = Changes(before, after); + return since.Count == 0 ? Task.CompletedTask : storage.Conversions.SaveSettingsAndDeleteQueuesAsync(since, formats, ct); + } + + /// + /// For each kind whose library format changes: its «dal» key (now, or removed when it goes back to «Originale») and + /// the format replaced, whose queue goes. + /// + private (Dictionary Since, List Formats) Changes(ExportSettings before, ExportSettings after) + { + var since = new Dictionary(StringComparer.Ordinal); + var formats = new List(); + foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video }) + { + var old = LibraryConversionRules.FormatFor(kind, before); + var now = LibraryConversionRules.FormatFor(kind, after); + if (old == now) + { + continue; + } + + if (old is { } format) + { + formats.Add(format); + } + + // The files of the library before now are «già in libreria»: only «Anche i N» queues them. + since[SinceKey(kind)] = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture); + } + + return (since, formats); + } + + /// + /// «Riprova»: the failed files of the library formats set now go back to the queue, except those that never convert + /// (AsIs*). Returns how many. + /// + public async Task RetryFailedAsync(CancellationToken ct = default) + { + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var formats = new[] { MediaKind.Photo, MediaKind.Video } + .Select(kind => LibraryConversionRules.FormatFor(kind, settings)) + .OfType() + .ToList(); + var reset = await storage.Conversions.ResetFailedAsync(formats, clock.Now, ct).ConfigureAwait(false); + if (reset > 0) + { + Signal(); + } + + return reset; + } + + /// «In pausa» or not. + public static async Task IsPausedAsync(ISettingsStore settings, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + return await settings.GetAsync(PausedKey, ct).ConfigureAwait(false) == "1"; + } + + /// «Sospendi» / «Riprendi» the conversion for the library. + public async Task SetPausedAsync(bool paused, CancellationToken ct = default) + { + await storage.Settings.SetAsync(PausedKey, paused ? "1" : "0", ct).ConfigureAwait(false); + if (!paused) + { + Signal(); + } + } + + /// + /// Queues the new files of an entry by the library formats set now, after its journal line (the hook of + /// ): those stored in the library since the format was set (), + /// not the files an old entry already had when a late one arrives (they had their answer, «Solo i nuovi» included). + /// Nothing when both formats are «Originale». Returns how many rows were added. + /// + public static async Task EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList media, DateTimeOffset at, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(media); + // One read: the formats and their «dal» keys as one change stored them, never a format with an older key. + var values = await storage.Settings.GetAllAsync(ct).ConfigureAwait(false); + var settings = ExportSettings.From(values); + if (!settings.ConvertsLibrary) + { + return 0; + } + + var photoSince = Since(values, MediaKind.Photo); + var videoSince = Since(values, MediaKind.Video); + var requests = LibraryConversionRules.RequestsFor( + media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since + || (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)), + settings); + if (requests.Count == 0) + { + return 0; + } + + var added = await storage.Conversions.EnqueueAsync(requests, at, ct).ConfigureAwait(false); + if (added > 0) + { + Signal(); + } + + return added; + } + + private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey; + + /// Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new. + private static long? Since(IReadOnlyDictionary values, MediaKind kind) => + long.TryParse(values.GetValueOrDefault(SinceKey(kind)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null; + + /// Wakes the worker: something entered the queue (or the pause ended). + public static void Signal() + { + TaskCompletionSource fired; + lock (SignalGate) + { + fired = _signal; + _signal = NewSignal(); + } + + fired.TrySetResult(); + } + + /// A task that completes at the next . + internal static Task NextSignal() + { + lock (SignalGate) + { + return _signal.Task; + } + } + + private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously); +} diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionRules.cs b/src/Febe.Core/Library/Conversion/LibraryConversionRules.cs new file mode 100644 index 0000000..8defde5 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionRules.cs @@ -0,0 +1,66 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; + +namespace Febe.Core.Library.Conversion; + +/// +/// Which library files the conversion for the library queues (tappa E3, D15, WP2.2): a present file whose extension +/// says it converts into the format chosen for its kind ( is Converted). A file +/// already in that format, HEIC, HEIF, AVIF, raw, GIF and WebM are never queued. The same rule is written in SQL by the +/// store (). +/// +public static class LibraryConversionRules +{ + /// The format of the conversion for the library of a kind; null when it is off («Originale»). + public static ExportFormat? FormatFor(MediaKind kind, ExportSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + var format = kind == MediaKind.Photo ? settings.LibraryPhotoFormat : settings.LibraryVideoFormat; + var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format); + return format != ExportFormat.Original && fits ? format : null; + } + + /// True when a file at of is queued for . + public static bool Converts(string relativePath, MediaKind kind, ExportFormat format) + { + ArgumentNullException.ThrowIfNull(relativePath); + var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format); + return format != ExportFormat.Original && fits && ExportConversions.Predict(relativePath, kind, format) == ExportPrediction.Converted; + } + + /// + /// The extensions (with their dot, lower case) of the files that are not queued for : the + /// format's own and the ones copied as they are. Equivalent to on the extension. + /// + public static IReadOnlyList ExcludedExtensions(ExportFormat format) + { + var own = format switch + { + ExportFormat.Jpg => new[] { ".jpg", ".jpeg" }, + ExportFormat.Png => [".png"], + ExportFormat.WebpLossless => [".webp"], + ExportFormat.Mp4 => [".mp4"], + _ => throw new ArgumentOutOfRangeException(nameof(format), "La conversione della libreria ha un formato diverso dall'originale."), + }; + return [.. own, ".heic", ".heif", ".avif", ".gif", ".webm", .. MediaConverter.RawExtensionList.Select(e => e.ToLowerInvariant()).Order(StringComparer.Ordinal)]; + } + + /// The conversions to queue for the present files of an entry, by the settings now. + public static IReadOnlyList RequestsFor(IEnumerable media, ExportSettings settings) + { + ArgumentNullException.ThrowIfNull(media); + ArgumentNullException.ThrowIfNull(settings); + var list = new List(); + foreach (var m in media) + { + if (EntryStateRules.IsPresent(m.State) && m.Sha256 is { Length: 64 } sha && m.RelativePath is { } path + && FormatFor(m.Kind, settings) is { } format && Converts(path, m.Kind, format)) + { + list.Add(new MediaConversionRequest(m.Id, format, sha)); + } + } + + return list; + } +} diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionText.cs b/src/Febe.Core/Library/Conversion/LibraryConversionText.cs new file mode 100644 index 0000000..0d66ace --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionText.cs @@ -0,0 +1,72 @@ +using Febe.Core.Codecs.Images; +using Febe.Core.Export; + +namespace Febe.Core.Library.Conversion; + +/// +/// The codes of media_conversion.last_error (tappa E3, D19) and their Italian texts. A Failed row carries why it +/// failed (an AsIs* code first when the file never converts); a Converted row carries what was not kept. +/// +public static class LibraryConversionText +{ + /// The original is not in the library folder. + public const string SourceMissing = ExportText.Notes.SourceMissing; + + /// The original's bytes are not the ones recorded. + public const string SourceChanged = ExportText.Notes.SourceChanged; + + /// The account folder is not there (an unplugged disk): it is never created. + public const string AccountFolderMissing = "AccountFolderMissing"; + + /// The prefix of an unexpected failure; the exception's type name follows the colon. + public const string Error = "Error"; + + /// The prefix of the codes of files that never convert. + public const string AsIsPrefix = "AsIs"; + + /// «In pausa» for low space (D17). + public const string LowSpace = "Spazio libero sotto la soglia: la conversione della libreria è in pausa"; + + /// Waiting for the end of an engine session. + public const string InSession = "Il motore è in sessione: la conversione della libreria riprende dopo"; + + /// Waiting for an import, a copy or a rebuild. + public const string LongWork = "Un'importazione, una copia o una ricostruzione è al lavoro: la conversione della libreria riprende dopo"; + + /// True when the codes of a Failed row say the file never converts. + public static bool IsAsIs(string? codes) => codes is not null && codes.TrimStart().StartsWith(AsIsPrefix, StringComparison.Ordinal); + + /// The Italian text of a list of codes («·» between them); unknown codes are shown as they are. + public static string? Note(string? codes) + { + if (string.IsNullOrWhiteSpace(codes)) + { + return null; + } + + return string.Join(" · ", codes.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(One)); + } + + private static string One(string code) + { + var colon = code.IndexOf(':', StringComparison.Ordinal); + var name = colon < 0 ? code : code[..colon]; + return name switch + { + SourceMissing => "File non presente in libreria", + SourceChanged => "Il file della libreria non è quello registrato", + AccountFolderMissing => "La cartella dell'account non c'è: ricollega il disco e riprova", + Error => "Conversione non riuscita: riprova", + ImageConversionLosses.AsIsHeif => "Non si converte: HEIC", + ImageConversionLosses.AsIsAvif => "Non si converte: AVIF", + ImageConversionLosses.AsIsRaw => "Non si converte: raw", + ImageConversionLosses.AsIsAnimated => "Non si converte: immagine animata (perderebbe i fotogrammi dopo il primo)", + ImageConversionLosses.AsIsNotDecodable => "Non si converte: Febe non riesce a leggere l'immagine", + ImageConversionLosses.AsIsDeepColor => "Non si converte: più di 8 bit per colore", + ImageConversionLosses.AsIsCmyk => "Non si converte: immagine CMYK", + ImageConversionLosses.AsIsTooLarge => "Non si converte: troppo grande per il formato scelto", + MediaConversionResult.AsIsNotRemuxable => "Non si porta in MP4 senza ricodificarlo" + (ExportText.Note(code) is { } t && t.IndexOf('(', StringComparison.Ordinal) is var i and >= 0 ? " " + t[i..] : string.Empty), + _ => ExportText.Note(code) ?? code, + }; + } +} diff --git a/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs b/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs new file mode 100644 index 0000000..0424648 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/LibraryConversionWorker.cs @@ -0,0 +1,560 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; + +namespace Febe.Core.Library.Conversion; + +/// What the conversion for the library needs from the rest of Febe (tappa E3, WP2.2). +public sealed record LibraryConversionEnvironment +{ + public required IFebeStorage Storage { get; init; } + + /// The library folder and account folders now (on Windows it can change while Febe runs). + public required Func Layout { get; init; } + + public required IClock Clock { get; init; } + + /// Shared with import, export, rebuild and frame download, which pre-empt the conversion. Null: nothing to yield to (tests). + public LongWorkGate? Gate { get; init; } + + /// The conversion never runs during an engine session. + public IEngineSessionState Session { get; init; } = NoEngineSession.Instance; + + /// One conversion at a time in the process (D16): shared with the copies to external folders. + public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared; + + /// The free space of the disk of an account folder. + public IFreeSpaceProbe FreeSpace { get; init; } = new DriveFreeSpaceProbe(); + + /// Below this, once the file is written, the conversion pauses (D17): the alerts' «quasi pieno». + public DiskThresholds Thresholds { get; init; } = DiskThresholds.Default; + + /// How long the worker sleeps when nothing wakes it. + public TimeSpan Idle { get; init; } = TimeSpan.FromSeconds(30); + + /// How often it looks again while it waits for an engine session or a long work to end. + public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5); + + /// Rows read from the queue at a time. + public int BatchSize { get; init; } = 50; + + /// One line for the log: only Italian text and exception type names, never paths or messages. + public Action? Log { get; init; } + + /// Test seam: runs once the converted file is on disk, before its record. + public Func? AfterWrite { get; init; } +} + +/// The conversion for the library as the interface shows it. +/// Files in the queue. +/// Files converted. +/// Files that failed and can be tried again («Riprova»). +/// Files that never convert («non si convertono»). +/// «In pausa» by Alberto. +/// Why it waits now (an engine session, a long work, low space), or null. +/// The library file being converted now, or null. +public sealed record LibraryConversionStatus(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, long? CurrentMediaId); + +/// What one pass over the queue did. +/// Files converted (or adopted). +/// Rows settled: converted, dropped (already in the format), failed. +/// True when the pass stopped early and should look again soon (session, long work, pre-emption). +public sealed record LibraryConversionPass(int Converted, int Done, bool Again); + +/// +/// The conversion for the library (tappa E3, spec §4.10, D15-D18): adds, next to an original, the same file in the +/// format chosen for its kind, as a new file with the same stem and a free name. The original, its record, its +/// thumbnail, perceptual hash and journal line stay as they are; the converted file is only a media_conversion +/// row. It runs in the background through (started by the composition, never in the demo), +/// yields to import, export, rebuild and frame download (), never runs during +/// an engine session and pauses when the disk is almost full. +/// +public sealed class LibraryConversionWorker(LibraryConversionEnvironment env) +{ + private readonly LibraryConversionEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + private volatile string? _waiting; + private long _current; + + /// + /// The file that last paused the conversion for space, with the length its converted file needs: until the disk + /// has room for that too, the original is not read (hashed, decoded or remuxed) again at every wake-up (D17). + /// + private volatile LowSpaceMark? _lowSpace; + + private sealed record LowSpaceMark(long RowId, string SourceSha256, long Needed); + + /// The counts of the store with what the worker is doing now. + public async Task StatusAsync(CancellationToken ct = default) + { + var counts = await _env.Storage.Conversions.CountByStateAsync(ct).ConfigureAwait(false); + var paused = await LibraryConversionQueue.IsPausedAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + var current = Interlocked.Read(ref _current); + return new LibraryConversionStatus(counts.Pending, counts.Converted, counts.Failed, counts.AsIs, paused, paused ? null : _waiting, current == 0 ? null : current); + } + + /// + /// The loop: a pass over the queue, then a wait for or + /// . A failure of a pass is logged by type and the loop goes on; it + /// ends with . + /// + public async Task RunAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + var wait = _env.Idle; + try + { + var pass = await RunOnceAsync(ct).ConfigureAwait(false); + if (pass.Again) + { + wait = _env.Poll; + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + _env.Log?.Invoke($"La conversione della libreria si è fermata per un errore ({ex.GetType().Name}): riprova fra poco."); + } + + using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct); + var signal = LibraryConversionQueue.NextSignal(); + var delay = _env.Clock.Delay(wait, stop.Token); + await Task.WhenAny(signal, delay).ConfigureAwait(false); + await stop.CancelAsync().ConfigureAwait(false); + } + } + + /// One pass over the queue, in order, until it is empty or something stops it. + public async Task RunOnceAsync(CancellationToken ct = default) + { + var storage = _env.Storage; + if (await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false)) + { + _waiting = null; + return new LibraryConversionPass(0, 0, false); + } + + if (_env.Session.InSession) + { + _waiting = LibraryConversionText.InSession; + return new LibraryConversionPass(0, 0, true); + } + + if ((await storage.Conversions.ListPendingAsync(0, 1, ct).ConfigureAwait(false)).Count == 0) + { + _waiting = null; + return new LibraryConversionPass(0, 0, false); + } + + LongWorkGate.BackgroundLease? lease = null; + if (_env.Gate is { } gate && !gate.TryEnterBackground(out lease)) + { + _waiting = LibraryConversionText.LongWork; + return new LibraryConversionPass(0, 0, true); + } + + using (lease) + { + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease?.Preempted ?? CancellationToken.None); + var token = linked.Token; + _waiting = null; + var converted = 0; + var done = 0; + var after = 0L; + while (true) + { + var rows = await storage.Conversions.ListPendingAsync(after, _env.BatchSize, ct).ConfigureAwait(false); + if (rows.Count == 0) + { + return new LibraryConversionPass(converted, done, false); + } + + foreach (var row in rows) + { + after = row.Id; + if (token.IsCancellationRequested || _env.Session.InSession + || await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false)) + { + ct.ThrowIfCancellationRequested(); + return new LibraryConversionPass(converted, done, true); + } + + var outcome = await ConvertOneAsync(row, lease, token, ct).ConfigureAwait(false); + switch (outcome) + { + case Outcome.Converted: + converted++; + done++; + break; + case Outcome.Settled: + done++; + break; + case Outcome.LowSpace: + _waiting = LibraryConversionText.LowSpace; + return new LibraryConversionPass(converted, done, false); + case Outcome.Stopped: + ct.ThrowIfCancellationRequested(); + return new LibraryConversionPass(converted, done, true); + } + } + } + } + } + + private enum Outcome + { + Converted, + Settled, + Skipped, + LowSpace, + Stopped, + } + + private async Task ConvertOneAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token, CancellationToken ct) + { + Interlocked.Exchange(ref _current, row.MediaId); + try + { + return await ConvertAsync(row, lease, token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // Pre-empted, or Febe stops: our temporary file is gone, the row stays in the queue. + return Outcome.Stopped; + } + catch (Exception ex) + { + // One file never stops the queue: the reason goes to the row (codes, D19), the log gets the type only. + _env.Log?.Invoke($"Un file non si è convertito per la libreria ({ex.GetType().Name})."); + await FailAsync(row, $"{LibraryConversionText.Error}:{ex.GetType().Name}").ConfigureAwait(false); + ct.ThrowIfCancellationRequested(); + return Outcome.Settled; + } + finally + { + Interlocked.Exchange(ref _current, 0); + } + } + + private async Task ConvertAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token) + { + var storage = _env.Storage; + var media = await storage.Media.GetAsync(row.MediaId, token).ConfigureAwait(false); + if (media is null || !EntryStateRules.IsPresent(media.State) || media.RelativePath is null || media.Sha256 is not { Length: 64 }) + { + // Not in the library (deleted meanwhile, or never stored): nothing to convert. + await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false); + return Outcome.Skipped; + } + + // Only in the library format set now (§4.10, Q29): a row left in a format turned off or changed (put back by a + // supersession, say) is dropped, never converted. + var settings = await ExportSettings.LoadAsync(storage.Settings, token).ConfigureAwait(false); + if (LibraryConversionRules.FormatFor(media.Kind, settings) != row.Format) + { + await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false); + return Outcome.Skipped; + } + + var entry = await storage.Entries.GetAsync(media.EntryId, token).ConfigureAwait(false); + var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false); + if (entry is null || account is null) + { + await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false); + return Outcome.Skipped; + } + + var layout = _env.Layout(); + var folder = layout.AccountFolder(account); + if (!Directory.Exists(folder)) + { + // An unplugged disk of an account folder outside the library: never created again here. + await FailAsync(row, LibraryConversionText.AccountFolderMissing).ConfigureAwait(false); + return Outcome.Settled; + } + + var original = LibraryLayout.FullPath(folder, media.RelativePath); + if (!File.Exists(original)) + { + await FailAsync(row, LibraryConversionText.SourceMissing).ConfigureAwait(false); + return Outcome.Settled; + } + + // A disk already below the threshold stays below it with the file, and the file that paused the conversion last + // needs as much again: the pause holds before the original is read (hashed, decoded or remuxed) again at every + // wake-up (D17). The exact check with the file's length follows. + var source = media.Sha256.ToLowerInvariant(); + var needed = _lowSpace is { } mark && mark.RowId == row.Id && string.Equals(mark.SourceSha256, source, StringComparison.Ordinal) ? mark.Needed : 0; + if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before with { AvailableBytes = before.AvailableBytes - needed })) + { + return Outcome.LowSpace; + } + + if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal)) + { + row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now }; + await storage.Conversions.UpdateAsync(row, CancellationToken.None).ConfigureAwait(false); + } + + if (media.Kind == MediaKind.Video && !string.Equals(await HashAsync(original, token).ConfigureAwait(false), source, StringComparison.Ordinal)) + { + // A remux reads the file in pieces: its bytes are checked first (a photo is checked by the converter). + await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false); + return Outcome.Settled; + } + + MediaConversionResult result; + try + { + result = await MediaConverter.PrepareAsync(() => OpenRead(original), media.RelativePath, media.Kind, row.Format, source, _env.Throttle, token) + .ConfigureAwait(false); + } + catch (ContentChangedException) + { + await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false); + return Outcome.Settled; + } + + using (result) + { + if (result.Variant == ExportVariant.Whole) + { + if (result.Notes.Count == 0) + { + // Already in the format by its bytes (a «.png» that is a JPEG, to JPG): there is no file to add. + await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false); + } + else + { + // Animated, not decodable, CMYK, too large, not remuxable…: it never converts (terminal). + await FailAsync(row, ExportText.JoinNotes(result.Notes)).ConfigureAwait(false); + } + + return Outcome.Settled; + } + + if (_env.FreeSpace.Measure(folder) is { } space + && _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length })) + { + _lowSpace = new LowSpaceMark(row.Id, source, result.Length); + return Outcome.LowSpace; + } + + _lowSpace = null; + return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false); + } + } + + private async Task WriteAsync(MediaConversion row, Media media, Entry entry, Account account, string folder, LibraryLayout layout, + MediaConversionResult result, LongWorkGate.BackgroundLease? lease, CancellationToken token) + { + var storage = _env.Storage; + var relative = LibraryLayout.ToStored(media.RelativePath!); + var slash = relative.LastIndexOf('/'); + var directory = slash < 0 ? string.Empty : relative[..slash]; + var stem = WindowsFileNames.SplitExtension(relative[(slash + 1)..]).Stem; + var setTime = await SetFileTimeAsync(token).ConfigureAwait(false); + + FileDigest written = default; + string? adopted = null; + var preempted = false; + IDisposable? commit = null; + try + { + var writer = new SafeFileWriter(layout.MaxPathLength); + var saved = await writer.SaveAsync( + result.Produce, + folder, + directory, + async (digest, t) => + { + written = digest; + adopted = await FindAdoptableAsync(account, folder, layout, directory, stem, result.Extension, digest, t).ConfigureAwait(false); + if (lease is not null && !lease.TryBeginCommit(out commit)) + { + preempted = true; + return null; + } + + return adopted is null ? Join(directory, stem + result.Extension) : null; + }, + new SafeWriteOptions + { + RequireExistingRoot = true, + VerifyFromDisk = true, + LastWriteTime = setTime ? entry.PublishedAt : null, + }, + token).ConfigureAwait(false); + if (preempted) + { + return Outcome.Stopped; + } + + var path = adopted ?? saved!.RelativePath; + if (_env.AfterWrite is { } after) + { + await after(row, CancellationToken.None).ConfigureAwait(false); + } + + MediaConversionCommitOutcome outcome; + try + { + outcome = await storage.Conversions.CommitAsync( + new MediaConversionCommit(row.Id, media.Id, row.Format, row.SourceSha256, path, written.Bytes, written.Sha256, _env.Clock.Now, + ExportText.JoinNotes(result.Notes)), + CancellationToken.None).ConfigureAwait(false); + } + catch when (adopted is null) + { + DiscardOwn(folder, path, written.Sha256); + throw; + } + + if (outcome is MediaConversionCommitOutcome.Recorded or MediaConversionCommitOutcome.Upserted) + { + return Outcome.Converted; + } + + if (adopted is null) + { + // The entry was deleted (or the original replaced) while the file was written: the file just written + // belongs to nothing. It is this operation's own file, never one of the library: it goes. + DiscardOwn(folder, path, written.Sha256); + } + + return Outcome.Settled; + } + finally + { + commit?.Dispose(); + } + } + + /// + /// A file already at the path (or at one of its free names) with the conversion's SHA-256 that no library file and + /// no other conversion records: a conversion of an earlier run (or of a lost database) whose record is missing. Null + /// when there is none: the file is written with the next free name. Never by size alone (D10). + /// + private async Task FindAdoptableAsync(Account account, string folder, LibraryLayout layout, string directory, string stem, string extension, + FileDigest digest, CancellationToken ct) + { + for (var attempt = 1; attempt <= 50; attempt++) + { + var name = attempt == 1 ? stem + extension : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"); + var segments = Join(directory, WindowsFileNames.SanitizeSegment(name)).Split('/', StringSplitOptions.RemoveEmptyEntries); + var relative = string.Join('/', WindowsFileNames.FitPath(folder, segments, layout.MaxPathLength)); + string full; + try + { + full = LibraryLayout.FullPath(folder, relative); + } + catch (ArgumentException) + { + return null; + } + + var info = new FileInfo(full); + if (!info.Exists) + { + return null; + } + + if (info.Length == digest.Bytes + && string.Equals(await HashAsync(full, ct).ConfigureAwait(false), digest.Sha256, StringComparison.Ordinal) + && !await IsRecordedAsync(account, relative, digest.Sha256, ct).ConfigureAwait(false)) + { + return relative; + } + } + + return null; + } + + /// A library file of the account, or a live conversion of one, records this path (another entry's «x.jpg»). + private async Task IsRecordedAsync(Account account, string relative, string sha, CancellationToken ct) + { + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var media = await _env.Storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false); + if (media.Any(m => m.Entry.AccountId == account.Id && m.Media.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), relative, comparison))) + { + return true; + } + + foreach (var conversion in await _env.Storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false)) + { + if (conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded + && conversion.RelativePath is { } path && string.Equals(path, relative, comparison)) + { + var owner = await _env.Storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false); + var entry = owner is null ? null : await _env.Storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false); + if (entry?.AccountId == account.Id) + { + return true; + } + } + } + + return false; + } + + /// Deletes the file this conversion just wrote, only if it still has the bytes written (precedent: LibraryIngest). + private void DiscardOwn(string folder, string relative, string sha) + { + try + { + var full = LibraryLayout.FullPath(folder, relative); + if (File.Exists(full) && string.Equals(HashFile(full), sha, StringComparison.Ordinal)) + { + File.Delete(full); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + _env.Log?.Invoke($"Un file convertito per un elemento eliminato non si è potuto togliere ({ex.GetType().Name})."); + } + } + + private async Task FailAsync(MediaConversion row, string? codes) + { + try + { + await _env.Storage.Conversions.UpdateAsync( + row with { State = MediaConversionState.Failed, LastError = codes, StateChangedAt = _env.Clock.Now, RelativePath = null, Bytes = null, Sha256 = null, ConvertedAt = null }, + CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is KeyNotFoundException or DuplicateRecordException) + { + // The row went or changed meanwhile (a deletion, the setting turned off): nothing to record. + } + } + + private async Task SetFileTimeAsync(CancellationToken ct) + { + var text = await _env.Storage.Settings.GetAsync(SettingKeys.SetFileTimeToPublication, ct).ConfigureAwait(false); + return text is null || !bool.TryParse(text, out var parsed) || parsed; + } + + private static string Join(string directory, string name) => directory.Length == 0 ? name : directory + "/" + name; + + private static FileStream OpenRead(string path) => + new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess); + + private static async Task HashAsync(string path, CancellationToken ct) + { + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, + FileOptions.Asynchronous | FileOptions.SequentialScan); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); + } + + private static string HashFile(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.SequentialScan); + return Convert.ToHexStringLower(SHA256.HashData(stream)); + } +} diff --git a/src/Febe.Core/Library/Conversion/MediaConverter.cs b/src/Febe.Core/Library/Conversion/MediaConverter.cs new file mode 100644 index 0000000..cef71a8 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/MediaConverter.cs @@ -0,0 +1,220 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; + +namespace Febe.Core.Library.Conversion; + +/// +/// A library file ready to be written in a format (tappa E3, spec §4.10 «Conversione del formato»): what will be +/// written and how. Dispose it once written or given up. +/// +/// (the file byte for byte) or . +/// The effective format: for a whole file. +/// The extension of the file written, with its dot («.jpg»; a whole file keeps its own). +/// The bytes writes. +/// +/// The SHA-256 (lowercase hex) of what writes; null for a remux, known once written. +/// +/// Note codes: why the file is copied as it is, or what the conversion could not carry. +/// Writes the file into the stream given. +public sealed record MediaConversionResult(ExportVariant Variant, ExportFormat Format, string Extension, + long Length, string? Sha256, IReadOnlyList Notes, Func Produce) : IDisposable +{ + /// The note prefix of a video that cannot be remuxed; the follows the colon. + public const string AsIsNotRemuxable = "AsIsNotRemuxable"; + + /// Converted bytes or a remux plan, released on . + internal object? Held { get; set; } + + /// + public void Dispose() => Held = null; +} + +/// +/// Prepares a library file in a target format, independent of where it goes (an export destination, the library): +/// photos are converted in memory under the , videos are remuxed into MP4 while being +/// written. The source is never changed. +/// +public static class MediaConverter +{ + /// The raw camera formats, copied as they are (spec §4.10). + private static readonly HashSet RawExtensions = new(StringComparer.OrdinalIgnoreCase) + { + ".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw", + }; + + /// A raw camera format by its extension (with its dot), copied as it is. + public static bool IsRawExtension(string extension) => RawExtensions.Contains(extension); + + /// The raw camera extensions (with their dot, lower case), for rules written in SQL. + public static IReadOnlyCollection RawExtensionList => RawExtensions; + + /// + /// Prepares (only its name is used) in . + /// opens the source for reading, seekable; it may be called more than once. + /// + /// A photo's bytes do not have . + /// The target does not belong to the kind of file. + public static async Task PrepareAsync(Func openRandomAccess, string relativePath, + MediaKind kind, ExportFormat target, string expectedSourceSha256, ConversionThrottle throttle, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(openRandomAccess); + ArgumentException.ThrowIfNullOrEmpty(relativePath); + ArgumentException.ThrowIfNullOrEmpty(expectedSourceSha256); + ArgumentNullException.ThrowIfNull(throttle); + var valid = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(target) : ExportFormats.IsVideoFormat(target); + if (!valid) + { + throw new ArgumentException("Il formato non è adatto a questo tipo di file.", nameof(target)); + } + + return kind == MediaKind.Photo + ? await PreparePhotoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false) + : await PrepareVideoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false); + } + + /// The image format written for an export format; null for Original and MP4. + public static ImageFormat? ImageFormatOf(ExportFormat format) => format switch + { + ExportFormat.Jpg => ImageFormat.Jpeg, + ExportFormat.Png => ImageFormat.Png, + ExportFormat.WebpLossless => ImageFormat.WebP, + _ => null, + }; + + /// The extension of a converted file, with its dot. + public static string ExtensionOf(ExportFormat format) => format switch + { + ExportFormat.Jpg => ".jpg", + ExportFormat.Png => ".png", + ExportFormat.WebpLossless => ".webp", + ExportFormat.Mp4 => ".mp4", + _ => throw new ArgumentOutOfRangeException(nameof(format)), + }; + + private static async Task PreparePhotoAsync(Func open, string relativePath, + ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct) + { + var extension = Path.GetExtension(relativePath); + long length; + byte[]? bytes = null; + await using (var source = open()) + { + length = source.Length; + if (target != ExportFormat.Original && length <= ImageConverter.MaxSourceBytes) + { + bytes = new byte[length]; + await source.ReadExactlyAsync(bytes, ct).ConfigureAwait(false); + } + } + + if (bytes is null) + { + // Original, or too large to hold: the file byte for byte, checked against its SHA while written. + return Whole(open, extension, length, expected, target == ExportFormat.Original ? [] : [ImageConversionLosses.AsIsTooLarge]); + } + + var sha = Convert.ToHexStringLower(SHA256.HashData(bytes)); + if (!string.Equals(sha, expected, StringComparison.Ordinal)) + { + throw new ContentChangedException("Il file della libreria è cambiato durante la copia."); + } + + if (RawExtensions.Contains(extension)) + { + return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsRaw]); + } + + var format = ImageFormatOf(target)!.Value; + var check = ImageConverter.Check(bytes, format); + switch (check.Action) + { + case ImageConversionAction.CopyAsIs: + return Whole(bytes, extension, sha, []); + case ImageConversionAction.CopyOriginal: + return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []); + } + + var (converted, refusal) = await throttle.RunAsync((ImageConversionResult? Result, string? Refusal) (CancellationToken token) => + { + token.ThrowIfCancellationRequested(); + try + { + return (ImageConverter.Convert(bytes, format), null); + } + catch (ImageLimitException) + { + // Readable, but over what the decoder or the target allows: «troppo grande», never «non si legge». + return (null, ImageConversionLosses.AsIsTooLarge); + } + catch (ImageDecodeException) + { + return (null, ImageConversionLosses.AsIsNotDecodable); + } + }, ct).ConfigureAwait(false); + if (converted is null) + { + return Whole(bytes, extension, sha, [refusal!]); + } + + var data = converted.Data; + return new MediaConversionResult(ExportVariant.Converted, target, ExtensionOf(target), data.Length, + Convert.ToHexStringLower(SHA256.HashData(data)), converted.Losses, Writer(data)) + { + Held = data, + }; + } + + private static async Task PrepareVideoAsync(Func open, string relativePath, + ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct) + { + var extension = Path.GetExtension(relativePath); + var fileName = Path.GetFileName(relativePath); + var (length, refusal, plan) = await throttle.RunAsync(token => + { + using var source = open(); + var size = source.Length; + if (target == ExportFormat.Original) + { + return (size, RemuxRefusal.AlreadyMp4, (RemuxPlan?)null); + } + + var outcome = Mp4Remuxer.Check(source, fileName, out var made, token); + return (size, outcome, made); + }, ct).ConfigureAwait(false); + + if (refusal == RemuxRefusal.None && plan is not null) + { + return new MediaConversionResult(ExportVariant.Converted, ExportFormat.Mp4, ".mp4", plan.OutputLength, null, + plan.Losses, (output, token) => Task.Run( + () => + { + using var source = open(); + Mp4Remuxer.Write(plan, source, output, token); + }, + token)) + { + Held = plan, + }; + } + + string[] notes = refusal == RemuxRefusal.AlreadyMp4 ? [] : [$"{MediaConversionResult.AsIsNotRemuxable}:{refusal}"]; + return Whole(open, extension, length, expected, notes); + } + + /// A whole file streamed from the source (a video, or a photo not read into memory). + private static MediaConversionResult Whole(Func open, string extension, long length, string sha, IReadOnlyList notes) => + new(ExportVariant.Whole, ExportFormat.Original, extension, length, sha, notes, async (output, token) => + { + await using var source = open(); + await source.CopyToAsync(output, token).ConfigureAwait(false); + }); + + /// A whole photo from the bytes already read and checked. + private static MediaConversionResult Whole(byte[] bytes, string extension, string sha, IReadOnlyList notes) => + new(ExportVariant.Whole, ExportFormat.Original, extension, bytes.Length, sha, notes, Writer(bytes)) { Held = bytes }; + + private static Func Writer(byte[] data) => + (output, token) => output.WriteAsync(data, token).AsTask(); +} diff --git a/src/Febe.Core/Library/DownloadDuplicateReview.cs b/src/Febe.Core/Library/DownloadDuplicateReview.cs index 75e13e6..da5bb97 100644 --- a/src/Febe.Core/Library/DownloadDuplicateReview.cs +++ b/src/Febe.Core/Library/DownloadDuplicateReview.cs @@ -282,7 +282,12 @@ public sealed class DownloadDuplicateReview( } var folder = layout.AccountFolder(account); - await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false); + + // Its converted files of the library (tappa E3) go with it, in the transaction that deletes the file: the queue + // and the failures are dropped, the rows with a file become «Tolto» and their files are deleted below (one the + // worker records meanwhile is among them). No supersession for the loser. + var removed = await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false); + var withFiles = removed.Where(LibraryDeletion.HasFile).ToList(); await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false); hashIndex?.Remove(media.Id); var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList(); @@ -312,6 +317,14 @@ public sealed class DownloadDuplicateReview( } } + var failedConverted = new List(); + await LibraryDeletion.DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, [], [], failedConverted, ct).ConfigureAwait(false); + if (failedConverted.Count > 0) + { + var more = $"@{side.Username}, file convertiti: {string.Join("; ", failedConverted)}."; + problem = problem is null ? more : problem + " " + more; + } + if (thumbnails is not null && media.Sha256 is { } sha) { var users = await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false); diff --git a/src/Febe.Core/Library/LibraryDeletion.cs b/src/Febe.Core/Library/LibraryDeletion.cs index e560701..2ef90bc 100644 --- a/src/Febe.Core/Library/LibraryDeletion.cs +++ b/src/Febe.Core/Library/LibraryDeletion.cs @@ -31,6 +31,9 @@ public sealed record DeletionResult( IReadOnlyList FailedFiles) { public bool Complete => Found && FailedFiles.Count == 0; + + /// Converted files of the library (tappa E3) deleted with the originals; they are in too. + public int ConvertedFiles { get; init; } } /// @@ -69,14 +72,12 @@ public sealed class LibraryDeletion( await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none) .ConfigureAwait(false); - if (mode == DeletionMode.Remember) - { - await storage.Entries.MarkDeletedAsync(entryId, clock.Now, none).ConfigureAwait(false); - } - else - { - await storage.Entries.RemoveAsync(entryId, none).ConfigureAwait(false); - } + // The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them. + // Their rows are chosen in the transaction that deletes the entry: one the worker records meanwhile is among them. + var removed = mode == DeletionMode.Remember + ? await storage.Entries.MarkDeletedWithConversionsAsync(entryId, clock.Now, none).ConfigureAwait(false) + : await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false); + IReadOnlyList withFiles = removed.Where(HasFile).ToList(); foreach (var media in stored.Media) { @@ -108,6 +109,8 @@ public sealed class LibraryDeletion( } } + var converted = await DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, deleted, missing, failed, none).ConfigureAwait(false); + if (thumbnails is not null) { foreach (var sha in stored.Media.Select(m => m.Sha256).OfType().Distinct(StringComparer.Ordinal)) @@ -127,7 +130,89 @@ public sealed class LibraryDeletion( } } - return new DeletionResult(entryId, true, deleted, missing, failed); + return new DeletionResult(entryId, true, deleted, missing, failed) { ConvertedFiles = converted }; + } + + /// A conversion whose file is (or was last known to be) on disk. + internal static bool HasFile(MediaConversion c) => + c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null; + + /// + /// Deletes the converted files of conversions just removed or marked «Tolto», each only if no library file and no + /// live conversion still records its path and it still has the bytes recorded: a file replaced by Alberto stays and + /// is listed among the failures with its reason. Returns how many were deleted. + /// + internal static async Task DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList conversions, + List deleted, List missing, List failed, CancellationToken ct) + { + var count = 0; + foreach (var conversion in conversions) + { + var relative = conversion.RelativePath!; + try + { + var path = LibraryLayout.FullPath(folder, relative); + if (!File.Exists(path)) + { + missing.Add(relative); + continue; + } + + if (await IsStillRecordedAsync(storage, accountId, conversion, ct).ConfigureAwait(false)) + { + continue; // another file of the library has that name now: it is not this conversion's to delete + } + + if (!string.Equals(HashFile(path), conversion.Sha256, StringComparison.OrdinalIgnoreCase)) + { + failed.Add($"{relative}: il file convertito è cambiato dopo la conversione, quindi resta dov'è."); + continue; + } + + File.Delete(path); + deleted.Add(relative); + count++; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + failed.Add($"{relative}: {ex.Message}"); + } + } + + return count; + } + + private static async Task IsStillRecordedAsync(IFebeStorage storage, long accountId, MediaConversion conversion, CancellationToken ct) + { + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + var sha = conversion.Sha256!; + foreach (var m in await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false)) + { + if (m.Entry.AccountId == accountId && EntryStateRules.IsPresent(m.Media.State) && m.Media.RelativePath is { } p + && string.Equals(LibraryLayout.ToStored(p), conversion.RelativePath, comparison)) + { + return true; + } + } + + foreach (var other in await storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false)) + { + if (other.Id != conversion.Id && other.State is MediaConversionState.Converted or MediaConversionState.Superseded + && string.Equals(other.RelativePath, conversion.RelativePath, comparison) + && await storage.Media.GetAsync(other.MediaId, ct).ConfigureAwait(false) is { } owner + && (await storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false))?.AccountId == accountId) + { + return true; + } + } + + return false; + } + + private static string HashFile(string path) + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.SequentialScan); + return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream)); } /// Multiple selection: deletes each entry in turn. diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index 45b8dc3..2a9c155 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -3,6 +3,7 @@ using System.Globalization; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -371,6 +372,10 @@ public sealed class LibraryIngest( stored.Media, highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(), ct).ConfigureAwait(false); + + // The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line; the + // files the entry already had before the format was set wait for «Anche i N» (EnqueueEntryAsync). + await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false); } /// diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index a7915aa..f2a2833 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -1,7 +1,9 @@ +using System.Globalization; using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -61,6 +63,15 @@ public sealed record RebuildReport /// Files in account folders that no journal line mentions: left untouched, not added. public int UntrackedFiles { get; init; } + /// + /// Converted files of the library without a record (tappa E3): next to a file of the journal, with its name and in a + /// target format. Left untouched; queued again when the conversion for their kind is on with that format. + /// + public int ConversionsFound { get; init; } + + /// Converted files of the library still on disk for entries deleted «ricordando la scelta»: left untouched. + public int ConversionsOfDeletedEntries { get; init; } + public int InvalidLines { get; init; } /// A few examples of what needs attention (Italian), for the report screen. @@ -152,7 +163,7 @@ public sealed class LibraryRebuilder( var allItems = Fold(journal.Lines, report); // Entries already in the database are left as they are (deletions excepted): no hashing, no change. - var items = await SplitPresentAsync(account, allItems, report, ct).ConfigureAwait(false); + var items = await SplitPresentAsync(account, folder, allItems, report, ct).ConfigureAwait(false); // Verify files in parallel: hashing dominates the time. var live = items.Where(i => !i.Deleted).ToList(); @@ -198,11 +209,11 @@ public sealed class LibraryRebuilder( batch.Add((item, new NewEntry(entry, media))); if (batch.Count >= BatchSize) { - await FlushAsync(account, batch, report, ct).ConfigureAwait(false); + await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false); } } - await FlushAsync(account, batch, report, ct).ConfigureAwait(false); + await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false); // Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10). foreach (var (old, now) in report.Changed) @@ -211,14 +222,14 @@ public sealed class LibraryRebuilder( } report.Changed.Clear(); - CountUntracked(folder, allItems, report); + await CountUntrackedAsync(account, folder, allItems, report, ct).ConfigureAwait(false); } /// /// Returns the items that are not in the database yet. Items already present are counted; a remembered deletion /// is applied to them if the database still shows them. /// - private async Task> SplitPresentAsync(Account account, List items, Accumulator report, CancellationToken ct) + private async Task> SplitPresentAsync(Account account, string folder, List items, Accumulator report, CancellationToken ct) { var paths = await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false); var known = new HashSet<(EntryKind, string)>(); @@ -253,7 +264,7 @@ public sealed class LibraryRebuilder( : null; if (existing is not null && existing.State != EntryState.Deleted) { - await storage.Entries.MarkDeletedAsync(existing.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false); + await MarkDeletedAsync(folder, existing.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false); } } } @@ -582,7 +593,7 @@ public sealed class LibraryRebuilder( }; } - private async Task FlushAsync(Account account, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct) + private async Task FlushAsync(Account account, string folder, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct) { if (batch.Count == 0) { @@ -604,7 +615,7 @@ public sealed class LibraryRebuilder( report.EntriesAlreadyPresent++; if (item.Deleted && stored.Entry.State != EntryState.Deleted) { - await storage.Entries.MarkDeletedAsync(stored.Entry.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false); + await MarkDeletedAsync(folder, stored.Entry.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false); } } @@ -661,11 +672,98 @@ public sealed class LibraryRebuilder( State = MediaState.Deleted, }; - private static void CountUntracked(string folder, List items, Accumulator report) + /// + /// A remembered deletion found by the rebuild (tappa E3, WP2.4): the entry's conversions whose converted file is + /// missing become «Tolto»; those whose file is still on disk stay as they are (the rebuild never deletes a file) and + /// are counted. + /// + private async Task MarkDeletedAsync(string folder, long entryId, DateTimeOffset at, Accumulator report, CancellationToken ct) { + var missing = new List(); + foreach (var conversion in await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false)) + { + if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded) || conversion.RelativePath is not { } relative) + { + continue; + } + + if (ExistsIn(folder, relative)) + { + report.ConversionsOfDeletedEntries++; + } + else + { + missing.Add(conversion.Id); + } + } + + await storage.Entries.MarkDeletedAsync(entryId, at, missing, ct).ConfigureAwait(false); + } + + private static bool ExistsIn(string folder, string relative) + { + try + { + return File.Exists(LibraryLayout.FullPath(folder, relative)); + } + catch (ArgumentException) + { + return false; + } + } + + /// The format a converted file of the library has, by its extension; null for any other file. + private static ExportFormat? ConvertedFormatOf(string extension) => extension.ToLowerInvariant() switch + { + ".jpg" or ".jpeg" => ExportFormat.Jpg, + ".png" => ExportFormat.Png, + ".webp" => ExportFormat.WebpLossless, + ".mp4" => ExportFormat.Mp4, + _ => null, + }; + + /// «nome (2)» → «nome»: the free names the conversion for the library gives. + private static string WithoutNumber(string stem) + { + var open = stem.LastIndexOf(" (", StringComparison.Ordinal); + if (open > 0 && stem.EndsWith(')') + && int.TryParse(stem.AsSpan(open + 2, stem.Length - open - 3), NumberStyles.None, CultureInfo.InvariantCulture, out _)) + { + return stem[..open]; + } + + return stem; + } + + /// + /// Counts the files of the account folder that no journal line mentions (left untouched). The converted files of the + /// library (tappa E3) are not unknown: those with a row are skipped; one without a row, next to a file of the + /// journal with its stem and in a target format, is counted apart and, when the conversion for that kind is on with + /// that format, its file is queued again (a Pending row: the worker adopts the file by its SHA-256). Nothing is + /// converted during the rebuild. + /// + private async Task CountUntrackedAsync(Account account, string folder, List items, Accumulator report, CancellationToken ct) + { + var comparer = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; var known = new HashSet( items.SelectMany(i => i.Files.Values.Concat(i.Removed.Values)).Select(f => LibraryLayout.ToStored(f.Path)), - OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + comparer); + foreach (var path in await storage.Conversions.ListPathsByAccountAsync(account.Id, ct).ConfigureAwait(false)) + { + known.Add(path); + } + + // Files of the journal by folder and stem, for the converted files next to them. + var byStem = new Dictionary(comparer); + foreach (var file in items.Where(i => !i.Deleted).SelectMany(i => i.Files.Values)) + { + var stored = LibraryLayout.ToStored(file.Path); + var slash = stored.LastIndexOf('/'); + byStem.TryAdd((slash < 0 ? string.Empty : stored[..(slash + 1)]) + WindowsFileNames.SplitExtension(stored[(slash + 1)..]).Stem, file); + } + + ExportSettings? settings = null; + IReadOnlyDictionary? paths = null; foreach (var file in Directory.EnumerateFiles(folder, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true })) { var name = Path.GetFileName(file); @@ -675,11 +773,56 @@ public sealed class LibraryRebuilder( } var relative = LibraryLayout.ToStored(Path.GetRelativePath(folder, file)); - if (!known.Contains(relative)) + if (known.Contains(relative)) { - report.UntrackedFiles++; - report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}"); + continue; } + + var slash = relative.LastIndexOf('/'); + var (stem, extension) = WindowsFileNames.SplitExtension(relative[(slash + 1)..]); + var key = (slash < 0 ? string.Empty : relative[..(slash + 1)]) + WithoutNumber(stem); + if (ConvertedFormatOf(extension) is { } format && byStem.TryGetValue(key, out var original)) + { + report.ConversionsFound++; + try + { + settings ??= await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + paths ??= await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false); + await QueueFoundAsync(original, format, settings, paths, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is DuplicateRecordException or KeyNotFoundException or ArgumentException) + { + // Counted, never thrown: the worker or a later rebuild finds it again. + } + + continue; + } + + report.UntrackedFiles++; + report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}"); + } + } + + /// Queues the journal file in when its conversion is on with that format. + private async Task QueueFoundAsync(JournalFile original, ExportFormat format, ExportSettings settings, IReadOnlyDictionary paths, CancellationToken ct) + { + var stored = LibraryLayout.ToStored(original.Path); + if (!paths.TryGetValue(stored, out var entryId)) + { + return; + } + + var media = (await storage.Media.ListByEntryAsync(entryId, ct).ConfigureAwait(false)) + .FirstOrDefault(m => m.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), stored, StringComparison.Ordinal)); + if (media is null || LibraryConversionRules.FormatFor(media.Kind, settings) != format) + { + return; + } + + var requests = LibraryConversionRules.RequestsFor([media], settings); + if (requests.Count > 0) + { + await storage.Conversions.EnqueueAsync(requests, clock.Now, ct).ConfigureAwait(false); } } @@ -746,6 +889,10 @@ public sealed class LibraryRebuilder( public int UntrackedFiles { get; set; } + public int ConversionsFound { get; set; } + + public int ConversionsOfDeletedEntries { get; set; } + public int InvalidLines { get; set; } /// (journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato». @@ -773,6 +920,8 @@ public sealed class LibraryRebuilder( FilesUnreadable = FilesUnreadable, HashMismatches = HashMismatches, UntrackedFiles = UntrackedFiles, + ConversionsFound = ConversionsFound, + ConversionsOfDeletedEntries = ConversionsOfDeletedEntries, InvalidLines = InvalidLines, Notes = _notes, }; diff --git a/src/Febe.Core/Library/SafeFileWriter.cs b/src/Febe.Core/Library/SafeFileWriter.cs index 244e9f9..9455414 100644 --- a/src/Febe.Core/Library/SafeFileWriter.cs +++ b/src/Febe.Core/Library/SafeFileWriter.cs @@ -42,6 +42,12 @@ public sealed record SafeWriteOptions /// is removed and an says so. /// public bool VerifyFromDisk { get; init; } + + /// + /// The end of the stem of the file name that a shortening or a free name never cuts (the frame suffix of tappa + /// E3, «_t0m12s340»): a free name is «nome_t0m12s340 (2).png», as ExportPaths.NumberedName gives it. + /// + public string? KeepSuffix { get; init; } } /// The content exceeded ; nothing was kept. @@ -164,6 +170,38 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(source); + return await SaveCoreAsync((path, o, token) => WriteTempAsync(source, path, o, token), rootFolder, tempDirectory, decide, options, ct) + .ConfigureAwait(false); + } + + /// + /// As , + /// for content that is made while it is written (a converted photo, a remuxed video, a frame): + /// writes it into the temporary file, through a stream that hashes and counts it (and honours + /// and ); then the same checks, + /// and the free-name rename. Our own temporary file is removed on any failure. + /// + public async Task SaveAsync( + Func produce, + string rootFolder, + string tempDirectory, + Func> decide, + SafeWriteOptions? options = null, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(produce); + return await SaveCoreAsync((path, o, token) => ProduceTempAsync(produce, path, o, token), rootFolder, tempDirectory, decide, options, ct) + .ConfigureAwait(false); + } + + private async Task SaveCoreAsync( + Func> write, + string rootFolder, + string tempDirectory, + Func> decide, + SafeWriteOptions? options, + CancellationToken ct) + { ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder); ArgumentNullException.ThrowIfNull(decide); options ??= new SafeWriteOptions(); @@ -180,7 +218,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL try { - var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false); + var digest = await write(tempPath, options, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); if (options.VerifyFromDisk) { @@ -194,7 +232,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL } ct.ThrowIfCancellationRequested(); - var finalPath = MoveToFreeName(tempPath, root, desired, out var relative); + var finalPath = MoveToFreeName(tempPath, root, desired, options.KeepSuffix, out var relative); var timeSet = true; if (options.LastWriteTime is { } time) { @@ -289,6 +327,93 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset())); } + private static async Task ProduceTempAsync(Func produce, string tempPath, SafeWriteOptions options, CancellationToken ct) + { + await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous); + using var hashing = new HashingStream(target, options); + await produce(hashing, ct).ConfigureAwait(false); + ct.ThrowIfCancellationRequested(); + await target.FlushAsync(ct).ConfigureAwait(false); + target.Flush(flushToDisk: true); + return hashing.Digest(); + } + + /// A write-only stream that hashes and counts what goes through it into the temporary file. + private sealed class HashingStream(Stream inner, SafeWriteOptions options) : Stream + { + private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + private long total; + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public override long Length => total; + + public override long Position + { + get => total; + set => throw new NotSupportedException(); + } + + public FileDigest Digest() => new(total, Convert.ToHexStringLower(hash.GetHashAndReset())); + + public override void Flush() => inner.Flush(); + + public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken); + + 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(); + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + Count(buffer); + inner.Write(buffer); + options.Progress?.Report(total); + } + + public override void WriteByte(byte value) => Write([value]); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + Count(buffer.Span); + await inner.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); + options.Progress?.Report(total); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + hash.Dispose(); + } + + base.Dispose(disposing); + } + + private void Count(ReadOnlySpan buffer) + { + total += buffer.Length; + if (options.MaxBytes is { } max && total > max) + { + throw new FileTooLargeException( + string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato.")); + } + + hash.AppendData(buffer); + } + } + /// Reads the temporary file back and compares its SHA-256 with the one computed while writing. private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct) { @@ -316,7 +441,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments; } - private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative) + private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, string? keepSuffix, out string relative) { var segments = Segments(desiredRelativePath); var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); @@ -324,7 +449,8 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL { var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"); var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList(); - var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength); + var keep = keepSuffix is null ? null : attempt == 1 ? keepSuffix : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})"); + var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength, keep); relative = string.Join('/', fitted); var finalPath = LibraryLayout.FullPath(root, relative); Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!); diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index 261bfcf..93e26e4 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -58,7 +58,7 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff /// (, ). Videos in other codecs (VP9, AV1, ...) give no frame: the /// interface shows the neutral tile. /// -public sealed class VideoFrameDecoder +public sealed partial class VideoFrameDecoder { /// Differences up to this value (0–255) count as compression noise of a still picture. public const double StillThreshold = 3.0; @@ -77,8 +77,6 @@ public sealed class VideoFrameDecoder /// How far back from a sample flagged as key the decoder looks for one it can really start from. private const int MaxRunStartSearch = 2000; - private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero); - private readonly TimeSpan budget; private readonly int maxRun; @@ -184,10 +182,10 @@ public sealed class VideoFrameDecoder // The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture // of the HEVC CRA picture decoding starts from, a damaged sample). - var frames = decoding.Decode(start < target ? [start, target] : [target], ct); + var frames = decoding.DecodeAll(start < target ? [start, target] : [target], ct); if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0) { - frames = new Decoding(stream, video, maxRun).Decode([0], ct); + frames = new Decoding(stream, video, maxRun).DecodeAll([0], ct); frames.TryGetValue(0, out frame); } @@ -248,7 +246,7 @@ public sealed class VideoFrameDecoder return null; } - var frames = decoding.Decode([.. targets], ct); + var frames = decoding.DecodeAll([.. targets], ct); if (frames.Count < 2) { return null; @@ -295,7 +293,7 @@ public sealed class VideoFrameDecoder private static VideoTrack? Open(Stream stream) { // The creation time does not matter here: any date is accepted (the readers add a day to «now»). - var container = ContainerReader.Read(stream, AnyDate, samples: true); + var container = ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true); return container?.Video is { Samples.Count: > 0 } video && video.Codec switch { VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null, @@ -362,6 +360,13 @@ public sealed class VideoFrameDecoder /// Exact: an H.264 IDR picture, an HEVC IDR or BLA picture. Idr, + + /// + /// Exact for the pictures shown from it on: an HEVC CRA picture (only its RASL pictures, shown before it, are + /// lost), an H.264 I picture with a recovery point SEI whose recovery_frame_cnt is 0. Elsewhere close, as + /// . + /// + Recovery, } /// Size of the NAL length fields of the samples (0: Annex B), from the configuration record. @@ -436,9 +441,11 @@ public sealed class VideoFrameDecoder /// /// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it. /// - private sealed class Decoding(Stream stream, VideoTrack video, int maxRun) + private sealed class Decoding(Stream stream, VideoTrack video, int maxRun, bool exact = false) { private readonly Dictionary found = []; + private readonly HashSet produced = []; + private readonly List<(int Sample, Frame Frame)> pending = []; private readonly HashSet wanted = []; private readonly int[] keys = KeyIndices(video); private readonly Dictionary accessPoints = []; @@ -458,6 +465,11 @@ public sealed class VideoFrameDecoder /// internal int RunStart(int index) { + if (exact) + { + return ExactStart(index); + } + var position = Array.BinarySearch(keys, index); position = position >= 0 ? position : Math.Max(0, ~position - 1); var intra = -1; @@ -475,7 +487,7 @@ public sealed class VideoFrameDecoder return index - candidate <= maxRun || intra < 0 ? candidate : intra; } - if (point == StartPoint.Intra && intra < 0) + if (point is StartPoint.Intra or StartPoint.Recovery && intra < 0) { intra = candidate; } @@ -490,6 +502,34 @@ public sealed class VideoFrameDecoder return index <= maxRun || intra < 0 ? 0 : intra; } + /// + /// The nearest start from which comes out exact, however far: an IDR picture, or a + /// recovery point shown no later than it; otherwise the first sample. + /// + private int ExactStart(int index) + { + var position = Array.BinarySearch(keys, index); + position = position >= 0 ? position : Math.Max(0, ~position - 1); + var shown = video.Samples[index].PresentationTime; + for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++) + { + var candidate = keys[position]; + if (!accessPoints.TryGetValue(candidate, out var point)) + { + point = AccessPointOf(candidate); + accessPoints[candidate] = point; + } + + if (point == StartPoint.Idr + || (point == StartPoint.Recovery && shown >= video.Samples[candidate].PresentationTime)) + { + return candidate; + } + } + + return 0; + } + private StartPoint AccessPointOf(int index) { try @@ -500,7 +540,7 @@ public sealed class VideoFrameDecoder return H265Decoder.AccessPoint(sample, lengthSize) switch { H265AccessPoint.Idr => StartPoint.Idr, - H265AccessPoint.Cra => StartPoint.Intra, + H265AccessPoint.Cra => StartPoint.Recovery, _ => StartPoint.None, }; } @@ -508,6 +548,7 @@ public sealed class VideoFrameDecoder return H264Decoder.AccessPoint(sample, lengthSize) switch { H264AccessPoint.Idr => StartPoint.Idr, + H264AccessPoint.IntraPicture when H264Decoder.HasExactRecoveryPoint(sample, lengthSize) => StartPoint.Recovery, H264AccessPoint.IntraPicture => StartPoint.Intra, _ => StartPoint.None, }; @@ -518,7 +559,25 @@ public sealed class VideoFrameDecoder } } - internal Dictionary Decode(int[] targets, CancellationToken ct) + /// + /// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a + /// stillness check asks for. + /// + internal Dictionary DecodeAll(int[] targets, CancellationToken ct) + { + foreach (var (sample, frame) in Decode(targets, ct)) + { + found.TryAdd(sample, frame); + } + + return found; + } + + /// + /// Decodes the targets (sample indices in ascending order) and hands out each frame as soon as the sample that + /// finishes it is decoded, in decoding order, once per sample; a target that gives no picture is left out. + /// + internal IEnumerable<(int Sample, Frame Frame)> Decode(int[] targets, CancellationToken ct) { foreach (var t in targets) { @@ -536,29 +595,56 @@ public sealed class VideoFrameDecoder next = key; } - try + for (; next <= target; next++) { - // Frames are matched to samples by the sample being decoded, not by the decoder's own count: a - // sample without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift - // the frames after it. - runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame)); - for (; next <= target; next++) + ct.ThrowIfCancellationRequested(); + if (!Step(ref runner, next)) { - ct.ThrowIfCancellationRequested(); - current = next; - runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer)); + // This run is damaged (or its samples lie past the end of a truncated file): the next target + // starts again from its own key frame, and what was decoded so far stands. + runner = null; + } + + foreach (var item in pending) + { + yield return item; + } + + pending.Clear(); + if (runner is null) + { + break; } } - catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException - or IndexOutOfRangeException or ArgumentException or InvalidOperationException) - { - // This run is damaged (or its samples lie past the end of a truncated file): the next target starts - // again from its own key frame, and what was decoded so far stands. - runner = null; - } } + } - return found; + /// Decodes one sample; false when the stream is damaged there. + private bool Step(ref Runner? runner, int sample) + { + try + { + // Frames are matched to samples by the sample being decoded, not by the decoder's own count: a sample + // without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift the frames + // after it. + runner ??= new Runner(video, () => wanted.Contains(current), Found); + current = sample; + runner.Decode(ContainerReader.ReadSample(stream, video.Samples[sample], ref buffer)); + return true; + } + catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException + or IndexOutOfRangeException or ArgumentException or InvalidOperationException) + { + return false; + } + } + + private void Found(Frame frame) + { + if (produced.Add(current)) + { + pending.Add((current, frame)); + } } } diff --git a/src/Febe.Core/Library/VideoFrames.cs b/src/Febe.Core/Library/VideoFrames.cs new file mode 100644 index 0000000..f941390 --- /dev/null +++ b/src/Febe.Core/Library/VideoFrames.cs @@ -0,0 +1,348 @@ +using Febe.Core.Codecs; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.Images; +using YuvToRgb = Febe.Core.Codecs.YuvToRgb; + +namespace Febe.Core.Library; + +/// What found about a video. +/// False when no frame can be taken from it: says why. +/// The Italian message shown when frames are not available; null otherwise. +/// The presentation length (zero when unknown). +/// Width of a frame as shown (rotation applied). +/// Height of a frame as shown (rotation applied). +/// Clockwise rotation of the track: 0, 90, 180 or 270. +/// The video codec («H264», «Hevc»), or the container's codec tag of one Febe does not decode. +/// The mean time between two frames (zero when unknown). +/// Whether the container has an audio track. +/// Samples of the video track. +public sealed record VideoFrameInfo(bool Available, string? Unavailable, TimeSpan Duration, int Width, int Height, + int Rotation, string Codec, TimeSpan FrameDuration, bool HasAudio, int SampleCount); + +/// A frame to take: the instant asked for and the sample really shown then (spec §4.10 «Fotogrammi»). +/// Position of the instant in the request (0-based), which names the file. +/// The instant asked for. +/// +/// When the sample is shown, rounded up to the next 100 ns tick: what the frame's identity and name carry. +/// +/// The sample index in decoding order. +public sealed record VideoFrameTarget(int Index, TimeSpan Requested, TimeSpan Actual, int Sample); + +/// A decoded frame, upright, in 8-bit RGBA (alpha 255). Dispose it to give the pixels back. +public sealed class VideoFrame(int index, TimeSpan requested, TimeSpan actual, RgbaImage image) : IDisposable +{ + /// Position of the instant in the request. + public int Index { get; } = index; + + /// The instant asked for. + public TimeSpan Requested { get; } = requested; + + /// When the frame is shown. + public TimeSpan Actual { get; } = actual; + + /// The pixels, rotated as the video is shown. + public RgbaImage Image { get; } = image; + + /// + public void Dispose() => Image.Dispose(); +} + +/// +/// Frames of a video at chosen instants, at full resolution and exact (spec §4.10 «Fotogrammi»): instants are the +/// presentation times as a player shows them (ISO edit lists included), each frame decoded from a point the decoder can +/// start from exactly, and turned upright. One frame lives in memory at a time; the stream must stay open and seekable +/// while the reader is used. +/// +public sealed class VideoFrameReader : IDisposable +{ + /// The message for a video whose frames Febe cannot take. + public const string NotAvailableMessage = "Fotogramma non disponibile per questo video"; + + private readonly Stream? stream; + private readonly VideoTrack? video; + + /// Shown time of each sample in track units (presentation time plus the empty edits). + private readonly long[] shown = []; + + /// The samples that can be chosen, by shown time then decoding order. + private readonly int[] order = []; + + private VideoFrameReader(Stream? stream, VideoTrack? video) + { + this.stream = stream; + this.video = video; + if (video is null) + { + return; + } + + var samples = video.Samples; + shown = new long[samples.Count]; + for (var i = 0; i < samples.Count; i++) + { + shown[i] = samples[i].PresentationTime + video.EmptyEditDuration; + } + + // Samples shown before the start or from the end of the edit on (cut by the edit list) are not chosen, unless + // nothing else is. + var end = video.EditSegmentDuration is { } segment && segment > 0 ? video.EmptyEditDuration + segment : long.MaxValue; + var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0 && shown[i] < end).ToArray(); + order = visible.Length > 0 ? visible : [.. Enumerable.Range(0, samples.Count)]; + Array.Sort(order, (a, b) => shown[a] != shown[b] ? shown[a].CompareTo(shown[b]) : a.CompareTo(b)); + } + + /// + /// Opens the video in (left open: the caller disposes it after the reader). Never + /// throws for a video it cannot read: is then not available, and the reader gives no frame. + /// + public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info) + { + ArgumentNullException.ThrowIfNull(seekable); + MediaContainer? container; + VideoTrack? video; + try + { + seekable.Position = 0; + container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true); + video = container is null ? null : VideoFrameDecoder.FrameTrack(container); + } + catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex)) + { + container = null; + video = null; + } + + if (container?.Video is not { } track || video is null) + { + var v = container?.Video; + info = new VideoFrameInfo(false, NotAvailableMessage, container?.Duration ?? TimeSpan.Zero, + v?.DisplayWidth ?? 0, v?.DisplayHeight ?? 0, v?.Rotation ?? 0, v is null ? string.Empty : Codec(v), + TimeSpan.Zero, container?.Audio is not null, v?.Samples.Count ?? 0); + return new VideoFrameReader(null, null); + } + + var reader = new VideoFrameReader(seekable, video); + info = new VideoFrameInfo(true, null, reader.Duration(container), track.DisplayWidth, track.DisplayHeight, + Rotation(track.Rotation), Codec(track), reader.FrameDuration(), container.Audio is not null, track.Samples.Count); + return reader; + } + + /// The length of the video from its headers only (no sample table walked through); null when unreadable. + public static TimeSpan? ProbeDuration(Stream seekable) + { + ArgumentNullException.ThrowIfNull(seekable); + try + { + seekable.Position = 0; + return ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: false)?.Duration; + } + catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex)) + { + return null; + } + } + + /// + /// The sample shown at each instant: the one with the greatest shown time not after it; the first one for an + /// instant before it, the last one for an instant past the end. Empty when the video is not available. + /// + public IReadOnlyList Locate(IReadOnlyList instants) + { + ArgumentNullException.ThrowIfNull(instants); + if (video is null || order.Length == 0) + { + return []; + } + + var targets = new VideoFrameTarget[instants.Count]; + for (var i = 0; i < instants.Count; i++) + { + var sample = SampleAt(instants[i]); + targets[i] = new VideoFrameTarget(i, instants[i], ShownAt(sample), sample); + } + + return targets; + } + + /// + /// Decodes the targets lazily, in decoding order (not the order of the instants): each frame comes out as soon as it + /// is decoded and must be disposed by the caller. A target whose sample gives no picture (a damaged stream) is left + /// out; targets on the same sample each get their own copy. + /// + public IEnumerable Decode(IReadOnlyList targets, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(targets); + return video is null || stream is null || targets.Count == 0 ? [] : DecodeCore(targets, ct); + } + + private IEnumerable DecodeCore(IReadOnlyList targets, CancellationToken ct) + { + var bySample = targets.Where(t => t.Sample >= 0 && t.Sample < shown.Length) + .GroupBy(t => t.Sample) + .ToDictionary(g => g.Key, g => g.OrderBy(t => t.Index).ToArray()); + int[] samples = [.. bySample.Keys.Order()]; + foreach (var (sample, image) in VideoFrameDecoder.DecodeExact(stream!, video!, samples, ct)) + { + var wanted = bySample[sample]; + for (var i = 0; i < wanted.Length; i++) + { + var copy = i == wanted.Length - 1 ? image : new RgbaImage(image.Width, image.Height, image.ToArray()); + yield return new VideoFrame(wanted[i].Index, wanted[i].Requested, wanted[i].Actual, copy); + } + } + } + + /// + public void Dispose() + { + // The stream belongs to the caller; nothing else is held. + } + + private int SampleAt(TimeSpan at) + { + // Exact comparison of at (100 ns ticks) with a shown time (track units): at·timescale against shown·10⁷. + var timescale = (Int128)video!.Timescale; + var wanted = (Int128)at.Ticks * timescale; + int low = 0, high = order.Length - 1, best = -1; + while (low <= high) + { + var middle = (low + high) / 2; + if ((Int128)shown[order[middle]] * TimeSpan.TicksPerSecond <= wanted) + { + best = middle; + low = middle + 1; + } + else + { + high = middle - 1; + } + } + + if (best < 0) + { + return order[0]; + } + + // Among samples shown at the same time, the first in decoding order. + while (best > 0 && shown[order[best - 1]] == shown[order[best]]) + { + best--; + } + + return order[best]; + } + + /// The shown time of a sample as a TimeSpan, rounded up to the tick (never before it is shown). + private TimeSpan ShownAt(int sample) + { + var timescale = (Int128)Math.Max(1, video!.Timescale); + var units = (Int128)Math.Max(0, shown[sample]); + var ticks = ((units * TimeSpan.TicksPerSecond) + timescale - 1) / timescale; + return TimeSpan.FromTicks((long)Int128.Min(ticks, TimeSpan.MaxValue.Ticks)); + } + + private TimeSpan Duration(MediaContainer container) + { + if (container.Duration is { } d && d > TimeSpan.Zero) + { + return d; + } + + if (video!.Duration > 0 && video.Timescale > 0) + { + return TimeSpan.FromTicks((long)((Int128)video.Duration * TimeSpan.TicksPerSecond / video.Timescale)); + } + + return order.Length == 0 ? TimeSpan.Zero : ShownAt(order[^1]) + FrameDuration(); + } + + private TimeSpan FrameDuration() + { + if (order.Length < 2 || video!.Timescale <= 0) + { + return TimeSpan.Zero; + } + + var span = (Int128)(shown[order[^1]] - shown[order[0]]) * TimeSpan.TicksPerSecond; + return TimeSpan.FromTicks((long)(span / video.Timescale / (order.Length - 1))); + } + + private static int Rotation(int rotation) => ((rotation % 360) + 360) % 360 is var r && r is 90 or 180 or 270 ? r : 0; + + private static string Codec(VideoTrack video) => + video.Codec is VideoCodec.H264 or VideoCodec.Hevc ? video.Codec.ToString() : video.CodecTag; +} + +/// The frames part of the decoder: what needs of its private machinery. +public sealed partial class VideoFrameDecoder +{ + /// The track frames can be taken from: H.264 or HEVC with its samples and configuration; else null. + internal static VideoTrack? FrameTrack(MediaContainer container) => + container.Video is { Samples.Count: > 0, Encoded: false } video && video.Codec switch + { + VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null, + VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null, + _ => false, + } + ? video + : null; + + /// Whether an exception while reading a video means a file that cannot be read (not a bug). + internal static bool IsUnreadableFile(Exception ex) => IsUnreadable(ex); + + /// + /// Decodes the samples (ascending indices) exactly, each from an IDR picture or a recovery point shown no later than + /// it (else from the first sample), and gives each frame in RGBA, rotated upright, in decoding order. + /// + internal static IEnumerable<(int Sample, RgbaImage Image)> DecodeExact(Stream stream, VideoTrack video, int[] samples, + CancellationToken ct) + { + var decoding = new Decoding(stream, video, int.MaxValue, exact: true); + foreach (var (sample, frame) in decoding.Decode(samples, ct)) + { + yield return (sample, ToRgba(frame, video.Rotation)); + } + } + + /// A frame at full size in RGBA (alpha 255), brought to 8 bits, then turned as the video is shown. + private static RgbaImage ToRgba(Frame frame, int rotation) + { + RgbaImage image; + if (frame.Hevc is { } h) + { + image = ToRgba(Planes(h), h.MatrixCoefficients, h.FullRange); + } + else + { + var a = frame.Avc!; + image = a.BytesPerSample == 2 + ? ToRgba(WidePlanes(a), a.MatrixCoefficients, a.FullRange) + : ToRgba(Planes(a), a.MatrixCoefficients, a.FullRange); + } + + var orientation = (((rotation % 360) + 360) % 360) switch + { + 90 => 6, + 180 => 3, + 270 => 8, + _ => 1, + }; + var upright = ImageOrientation.Apply(image, orientation); + if (!ReferenceEquals(upright, image)) + { + image.Dispose(); + } + + return upright; + } + + private static RgbaImage ToRgba(in YuvPlanes planes, int matrix, bool fullRange) + where T : unmanaged, System.Numerics.IBinaryInteger + { + var image = new RgbaImage(planes.Width, planes.Height); + var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height); + YuvToRgb.Convert(planes, k, 1, image.Pixels, planes.Width * RgbaImage.BytesPerPixel, RgbaImage.BytesPerPixel, + planes.Width, planes.Height); + return image; + } +} diff --git a/src/Febe.Core/Library/WindowsFileNames.cs b/src/Febe.Core/Library/WindowsFileNames.cs index 24ea67b..53c6438 100644 --- a/src/Febe.Core/Library/WindowsFileNames.cs +++ b/src/Febe.Core/Library/WindowsFileNames.cs @@ -89,8 +89,15 @@ public static class WindowsFileNames /// keeping its extension; then the longest folder segments. A shortened part ends with ~ and eight hex digits /// of the SHA-256 of the original, so different names stay different (for example _1 and _2). /// + /// The folder the path is below. + /// The segments. + /// The longest full path. + /// + /// When the stem of the file name ends with it (a frame suffix, «_t0m12s340»), the part before it is shortened and the + /// hash goes before it: «nome~1a2b3c4d_t0m12s340.png». Null: the whole stem may be cut, as before tappa E3. + /// /// Even shortened, the path does not fit (the base folder is too long). - public static IReadOnlyList FitPath(string baseFolder, IReadOnlyList segments, int maxLength = MaxPathLength) + public static IReadOnlyList FitPath(string baseFolder, IReadOnlyList segments, int maxLength = MaxPathLength, string? keepSuffix = null) { ArgumentNullException.ThrowIfNull(baseFolder); ArgumentNullException.ThrowIfNull(segments); @@ -111,11 +118,11 @@ public static class WindowsFileNames // 1. The file name, keeping its extension. var last = parts.Length - 1; - var (stem, extension) = SplitExtension(parts[last]); + var (stem, extension) = SplitKept(parts[last], keepSuffix); var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength)); if (stemTarget < stem.Length) { - parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true); + parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true, keepSuffix); excess = Total() - maxLength; } @@ -156,10 +163,22 @@ public static class WindowsFileNames : (fileName[..dot], fileName[dot..]); } - /// Shortens a name to at most characters with a hash suffix of the original. - private static string Shorten(string name, int maxLength, bool keepExtension) + /// + /// The stem and the end that is kept of a file name: the extension, preceded by when + /// the stem ends with it. + /// + private static (string Stem, string Kept) SplitKept(string fileName, string? keepSuffix) { - var (stem, extension) = keepExtension ? SplitExtension(name) : (name, string.Empty); + var (stem, extension) = SplitExtension(fileName); + return keepSuffix is { Length: > 0 } && stem.Length > keepSuffix.Length && stem.EndsWith(keepSuffix, StringComparison.Ordinal) + ? (stem[..^keepSuffix.Length], keepSuffix + extension) + : (stem, extension); + } + + /// Shortens a name to at most characters with a hash suffix of the original. + private static string Shorten(string name, int maxLength, bool keepExtension, string? keepSuffix = null) + { + var (stem, extension) = keepExtension ? SplitKept(name, keepSuffix) : (name, string.Empty); var room = maxLength - extension.Length - HashSuffixLength; if (room < 1) { diff --git a/src/Febe.Core/Storage/IEntryStore.cs b/src/Febe.Core/Storage/IEntryStore.cs index bc61bbc..b9fef87 100644 --- a/src/Febe.Core/Storage/IEntryStore.cs +++ b/src/Febe.Core/Storage/IEntryStore.cs @@ -58,11 +58,36 @@ public interface IEntryStore /// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become /// and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job. /// - Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default); + Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct); - /// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). + /// + /// As , and in the same transaction the + /// conversions for the library of its files: the queue and the failures (Pending, Failed) go, and the rows of + /// (whose converted file goes or is gone) become «Tolto». Other converted rows stay. + /// + Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection removedConversionIds, CancellationToken ct = default); + + /// + /// «Elimina dalla libreria» with memory: as , + /// and in the same transaction every conversion of its files with a file (Converted, Superseded) becomes «Tolto» + /// and is returned as it was: chosen inside the transaction, so a conversion recorded just before is among them + /// (its file is the caller's to delete) and none can be recorded after. The queue and the failures go. + /// + Task> MarkDeletedWithConversionsAsync(long entryId, DateTimeOffset at, CancellationToken ct = default); + + /// + /// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). Conversions + /// without a file left (Pending, Failed, Removed) go with it; a Converted or Superseded one makes it fail with + /// (its file would be forgotten): use . + /// Task RemoveAsync(long entryId, CancellationToken ct = default); + /// + /// «Eliminalo e lascia che torni» from «Elimina dalla libreria»: removes the record and every conversion of its files + /// in one transaction, and returns the conversions removed (their converted files are the caller's to delete). + /// + Task> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default); + /// Entries of an account ordered by publication time, newest first (account tabs, collection pipeline). Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default); diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index c8f1b81..eacc66a 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -162,6 +162,12 @@ public interface IExportStore Task GetItemAsync(long itemId, CancellationToken ct = default); + /// + /// The first item of a library file in a job with this variant and format, any state; null when none. The frames of + /// a video are added together in instant order, so an item's position among them is its id minus this one. + /// + Task FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default); + /// Items of a job, by key, with an optional state. Task> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default); @@ -177,22 +183,47 @@ public interface IExportStore Task> ListAccountExportSwitchesAsync(CancellationToken ct = default); /// - /// The newest Superseded or Removed row of (destination, account) whose is - /// this SHA-256: the library file that took the place of a copied one, never copied again by itself. + /// The newest Superseded or Removed row, not a frame, of (destination, account) whose + /// is this SHA-256: the library file that took the place of a copied one, + /// never copied again by itself (a superseded frame never makes the file «Superato»). /// Task FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); /// - /// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use (the general - /// folder or the own folder of an account still in Febe), of an account still in Febe; with - /// , of an account other than that one, so a newer row of the account itself never - /// hides the copy of another account (decision of 2026-11-27: «una copia altrove conta solo se è di un altro account»). + /// «Una copia sola»: the newest Copied row of this original, in any form but a frame (whole or converted, decision D3 + /// of tappa E3), in a destination in use (the general folder or the own folder of an account still in Febe), of an + /// account still in Febe; with , of an account other than that one, so a newer row + /// of the account itself never hides the copy of another account (decision of 2026-11-27: «una copia altrove conta + /// solo se è di un altro account»). /// - Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default); + Task FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default); /// - /// The state of whole copies (, ) of (account, - /// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row + /// The SHA-256 of every file written converted or as a frame in a destination (any state, any destination): an + /// import recognises them as copies of library files (tappa E3, Q37). No index on copy_sha256: one read per + /// import run, bounded by the converted copies. + /// + Task> LoadConvertedCopyShasAsync(CancellationToken ct = default); + + /// + /// The current (Copied or Failed) rows of an original for an account in a destination, in any form but a frame, + /// newest first: «già copiato» looks at the file, not at its format (decision D3 of tappa E3). + /// + Task> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); + + /// The newest row, in any state and any form but a frame, of an original for an account in a destination (D3 of tappa E3). + Task FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); + + /// + /// After a copy of an original succeeded: its other current «Non riuscito» rows in any form but a frame, for the + /// account in the destination, are deleted (they have no file; the identity is kept). + /// Returns the rows deleted. + /// + Task ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default); + + /// + /// The state of the copies of (account, SHA-256) pairs in one destination, in any form but a frame (decision D3 of + /// tappa E3), for the plan: Copied when a current row is Copied, else Failed when one is Failed, else the newest row /// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256 /// (). Pairs without any are absent. /// @@ -227,7 +258,7 @@ public interface IExportStore /// Task> GetEntryCopyCountsAsync(IReadOnlyList entryIds, CancellationToken ct = default); - /// The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent. + /// The mark of single files («Tutte le foto»): Copied, FrameOnly or None; files that are not due are absent. Task> GetFileMarksAsync(IReadOnlyList mediaIds, CancellationToken ct = default); /// The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2). @@ -246,7 +277,8 @@ public sealed record ExportCandidate( long? Bytes, string? RelativePath, int Position, - bool InHighlight); + bool InHighlight, + TimeSpan? Duration = null); /// The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato». public enum ExportMark @@ -254,13 +286,21 @@ public enum ExportMark None, Partly, Copied, + + /// «Solo fotogrammi»: no due file is copied, at least one has a frame copied (decision D4 of tappa E3). + FrameOnly, } -/// The due files of an entry and how many are copied (decision D3 of tappa E2). -public sealed record ExportEntryCopies(int Due, int Copied) +/// +/// The due files of an entry and how many are copied (decision D3 of tappa E2): a frame never makes a file copied; a +/// file with only frames copied counts in (decision D4 of tappa E3). +/// +public sealed record ExportEntryCopies(int Due, int Copied, int FrameOnly = 0) { - /// «Non ancora copiato» (none), «Copiato in parte», «Copiato». - public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly; + /// «Non ancora copiato» (none), «Solo fotogrammi», «Copiato in parte», «Copiato». + public ExportMark Mark => Copied <= 0 + ? FrameOnly > 0 ? ExportMark.FrameOnly : ExportMark.None + : Copied >= Due ? ExportMark.Copied : ExportMark.Partly; } /// Counts of the due files of an account (decision D3 of tappa E2). diff --git a/src/Febe.Core/Storage/IMediaConversionStore.cs b/src/Febe.Core/Storage/IMediaConversionStore.cs index ed1ede3..b65b335 100644 --- a/src/Febe.Core/Storage/IMediaConversionStore.cs +++ b/src/Febe.Core/Storage/IMediaConversionStore.cs @@ -25,9 +25,134 @@ public interface IMediaConversionStore /// The conversions of one library file, in creation order. Task> ListByMediaAsync(long mediaId, CancellationToken ct = default); + /// The conversions of the files of one entry, by file and creation order. + Task> ListByEntryAsync(long entryId, CancellationToken ct = default); + + /// The conversions of these library files, by file and creation order. + Task> ListByMediaIdsAsync(IReadOnlyCollection mediaIds, CancellationToken ct = default); + + /// + /// The paths (relative to the account folder) that conversions of the account's files record: Converted, + /// Superseded and Removed rows (a rebuild does not count them as unknown files). + /// + Task> ListPathsByAccountAsync(long accountId, CancellationToken ct = default); + + /// The conversions of the account's files that record this path (any state with a path), by key. + Task> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default); + /// Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate). Task> FindBySha256Async(string sha256, CancellationToken ct = default); /// The queue of the conversion, in order, by key. Task> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default); + + /// «Tolto»: these Converted or Superseded rows lost their file with their entry. Returns the rows changed. + Task MarkRemovedAsync(IReadOnlyCollection ids, DateTimeOffset at, CancellationToken ct = default); + + /// + /// A library file leaves its entry («Tieni il più grande» on a file of a series), in one transaction: the file + /// becomes , its queue and failures go, its rows with a file become «Tolto». Returns + /// those rows as they were (chosen inside the transaction: their files are the caller's to delete). The state of + /// the entry is the caller's to recompute. + /// + Task> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default); + + /// + /// The account's file changed from to (spec §4.10 + /// «Superato»): the conversions made from the old bytes of the account's files that now have the new ones become + /// Superseded (their files stay); Pending and retryable Failed rows take the new SHA-256. Returns the media ids of the + /// files concerned (to queue them again). + /// + Task> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default); + + /// + /// The setting of a format went off or changed: its queue is emptied, with its failures that «Riprova» would put + /// back (Converted rows and their files stay, and so do the AsIs* verdicts). Returns how many rows went. + /// + Task DeleteQueueAsync(ExportFormat format, CancellationToken ct = default); + + /// + /// A change of the library formats: stores (null values remove their key) and empties + /// the queues of as does, in one transaction, so that the + /// formats, the keys that go with them and the queues are stored whole or not at all. Returns how many rows went. + /// + Task SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary settings, IReadOnlyCollection formats, CancellationToken ct = default); + + /// Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending. + Task DeletePendingRowAsync(long id, CancellationToken ct = default); + + /// How many rows are in each state; Failed rows with an AsIs* code are counted apart. + Task CountByStateAsync(CancellationToken ct = default); + + /// + /// Queues these files in these formats (Pending, source_sha256 = the given SHA-256). A file that already has a + /// current conversion in the format (Pending, Converted, or Failed, which holds the slot) is left as it is. Returns + /// how many rows were added. + /// + Task EnqueueAsync(IReadOnlyList requests, DateTimeOffset at, CancellationToken ct = default); + + /// + /// «Anche i N già in libreria»: queues, in one statement, every present library file of each kind whose extension + /// says it converts into the format given for its kind (null: that kind is not queued). Returns how many were added. + /// + Task EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default); + + /// What would queue: files and their bytes. + Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default); + + /// + /// Records a converted file just written (or adopted) for a Pending row, in one transaction (WP2.2 step 4): the row + /// becomes Converted only if it is still Pending with and its library file is still + /// present with that SHA-256. Otherwise, with the file still present and unchanged, the current conversion of that + /// file and format becomes Converted with this file, or a new row is added; with the file gone or changed nothing is + /// recorded. + /// + Task CommitAsync(MediaConversionCommit commit, CancellationToken ct = default); + + /// + /// «Riprova»: Failed rows in (the library formats set now) go back to Pending, except those + /// with an AsIs* code (they never convert). Returns how many. + /// + Task ResetFailedAsync(IReadOnlyCollection formats, DateTimeOffset at, CancellationToken ct = default); +} + +/// One file to queue in one format, made from these bytes. +public sealed record MediaConversionRequest(long MediaId, ExportFormat Format, string SourceSha256); + +/// The rows of the conversion for the library, by state. +/// In the queue. +/// Converted files. +/// Failed, to try again («Riprova»). +/// Failed for good: animated, not decodable, CMYK… («non si convertono»). +/// Converted from bytes the library no longer has. +/// Their file went with the entry. +public sealed record MediaConversionCounts(int Pending, int Converted, int Failed, int AsIs, int Superseded, int Removed); + +/// A converted file written for . +/// The Pending row it was written for. +/// Its library file. +/// The format. +/// The SHA-256 of the original it was made from. +/// Path relative to the account folder. +/// Its size. +/// Its SHA-256. +/// When it was converted. +/// What the conversion could not keep (loss codes, D19), or null. +public sealed record MediaConversionCommit(long ConversionId, long MediaId, ExportFormat Format, string SourceSha256, + string RelativePath, long Bytes, string Sha256, DateTimeOffset At, string? Notes); + +/// What did. +public enum MediaConversionCommitOutcome +{ + /// The Pending row is now Converted. + Recorded, + + /// The row had changed meanwhile; the file is recorded in the current row of its format, or a new one. + Upserted, + + /// Nothing recorded: the library file was deleted or changed meanwhile. + SourceGone, + + /// Nothing recorded: another converted file already holds the format of this library file. + SlotTaken, } diff --git a/src/Febe.Data/Stores/EngineStores.cs b/src/Febe.Data/Stores/EngineStores.cs index eb92055..44add40 100644 --- a/src/Febe.Data/Stores/EngineStores.cs +++ b/src/Febe.Data/Stores/EngineStores.cs @@ -623,7 +623,8 @@ internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore }, ct); - private static void Set(WriteContext w, string key, string? value) + /// Stores one value inside a write (null removes the key): also for stores that save settings with their rows. + internal static void Set(WriteContext w, string key, string? value) { if (value is null) { diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index fa2cd42..76e92f9 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -148,26 +148,119 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore public Task RecomputeStateAsync(long entryId, CancellationToken ct = default) => db.WriteAsync(w => RecomputeState(w, entryId), ct); - public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => - db.WriteAsync( + public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct); + + /// + /// «Eliminato» inside the caller's transaction: the entry, its files without path, and the conversions for the + /// library of its files (tappa E3) with nothing left to convert or retry (Pending, Failed) go. + /// + private static void MarkDeleted(WriteContext w, long entryId, DateTimeOffset at) + { + var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id") + .With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery(); + if (rows == 0) + { + throw new KeyNotFoundException($"Elemento {entryId} non trovato."); + } + + w.Command(""" + UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL + WHERE entry_id = @id + """).With("@id", entryId).ExecuteNonQuery(); + w.Command(""" + DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed') AND media_id IN (SELECT id FROM media WHERE entry_id = @id) + """).With("@id", entryId).ExecuteNonQuery(); + } + + public Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection removedConversionIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(removedConversionIds); + var removed = removedConversionIds.Distinct().ToList(); + return db.WriteAsync( w => { - var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id") - .With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery(); - if (rows == 0) + MarkDeleted(w, entryId, at); + + // The converted files that go (or are gone) are «Tolto», the others stay as they are. + if (removed.Count > 0) { - throw new KeyNotFoundException($"Elemento {entryId} non trovato."); + var own = new HashSet(); + using (var r = w.Command("SELECT mc.id FROM media_conversion mc JOIN media m ON m.id = mc.media_id WHERE m.entry_id = @id") + .With("@id", entryId).ExecuteReader()) + { + while (r.Read()) + { + own.Add(r.GetInt64(0)); + } + } + + MediaConversionStore.MarkRemoved(w, removed.Where(own.Contains).ToList(), at); + } + }, + ct); + } + + public Task> MarkDeletedWithConversionsAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync>( + w => + { + var withFiles = new List(); + using (var r = w.Command($""" + SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id + WHERE m.entry_id = @id AND mc.state IN ('Converted', 'Superseded') ORDER BY mc.media_id, mc.id + """).With("@id", entryId).ExecuteReader()) + { + while (r.Read()) + { + withFiles.Add(MediaConversionStore.ReadRow(r)); + } } - w.Command(""" - UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL - WHERE entry_id = @id - """).With("@id", entryId).ExecuteNonQuery(); + MarkDeleted(w, entryId, at); + MediaConversionStore.MarkRemoved(w, withFiles.Select(c => c.Id).ToList(), at); + return withFiles; }, ct); public Task RemoveAsync(long entryId, CancellationToken ct = default) => - db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct); + db.WriteAsync( + w => + { + MediaConversionStore.DeleteRowsWithoutFile(w, entryId); + try + { + w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(); + } + catch (SqliteException ex) when (ex.IsConstraintViolation()) + { + // ON DELETE RESTRICT of media_conversion: a converted file of the library would lose its record. + throw new InvalidOperationException( + "L'elemento ha file convertiti nella libreria: eliminalo con «Elimina dalla libreria», che toglie anche quelli.", ex); + } + }, + ct); + + public Task> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default) => + db.WriteAsync>( + w => + { + var list = new List(); + using (var r = w.Command($""" + SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id + WHERE m.entry_id = @id ORDER BY mc.media_id, mc.id + """).With("@id", entryId).ExecuteReader()) + { + while (r.Read()) + { + list.Add(MediaConversionStore.ReadRow(r)); + } + } + + w.Command("DELETE FROM media_conversion WHERE media_id IN (SELECT id FROM media WHERE entry_id = @id)").With("@id", entryId).ExecuteNonQuery(); + w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(); + return list; + }, + ct); public Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default) { diff --git a/src/Febe.Data/Stores/ExportFilterSql.cs b/src/Febe.Data/Stores/ExportFilterSql.cs index 82983b4..20b1c5f 100644 --- a/src/Febe.Data/Stores/ExportFilterSql.cs +++ b/src/Febe.Data/Stores/ExportFilterSql.cs @@ -137,10 +137,21 @@ internal static class ExportFilterSql private static string OneOnlyMatch(ExportFilterContext x) => $"((c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id) OR (c.account_id IS NOT NULL AND c.account_id <> e.account_id))"; - /// The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again. + /// + /// The last copy of the file in its effective destination failed («Non riuscito»), in any form but a frame: «Copia + /// in…» tries again. + /// public static string Failed(ExportFilterContext x) => !x.HasFailed ? "0" - : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed')"; + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed' AND c.variant <> 'Frame')"; + + /// + /// A frame of the file is copied in its effective destination (decision D4 of tappa E3): it never makes the file + /// copied, only the mark «Solo fotogrammi» of a file not copied otherwise. «Una copia sola» does not apply to frames. + /// + public static string FrameCopied(ExportFilterContext x) => !x.HasCopies + ? "0" + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant = 'Frame')"; /// /// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was @@ -286,9 +297,9 @@ internal static class ExportFilterSql { var destination = DestinationOf(x); var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " - + "AND c.state IN ('Removed', 'Superseded'))"; + + "AND c.state IN ('Removed', 'Superseded') AND c.variant <> 'Frame')"; var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " - + "AND c.state IN ('Superseded', 'Removed'))"; + + "AND c.state IN ('Superseded', 'Removed') AND c.variant <> 'Frame')"; if (!bulk) { return $"({removed} OR {superseded})"; diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index fbde21a..3492326 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -826,6 +826,32 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore public Task GetItemAsync(long itemId, CancellationToken ct = default) => db.ReadAsync(c => ReadFirst(c.Command($"SELECT {ItemColumns} FROM export_item WHERE id = @id").With("@id", itemId), ReadItem), ct); + /// The first item of a file of a job in a form (ux_export_item_file). + internal const string FirstItemSql = "SELECT min(id) FROM export_item WHERE run_id = @r AND media_id = @m AND variant = @v AND format = @f"; + + public Task> LoadConvertedCopyShasAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var command = c.Command("SELECT DISTINCT copy_sha256 FROM export_copy WHERE variant IN ('Converted', 'Frame') AND copy_sha256 IS NOT NULL"); + using var r = command.ExecuteReader(); + var set = new HashSet(StringComparer.Ordinal); + while (r.Read()) + { + set.Add(r.GetString(0)); + } + + return set; + }, + ct); + + public Task FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default) => + db.ReadAsync( + c => c.Command(FirstItemSql).With("@r", runId).With("@m", mediaId).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).ExecuteScalar() is long id + ? id + : (long?)null, + ct); + public Task> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(query); @@ -878,13 +904,37 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore internal const string ReplacedCopySql = $""" SELECT {CopyColumns} FROM export_copy - WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed') + WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed') AND variant <> 'Frame' ORDER BY id DESC LIMIT 1 """; + /// + /// The current rows of an original, any form but a frame (decision D3 of tappa E3; @h, @d, @a). INDEXED BY keeps + /// it on ix_export_copy_sha256 (a few rows, sorted): for «ORDER BY id» the planner would read a whole destination. + /// + internal const string CurrentCopiesAnyFormSql = $""" + SELECT {CopyColumns} FROM export_copy INDEXED BY ix_export_copy_sha256 + WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' AND state IN ('Copied', 'Failed') + ORDER BY id DESC + """; + + /// The newest row of an original, any state and any form but a frame (@h, @d, @a). + internal const string LatestCopyAnyFormSql = $""" + SELECT {CopyColumns} FROM export_copy INDEXED BY ix_export_copy_sha256 + WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' + ORDER BY id DESC LIMIT 1 + """; + + /// The «Non riuscito» rows of an original that a success leaves stale (@h, @d, @a; the kept identity @v, @f). + internal const string ClearFailedSql = """ + DELETE FROM export_copy + WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' AND state = 'Failed' + AND NOT (variant = @v AND format = @f) + """; + internal const string CopiedElsewhereSql = $""" SELECT {CopyColumns} FROM export_copy - WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL + WHERE source_sha256 = @h AND variant <> 'Frame' AND state = 'Copied' AND account_id IS NOT NULL AND (@a IS NULL OR account_id <> @a) AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL AND (scope = 'General' OR account_id IS NOT NULL)) ORDER BY id DESC LIMIT 1 @@ -892,10 +942,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit"; - /// The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256. + /// + /// The copies of a destination for some originals, in any form but a frame (ix_export_copy_sha256; decision D3 of + /// tappa E3); @d and the list of SHA-256. + /// internal static string CopyStatesSql(string shaList) => $""" SELECT account_id, source_sha256, state, id FROM export_copy - WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original' + WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant <> 'Frame' """; /// @@ -906,11 +959,12 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore internal static string ReplacedStatesSql(string shaList) => $""" SELECT account_id, superseded_by_sha256, state, id FROM export_copy WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND +state IN ('Superseded', 'Removed') + AND variant <> 'Frame' """; private const string CandidateColumns = "m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, " - + "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id)"; + + "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id), m.duration_ms"; private static ExportCandidate ReadCandidate(SqliteDataReader r) => new( r.GetInt64(0), @@ -923,7 +977,8 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore r.GetInt64OrNull(7), r.GetTextOrNull(8), r.GetInt32(9), - r.GetBool(10)); + r.GetBool(10), + r.GetDurationOrNull(11)); public Task> ListAccountExportSwitchesAsync(CancellationToken ct = default) => db.ReadAsync>( @@ -948,16 +1003,44 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore ct); } - public Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default) + public Task FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default) { var sha = ExportValues.Sha(sha256, nameof(sha256)); return db.ReadAsync( c => ReadFirst( - c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).With("@a", Sql.Int(exceptAccountId)), + c.Command(CopiedElsewhereSql).With("@h", sha).With("@a", Sql.Int(exceptAccountId)), ReadCopy), ct); } + public Task> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync>( + c => ReadAll(c.Command(CurrentCopiesAnyFormSql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy), + ct); + } + + public Task FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync( + c => ReadFirst(c.Command(LatestCopyAnyFormSql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy), + ct); + } + + public Task ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(except); + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.WriteAsync( + w => w.Command(ClearFailedSql) + .With("@h", sha).With("@d", destinationId).With("@a", accountId) + .With("@v", Sql.Enum(except.Variant)).With("@f", Sql.Enum(except.Format)) + .ExecuteNonQuery(), + ct); + } + public Task> GetCopyStatesAsync( long destinationId, IReadOnlyCollection<(long AccountId, string Sha256)> keys, @@ -968,8 +1051,9 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore return db.ReadAsync>( c => { - // Per pair: the current row (Copied or Failed), else the newest row when Removed or Superseded, else a row - // replaced by this file. Rows of other accounts that share a SHA-256 are read and dropped here. + // Per pair, over every form but a frame (D3 of tappa E3): a Copied row, else a Failed one, else the newest + // row when Removed or Superseded, else a row replaced by this file. Rows of other accounts that share a + // SHA-256 are read and dropped here. var current = new Dictionary<(long, string), ExportCopyState>(); var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); @@ -1000,7 +1084,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore { Read(CopyStatesSql, chunk, (key, state, id) => { - if (state is ExportCopyState.Copied or ExportCopyState.Failed) + if (state == ExportCopyState.Copied || (state == ExportCopyState.Failed && !current.ContainsKey(key))) { current[key] = state; } @@ -1134,12 +1218,15 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore return marks; } + var copied = ExportFilterSql.Copied(x); + var frames = ExportFilterSql.FrameCopied(x); foreach (var chunk in entryIds.Distinct().Chunk(IdChunk)) { using var command = c.Command(string.Empty); var list = command.AddList("x", chunk); command.CommandText = $""" - SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END) + SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {copied} THEN 1 ELSE 0 END), + SUM(CASE WHEN NOT {copied} AND {frames} THEN 1 ELSE 0 END) FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)} GROUP BY m.entry_id @@ -1147,7 +1234,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore using var r = command.ExecuteReader(); while (r.Read()) { - marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2)); + marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2), r.GetInt32(3)); } } @@ -1174,13 +1261,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore using var command = c.Command(string.Empty); var list = command.AddList("x", chunk); command.CommandText = $""" - SELECT m.id, {ExportFilterSql.Copied(x)} FROM media m JOIN entry e ON e.id = m.entry_id + SELECT m.id, {ExportFilterSql.Copied(x)}, {ExportFilterSql.FrameCopied(x)} FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)} """; using var r = command.ExecuteReader(); while (r.Read()) { - marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : ExportMark.None; + marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : r.GetInt64(2) != 0 ? ExportMark.FrameOnly : ExportMark.None; } } diff --git a/src/Febe.Data/Stores/MediaConversionStore.Library.cs b/src/Febe.Data/Stores/MediaConversionStore.Library.cs new file mode 100644 index 0000000..03b3b7c --- /dev/null +++ b/src/Febe.Data/Stores/MediaConversionStore.Library.cs @@ -0,0 +1,514 @@ +using System.Globalization; +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Library.Conversion; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +/// The queue, the commit and the hooks of the conversion for the library (tappa E3, WP2.3). +internal sealed partial class MediaConversionStore +{ + /// The same columns of the alias mc, for joins. + private const string JoinedColumns = + "mc.id, mc.media_id, mc.format, mc.state, mc.source_sha256, mc.relative_path, mc.bytes, mc.sha256, mc.created_at, mc.converted_at, mc.state_changed_at, mc.last_error"; + + /// The columns of the alias mc, for other stores reading rows with . + internal const string JoinedColumnList = JoinedColumns; + + /// The present library files of the alias m, as the conversion for the library sees them. + private const string PresentMedia = "m.state IN ('Downloaded', 'Imported') AND m.sha256 IS NOT NULL AND m.relative_path IS NOT NULL"; + + /// A Failed row whose code says it never converts (animated, not decodable, CMYK…): its first code. + internal const string AsIsCondition = "last_error LIKE 'AsIs%'"; + + /// One row read in the order of . + internal static MediaConversion ReadRow(SqliteDataReader r) => Read(r); + + public Task> ListByEntryAsync(long entryId, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id + WHERE m.entry_id = @e ORDER BY mc.media_id, mc.id + """).With("@e", entryId)), + ct); + + public Task> ListByMediaIdsAsync(IReadOnlyCollection mediaIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(mediaIds); + var ids = mediaIds.Distinct().ToList(); + if (ids.Count == 0) + { + return Task.FromResult>([]); + } + + return db.ReadAsync>( + c => + { + var list = new List(); + foreach (var chunk in ids.Chunk(500)) + { + using var command = c.Command(string.Empty); + command.CommandText = $"SELECT {Columns} FROM media_conversion WHERE media_id IN ({command.AddList("m", chunk)})"; + list.AddRange(ReadAll(command)); + } + + return list.OrderBy(x => x.MediaId).ThenBy(x => x.Id).ToList(); + }, + ct); + } + + public Task> ListPathsByAccountAsync(long accountId, CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var command = c.Command(""" + SELECT DISTINCT mc.relative_path FROM media_conversion mc + JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND mc.relative_path IS NOT NULL AND mc.state IN ('Converted', 'Superseded', 'Removed') + """).With("@a", accountId); + using var r = command.ExecuteReader(); + var list = new List(); + while (r.Read()) + { + list.Add(r.GetString(0)); + } + + return list; + }, + ct); + + public Task> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + return db.ReadAsync>( + c => ReadAll(c.Command($""" + SELECT {JoinedColumns} FROM media_conversion mc + JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND mc.relative_path = @p ORDER BY mc.id + """).With("@a", accountId).With("@p", relativePath)), + ct); + } + + public Task MarkRemovedAsync(IReadOnlyCollection ids, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(ids); + var list = ids.Distinct().ToList(); + return list.Count == 0 ? Task.FromResult(0) : db.WriteAsync(w => MarkRemoved(w, list, at), ct); + } + + /// «Tolto» for these ids among the Converted and Superseded rows, inside the caller's transaction. + internal static int MarkRemoved(WriteContext w, IReadOnlyCollection ids, DateTimeOffset at) + { + var changed = 0; + foreach (var chunk in ids.Chunk(500)) + { + using var command = w.Connection.Command(string.Empty, w.Transaction); + command.CommandText = $""" + UPDATE media_conversion SET state = 'Removed', state_changed_at = @at + WHERE state IN ('Converted', 'Superseded') AND id IN ({command.AddList("i", chunk)}) + """; + changed += command.With("@at", Sql.Time(at)).ExecuteNonQuery(); + } + + return changed; + } + + public Task> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default) => + db.WriteAsync>( + w => + { + w.Command("UPDATE media SET state = 'Deleted' WHERE id = @m").With("@m", mediaId).ExecuteNonQuery(); + w.Command("DELETE FROM media_conversion WHERE media_id = @m AND state IN ('Pending', 'Failed')").With("@m", mediaId).ExecuteNonQuery(); + var removed = ReadAll(w.Command($""" + SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id + WHERE mc.media_id = @m AND mc.state IN ('Converted', 'Superseded') ORDER BY mc.id + """).With("@m", mediaId)); + MarkRemoved(w, removed.Select(c => c.Id).ToList(), at); + return removed; + }, + ct); + + /// The rows without a file left (Pending, Failed, Removed) of an entry's files go, inside the caller's transaction. + internal static int DeleteRowsWithoutFile(WriteContext w, long entryId) => + w.Command(""" + DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed', 'Removed') + AND media_id IN (SELECT id FROM media WHERE entry_id = @e) + """).With("@e", entryId).ExecuteNonQuery(); + + public Task> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default) + { + var old = ExportValues.Sha(oldSha256, nameof(oldSha256)); + var now = ExportValues.Sha(newSha256, nameof(newSha256)); + if (old == now) + { + return Task.FromResult>([]); + } + + return db.WriteAsync>( + w => + { + var media = new List(); + using (var find = w.Connection.Command(""" + SELECT DISTINCT mc.media_id FROM media_conversion mc + JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND mc.source_sha256 = @old AND m.sha256 = @new + AND mc.state IN ('Pending', 'Converted', 'Failed') + ORDER BY mc.media_id + """, w.Transaction)) + { + find.With("@a", accountId).With("@old", old).With("@new", now); + using var r = find.ExecuteReader(); + while (r.Read()) + { + media.Add(r.GetInt64(0)); + } + } + + foreach (var chunk in media.Chunk(500)) + { + using var command = w.Connection.Command(string.Empty, w.Transaction); + var list = command.AddList("m", chunk); + + // Converted from the old bytes: history, its file stays. The queue and the failures take the new + // bytes (a verdict, «AsIs» included, was about the old ones) and are tried again. + command.CommandText = $""" + UPDATE media_conversion SET state = 'Superseded', state_changed_at = @at + WHERE state = 'Converted' AND source_sha256 = @old AND media_id IN ({list}); + UPDATE media_conversion SET state = 'Pending', source_sha256 = @new, last_error = NULL, state_changed_at = @at + WHERE state IN ('Pending', 'Failed') AND source_sha256 = @old AND media_id IN ({list}); + """; + command.With("@at", Sql.Time(at)).With("@old", old).With("@new", now).ExecuteNonQuery(); + } + + return media; + }, + ct); + } + + public Task DeleteQueueAsync(ExportFormat format, CancellationToken ct = default) => + db.WriteAsync(w => DeleteQueue(w, format), ct); + + public Task SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary settings, IReadOnlyCollection formats, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(formats); + foreach (var key in settings.Keys) + { + ArgumentException.ThrowIfNullOrWhiteSpace(key); + } + + return db.WriteAsync( + w => + { + foreach (var (key, value) in settings) + { + SettingsStore.Set(w, key, value); + } + + var deleted = 0; + foreach (var format in formats.Distinct()) + { + deleted += DeleteQueue(w, format); + } + + return deleted; + }, + ct); + } + + private static int DeleteQueue(WriteContext w, ExportFormat format) => + w.Command($""" + DELETE FROM media_conversion + WHERE format = @f AND (state = 'Pending' OR (state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition})))) + """).With("@f", Sql.Enum(format)).ExecuteNonQuery(); + + public Task DeletePendingRowAsync(long id, CancellationToken ct = default) => + db.WriteAsync( + w => w.Command("DELETE FROM media_conversion WHERE id = @id AND state = 'Pending'").With("@id", id).ExecuteNonQuery() > 0, + ct); + + public Task CountByStateAsync(CancellationToken ct = default) => + db.ReadAsync( + c => + { + using var command = c.Command($""" + SELECT state, CASE WHEN state = 'Failed' AND {AsIsCondition} THEN 1 ELSE 0 END, COUNT(*) + FROM media_conversion GROUP BY 1, 2 + """); + using var r = command.ExecuteReader(); + int pending = 0, converted = 0, failed = 0, asIs = 0, superseded = 0, removed = 0; + while (r.Read()) + { + var n = (int)r.GetInt64(2); + switch (r.GetString(0)) + { + case "Pending": + pending += n; + break; + case "Converted": + converted += n; + break; + case "Failed" when r.GetInt64(1) == 1: + asIs += n; + break; + case "Failed": + failed += n; + break; + case "Superseded": + superseded += n; + break; + case "Removed": + removed += n; + break; + } + } + + return new MediaConversionCounts(pending, converted, failed, asIs, superseded, removed); + }, + ct); + + public Task EnqueueAsync(IReadOnlyList requests, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(requests); + if (requests.Count == 0) + { + return Task.FromResult(0); + } + + var valid = requests.Select(r => + { + ArgumentNullException.ThrowIfNull(r); + if (r.Format == ExportFormat.Original) + { + throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(requests)); + } + + return r with { SourceSha256 = ExportValues.Sha(r.SourceSha256, nameof(r.SourceSha256)) }; + }).ToList(); + return db.WriteAsync( + w => + { + var added = 0; + foreach (var r in valid) + { + // A current row (Pending, Converted, or Failed, which holds the slot) is left as it is. + added += w.Command(""" + INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at) + SELECT @m, @f, 'Pending', @s, @at WHERE EXISTS (SELECT 1 FROM media WHERE id = @m) + ON CONFLICT DO NOTHING + """).With("@m", r.MediaId).With("@f", Sql.Enum(r.Format)).With("@s", r.SourceSha256).With("@at", Sql.Time(at)).ExecuteNonQuery(); + } + + return added; + }, + ct); + } + + /// The present files of a kind that convert into , as a condition on the alias m. + private static string ExistingCondition(SqliteCommand command, MediaKind kind, ExportFormat format) + { + var excluded = LibraryConversionRules.ExcludedExtensions(format); + var sql = new StringBuilder($"m.kind = @k AND {PresentMedia}"); + command.With("@k", Sql.Enum(kind)); + for (var i = 0; i < excluded.Count; i++) + { + // LIKE compares ASCII letters without case, as the extension rule does. + sql.Append(CultureInfo.InvariantCulture, $" AND m.relative_path NOT LIKE @x{i}"); + command.With(string.Create(CultureInfo.InvariantCulture, $"@x{i}"), "%" + excluded[i]); + } + + return sql.ToString(); + } + + private static List<(MediaKind Kind, ExportFormat Format)> Kinds(ExportFormat? photo, ExportFormat? video) + { + var kinds = new List<(MediaKind, ExportFormat)>(); + if (photo is { } p && p != ExportFormat.Original) + { + if (!ExportFormats.IsPhotoFormat(p)) + { + throw new ArgumentException("Il formato non è adatto alle foto.", nameof(photo)); + } + + kinds.Add((MediaKind.Photo, p)); + } + + if (video is { } v && v != ExportFormat.Original) + { + if (!ExportFormats.IsVideoFormat(v)) + { + throw new ArgumentException("Il formato non è adatto ai video.", nameof(video)); + } + + kinds.Add((MediaKind.Video, v)); + } + + return kinds; + } + + public Task EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default) + { + var kinds = Kinds(photo, video); + if (kinds.Count == 0) + { + return Task.FromResult(0); + } + + return db.WriteAsync( + w => + { + var added = 0; + foreach (var (kind, format) in kinds) + { + using var command = w.Connection.Command(string.Empty, w.Transaction); + var where = ExistingCondition(command, kind, format); + + // One statement; a file with a current row in the format (a Failed one included) keeps it. + command.CommandText = $""" + INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at) + SELECT m.id, @f, 'Pending', m.sha256, @at FROM media m WHERE {where} ORDER BY m.id + ON CONFLICT DO NOTHING + """; + added += command.With("@f", Sql.Enum(format)).With("@at", Sql.Time(at)).ExecuteNonQuery(); + } + + return added; + }, + ct); + } + + public Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default) + { + var kinds = Kinds(photo, video); + if (kinds.Count == 0) + { + return Task.FromResult((0, 0L)); + } + + return db.ReadAsync( + c => + { + var files = 0; + long bytes = 0; + foreach (var (kind, format) in kinds) + { + using var command = c.Command(string.Empty); + var where = ExistingCondition(command, kind, format); + command.CommandText = $""" + SELECT COUNT(*), COALESCE(SUM(m.bytes), 0) FROM media m + WHERE {where} AND NOT EXISTS ( + SELECT 1 FROM media_conversion mc WHERE mc.media_id = m.id AND mc.format = @f AND mc.state IN ('Pending', 'Converted', 'Failed')) + """; + command.With("@f", Sql.Enum(format)); + using var r = command.ExecuteReader(); + if (r.Read()) + { + files += (int)r.GetInt64(0); + bytes += r.GetInt64(1); + } + } + + return (files, bytes); + }, + ct); + } + + public Task CommitAsync(MediaConversionCommit commit, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(commit); + ArgumentException.ThrowIfNullOrWhiteSpace(commit.RelativePath); + ArgumentOutOfRangeException.ThrowIfNegative(commit.Bytes); + if (commit.Format == ExportFormat.Original) + { + throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(commit)); + } + + var source = ExportValues.Sha(commit.SourceSha256, nameof(commit.SourceSha256)); + var sha = ExportValues.Sha(commit.Sha256, nameof(commit.Sha256)); + return db.WriteAsync(w => Commit(w, commit, source, sha), ct); + } + + private static MediaConversionCommitOutcome Commit(WriteContext w, MediaConversionCommit commit, string source, string sha) + { + SqliteCommand Bind(SqliteCommand c) => + c.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).With("@s", source).With("@p", commit.RelativePath) + .With("@b", commit.Bytes).With("@h", sha).With("@at", Sql.Time(commit.At)).With("@e", Sql.Text(commit.Notes)); + + var recorded = Bind(w.Command($""" + UPDATE media_conversion SET state = 'Converted', relative_path = @p, bytes = @b, sha256 = @h, converted_at = @at, + state_changed_at = @at, last_error = @e + WHERE id = @id AND media_id = @m AND format = @f AND state = 'Pending' AND source_sha256 = @s + AND EXISTS (SELECT 1 FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia}) + """)).With("@id", commit.ConversionId).ExecuteNonQuery(); + if (recorded == 1) + { + return MediaConversionCommitOutcome.Recorded; + } + + var present = w.Command($"SELECT COUNT(*) FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia}") + .With("@m", commit.MediaId).With("@s", source).ScalarInt64() > 0; + if (!present) + { + return MediaConversionCommitOutcome.SourceGone; + } + + long? currentId = null; + string? currentState = null; + using (var r = w.Command("SELECT id, state FROM media_conversion WHERE media_id = @m AND format = @f AND state IN ('Pending', 'Converted', 'Failed')") + .With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).ExecuteReader()) + { + if (r.Read()) + { + currentId = r.GetInt64(0); + currentState = r.GetString(1); + } + } + + if (currentState == "Converted") + { + return MediaConversionCommitOutcome.SlotTaken; + } + + if (currentId is { } id) + { + Bind(w.Command(""" + UPDATE media_conversion SET state = 'Converted', source_sha256 = @s, relative_path = @p, bytes = @b, sha256 = @h, + converted_at = @at, state_changed_at = @at, last_error = @e + WHERE id = @id AND media_id = @m AND format = @f + """)).With("@id", id).ExecuteNonQuery(); + return MediaConversionCommitOutcome.Upserted; + } + + // The row went (the setting was turned off meanwhile): the file just written stays recorded. + Bind(w.Command(""" + INSERT INTO media_conversion (media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, + state_changed_at, last_error) + VALUES (@m, @f, 'Converted', @s, @p, @b, @h, @at, @at, @at, @e) + """)).ExecuteNonQuery(); + return MediaConversionCommitOutcome.Upserted; + } + + public Task ResetFailedAsync(IReadOnlyCollection formats, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(formats); + if (formats.Count == 0) + { + return Task.FromResult(0); + } + + return db.WriteAsync( + w => + { + using var command = w.Connection.Command(string.Empty, w.Transaction); + var list = command.AddList("f", formats.Distinct().Select(f => Sql.Enum(f)).ToList()); + command.CommandText = $""" + UPDATE media_conversion SET state = 'Pending', last_error = NULL, state_changed_at = @at + WHERE state = 'Failed' AND format IN ({list}) AND (last_error IS NULL OR NOT ({AsIsCondition})) + """; + return command.With("@at", Sql.Time(at)).ExecuteNonQuery(); + }, + ct); + } +} diff --git a/src/Febe.Data/Stores/MediaConversionStore.cs b/src/Febe.Data/Stores/MediaConversionStore.cs index 6517cdf..fd6df02 100644 --- a/src/Febe.Data/Stores/MediaConversionStore.cs +++ b/src/Febe.Data/Stores/MediaConversionStore.cs @@ -4,7 +4,7 @@ using Microsoft.Data.Sqlite; namespace Febe.Data.Stores; -internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore +internal sealed partial class MediaConversionStore(FebeDatabase db) : IMediaConversionStore { private const string Columns = "id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error"; diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs index ac8d073..e08db03 100644 --- a/src/Febe.Web/Api/AccountsApi.cs +++ b/src/Febe.Web/Api/AccountsApi.cs @@ -422,6 +422,7 @@ public static class AccountsApi var deleted = 0; var problems = 0; + var converted = 0; var deletion = library.Deletion; while (true) { @@ -436,13 +437,15 @@ public static class AccountsApi var result = await deletion.DeleteAsync(entry.Id, DeletionMode.AllowReturn, ct).ConfigureAwait(false); deleted += result.Found ? 1 : 0; problems += result.FailedFiles.Count; + converted += result.ConvertedFiles; } } await storage.Accounts.DeleteAsync(id, ct).ConfigureAwait(false); - var message = $"{handle} rimosso con {ItalianText.Count(deleted, "elemento", "elementi")}." + var message = $"{handle} rimosso con {ItalianText.Count(deleted, "elemento", "elementi")}" + + (converted > 0 ? $" e {ItalianText.Count(converted, "file convertito", "file convertiti")}." : ".") + (problems > 0 ? $" {ItalianText.Count(problems, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: restano nella sua cartella." : string.Empty); - return new RemoveAccountDto("removed", deleted, problems, message); + return new RemoveAccountDto("removed", deleted, problems, message, converted); } // ------------------------------------------------------------------------------------------ following and adding diff --git a/src/Febe.Web/Api/ApiErrorMiddleware.cs b/src/Febe.Web/Api/ApiErrorMiddleware.cs index f0e01fe..0d01f3f 100644 --- a/src/Febe.Web/Api/ApiErrorMiddleware.cs +++ b/src/Febe.Web/Api/ApiErrorMiddleware.cs @@ -39,6 +39,7 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger (StatusCodes.Status400BadRequest, "Richiesta non leggibile."), BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."), NotFoundException => (StatusCodes.Status404NotFound, ex.Message), + ApiStatusException a => (a.Status, ex.Message), DuplicateRecordException => (StatusCodes.Status409Conflict, ex.Message), _ => (StatusCodes.Status500InternalServerError, "Errore interno: Febe non ha completato l'operazione. Riprova; se succede ancora, guarda il registro."), }; diff --git a/src/Febe.Web/Api/ApiMapping.cs b/src/Febe.Web/Api/ApiMapping.cs index 6f9df0b..854375b 100644 --- a/src/Febe.Web/Api/ApiMapping.cs +++ b/src/Febe.Web/Api/ApiMapping.cs @@ -298,3 +298,30 @@ public sealed class NotFoundException : Exception { } } + +/// An answer with another status and an Italian message: 409 (busy, in session), 503 (too slow). +public sealed class ApiStatusException : Exception +{ + public ApiStatusException() + { + } + + public ApiStatusException(string message) + : base(message) + { + } + + public ApiStatusException(string message, Exception innerException) + : base(message, innerException) + { + } + + public ApiStatusException(int status, string message) + : base(message) + { + Status = status; + } + + /// The HTTP status (409 when not given). + public int Status { get; } = 409; +} diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs index fe62860..301d2bf 100644 --- a/src/Febe.Web/Api/Dtos.cs +++ b/src/Febe.Web/Api/Dtos.cs @@ -92,7 +92,9 @@ public sealed record MediaDto( bool Available, string State, bool Damaged = false, - IReadOnlyList? Copies = null); + IReadOnlyList? Copies = null, + bool? FramesAvailable = null, + IReadOnlyList? Conversions = null); /// Everything the viewer shows of an entry. public sealed record EntryDto( @@ -117,7 +119,8 @@ public sealed record EntryDto( public sealed record EntryIdsRequest(IReadOnlyList Ids, string? Mode); -public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList Problems, string Message); +/// What «Elimina dalla libreria» did; : converted files of the library deleted too (tappa E3). +public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList Problems, string Message, int ConvertedFiles = 0); /// Export by keys, or by the current filter when no keys are given. public sealed record ExportRequest(IReadOnlyList? Ids, string? Query); @@ -222,7 +225,7 @@ public sealed record CheckNowDto(string Status, string Message, string? Token); public sealed record RemoveAccountRequest(bool DeleteFiles); -public sealed record RemoveAccountDto(string Outcome, int DeletedEntries, int Problems, string Message); +public sealed record RemoveAccountDto(string Outcome, int DeletedEntries, int Problems, string Message, int ConvertedFiles = 0); public sealed record ParseRequest(string Text); diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs index a922b45..c1c4f83 100644 --- a/src/Febe.Web/Api/ExportApi.cs +++ b/src/Febe.Web/Api/ExportApi.cs @@ -2,6 +2,7 @@ using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; using Febe.Web.Export; using Febe.Web.Library; @@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.WebUtilities; +using ItalianText = Febe.Core.Engine.ItalianText; namespace Febe.Web.Api; @@ -30,57 +32,72 @@ public static class ExportApi private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10); + /// + /// One change of the export settings at a time: each saves all its keys from what it loaded, and the queue of the + /// library conversion compares before and after, so two quick changes must not both start from the same before. + /// + private static readonly SemaphoreSlim SettingsGate = new(1, 1); + public static void Map(IEndpointRouteBuilder endpoints) { ArgumentNullException.ThrowIfNull(endpoints); endpoints.MapGet("/api/export", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) => - { - var service = await hub.GetAsync(ct).ConfigureAwait(false); - var root = hub.RootFor(context); - var d = SettingsApi.Deps.From(services); - var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock); - var state = ExportRoots.Evaluate(root); - var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); - var names = await UsernamesAsync(storage, ct).ConfigureAwait(false); - var mapped = new List(destinations.Count); - foreach (var destination in destinations) - { - var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); - mapped.Add(Destination(destination, names, counts, root, clock)); - } + ApiHttp.Json(await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportOverviewDto)); - var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); - var active = service.ActiveRunIds; - var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id)); - var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming; - return ApiHttp.Json( - new ExportOverviewDto( - new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder), - SamePost(settings.SamePost), - mapped.FirstOrDefault(x => x.Scope == "general"), - [.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)], - active, - unfinished, - new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders)), - FebeJsonContext.Default.ExportOverviewDto); - }); - - endpoints.MapPut("/api/export/settings", async (HttpContext context, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => + endpoints.MapPut("/api/export/settings", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, LibraryConversionQueue queue, LibraryChanges changes, IClock clock, IServiceProvider services, CancellationToken ct) => { var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false); - var samePost = body.SamePost?.Trim().ToLowerInvariant() switch - { - "oneperaccount" => SamePostCopies.OnePerAccount, - "oneonly" => SamePostCopies.OneOnly, - _ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."), - }; - var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); - await (settings with { SamePost = samePost }).SaveAsync(storage.Settings, ct).ConfigureAwait(false); + var (before, after, queued) = await SaveSettingsAsync(body, storage, queue, ct).ConfigureAwait(false); changes.Publish(new LibraryChange(clock.Now, null, "export")); - return ApiHttp.Message(samePost == SamePostCopies.OneOnly - ? "Fatto: lo stesso post in due account si copia una volta sola." - : "Fatto: lo stesso post in due account si copia una volta per ciascun account."); + var overview = await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false); + return ApiHttp.Json(new ExportSettingsSavedDto(SettingsMessage(before, after, body, queued), overview, queued), FebeJsonContext.Default.ExportSettingsSavedDto); + }); + + endpoints.MapGet("/api/export/library-conversion", async (IFebeStorage storage, LibraryConversionWorker worker, CancellationToken ct) => + ApiHttp.Json(await ConversionAsync(storage, worker, ct).ConfigureAwait(false), FebeJsonContext.Default.LibraryConversionDto)); + + endpoints.MapGet("/api/export/library-conversion/preview", async (string? photo, string? video, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct) => + { + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + settings = settings with + { + LibraryPhotoFormat = ParseFormat(photo, MediaKind.Photo) ?? settings.LibraryPhotoFormat, + LibraryVideoFormat = ParseFormat(video, MediaKind.Video) ?? settings.LibraryVideoFormat, + }; + + // The question is about the kind being turned on or changed: the other one is not counted (it already had + // its answer). Without either, both formats set now. + var (photoAsked, videoAsked) = (!string.IsNullOrWhiteSpace(photo), !string.IsNullOrWhiteSpace(video)); + var both = !photoAsked && !videoAsked; + var preview = settings.ConvertsLibrary + ? await queue.PreviewExistingAsync( + both || photoAsked ? LibraryConversionRules.FormatFor(MediaKind.Photo, settings) : null, + both || videoAsked ? LibraryConversionRules.FormatFor(MediaKind.Video, settings) : null, + ct).ConfigureAwait(false) + : new LibraryConversionPreview(0, 0); + return ApiHttp.Json(new LibraryConversionPreviewDto(preview.Files, preview.Bytes, PreviewText(preview)), FebeJsonContext.Default.LibraryConversionPreviewDto); + }); + + endpoints.MapPost("/api/export/library-conversion/retry", async (LibraryConversionQueue queue, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var reset = await queue.RetryFailedAsync(ct).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, null, "export")); + return ApiHttp.Message(reset == 0 + ? "Nessuna conversione da riprovare." + : $"{Core.Engine.ItalianText.Count(reset, "file torna", "file tornano")} in coda per la conversione."); + }); + + endpoints.MapPost("/api/export/library-conversion/pause", async (LibraryConversionQueue queue, CancellationToken ct) => + { + await queue.SetPausedAsync(true, ct).ConfigureAwait(false); + return ApiHttp.Message("Conversione della libreria interrotta: i file già convertiti restano, riprendi quando vuoi."); + }); + + endpoints.MapPost("/api/export/library-conversion/resume", async (LibraryConversionQueue queue, CancellationToken ct) => + { + await queue.SetPausedAsync(false, ct).ConfigureAwait(false); + return ApiHttp.Message("La conversione della libreria riprende."); }); endpoints.MapGet("/api/export/folders", async (string? path, HttpContext context, ExportHub hub, CancellationToken ct) => @@ -228,7 +245,7 @@ public static class ExportApi var request = Request(body, clock); var service = await hub.GetAsync(ct).ConfigureAwait(false); var plan = await GuardAsync(() => service.PlanAsync(request, ct)).ConfigureAwait(false); - return ApiHttp.Json(Plan(plan, hub.RootFor(context)), FebeJsonContext.Default.ExportPlanDto); + return ApiHttp.Json(Plan(plan, hub.RootFor(context), request.Frames is not null), FebeJsonContext.Default.ExportPlanDto); }); endpoints.MapPost("/api/export/start", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) => @@ -237,7 +254,7 @@ public static class ExportApi var request = Request(body, clock); var service = await hub.GetAsync(ct).ConfigureAwait(false); var start = await GuardAsync(() => service.StartAsync(request, ct)).ConfigureAwait(false); - return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); + return ApiHttp.Json(Job(start, hub.RootFor(context), request.Frames is not null), FebeJsonContext.Default.ExportJobDto); }); endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) => @@ -275,18 +292,25 @@ public static class ExportApi throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo."); } + // The same form only (tappa E3, D11): a JPG copy taken again is not «già copiato» because of a whole one. if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c => - c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant)) + c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && SameForm(c, copy))) { throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella."); } // Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two // entries, and the first one found may be a file the library lost (it would end «non presente in libreria»). + // The file the copy was made from comes first, then one of the same kind. var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); - var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) ?? present[0]; + var kind = copy.MediaId is { } copiedId ? (await storage.Media.GetAsync(copiedId, ct).ConfigureAwait(false))?.Kind : null; + var location = present + .Where(l => account is not null && files.Resolve(account, l.Media) is not null) + .OrderBy(l => l.Media.Id == copy.MediaId ? 0 : l.Media.Kind == kind ? 1 : 2) + .FirstOrDefault() ?? present[0]; var service = await hub.GetAsync(ct).ConfigureAwait(false); - var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false); + var exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt); + var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true, Exact: exact), ct)).ConfigureAwait(false); return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); }); @@ -382,8 +406,9 @@ public static class ExportApi Run(report.Run, summary, labels, clock, service.ActiveRunIds.Contains(id)), ItemCounts(report.ByState), report.BytesCopied, - [.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed))], - [.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]), + [.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed, a.AsIs))], + [.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))], + [.. report.Notes.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]), FebeJsonContext.Default.ExportReportDto); }); } @@ -498,7 +523,9 @@ public static class ExportApi reachable, freeBytes, destination.IsOrphan, - destination.RemovedAccountUsername); + destination.RemovedAccountUsername, + destination.PhotoFormat is { } photo ? FormatName(photo) : null, + destination.VideoFormat is { } video ? FormatName(video) : null); } /// A destination with its counts, read from the database. @@ -536,7 +563,7 @@ public static class ExportApi counts.Failed); } - public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root) + public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root, bool frames = false) { ArgumentNullException.ThrowIfNull(plan); return new ExportPlanDto( @@ -547,7 +574,344 @@ public static class ExportApi plan.NotExported, plan.Missing, [.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))], - plan.HasDestination); + plan.HasDestination, + [.. plan.AsIs.Select(a => new ExportPlanAsIsDto(a.Label, a.Files))], + plan.Converted, + plan.Lossy, + plan.Videos, + plan.PhotosSkipped, + plan.Frames, + plan.OverCap, + PlanSummary(plan, frames)); + } + + /// + /// The line of «Copia in…» (tappa E3, §10.3): «312 file · 41 già copiati, saltati · circa 3 HEIC copiati come sono · + /// circa 4,2 GB · con perdita»; for frames «12 fotogrammi da 4 video · le 3 foto si saltano». + /// + public static string PlanSummary(ExportPlan plan, bool frames) + { + ArgumentNullException.ThrowIfNull(plan); + var parts = new List(); + if (frames) + { + parts.Add($"{ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi")} da {ItalianText.Number(plan.Videos)} video"); + if (plan.PhotosSkipped > 0) + { + parts.Add(PhotosSkippedText(plan.PhotosSkipped)); + } + + if (plan.OverCap > 0) + { + parts.Add(ExportFrames.OverCapMessage); + } + } + else + { + parts.Add(ItalianText.Count(plan.Files, "file", "file")); + if (plan.AlreadyCopied > 0) + { + parts.Add(plan.AlreadyCopied == 1 ? "1 già copiato, saltato" : $"{ItalianText.Number(plan.AlreadyCopied)} già copiati, saltati"); + } + + foreach (var asIs in plan.AsIs.Where(a => a.Files > 0)) + { + parts.Add($"circa {ItalianText.Number(asIs.Files)} {asIs.Label} {(asIs.Files == 1 ? "copiato com'è" : "copiati come sono")}"); + } + + if (plan.Bytes > 0) + { + parts.Add("circa " + ItalianText.Bytes(plan.Bytes)); + } + } + + if (plan.Lossy) + { + parts.Add("con perdita"); + } + + return string.Join(" · ", parts); + } + + /// «Le 4 foto si saltano» (frames are taken from videos only). + public static string PhotosSkippedText(int photos) => + photos == 1 ? "la foto si salta" : $"le {ItalianText.Number(photos)} foto si saltano"; + + /// The wire name of a format (D21): original, jpg, png, webplossless, mp4. + public static string FormatName(ExportFormat format) => format.ToString().ToLowerInvariant(); + + /// + /// PUT /api/export/settings under : loads the settings, applies the request, saves them + /// and tells the queue of the library conversion, all before the next change starts. + /// + private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsAsync( + ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct) + { + await SettingsGate.WaitAsync(ct).ConfigureAwait(false); + try + { + return await SaveSettingsCoreAsync(body, storage, queue, ct).ConfigureAwait(false); + } + finally + { + SettingsGate.Release(); + } + } + + private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsCoreAsync( + ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct) + { + var queued = 0; + var before = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var after = before; + if (body.SamePost is { } samePostText) + { + after = after with + { + SamePost = samePostText.Trim().ToLowerInvariant() switch + { + "oneperaccount" => SamePostCopies.OnePerAccount, + "oneonly" => SamePostCopies.OneOnly, + _ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."), + }, + }; + } + + after = after with + { + PhotoFormat = ParseFormat(body.PhotoFormat, MediaKind.Photo) ?? after.PhotoFormat, + VideoFormat = ParseFormat(body.VideoFormat, MediaKind.Video) ?? after.VideoFormat, + LibraryPhotoFormat = ParseFormat(body.LibraryPhotoFormat, MediaKind.Photo) ?? after.LibraryPhotoFormat, + LibraryVideoFormat = ParseFormat(body.LibraryVideoFormat, MediaKind.Video) ?? after.LibraryVideoFormat, + }; + if (body.SamePost is null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null && body.ConvertExisting is null) + { + throw new BadRequestException("Niente da salvare: scegli un'impostazione."); + } + + // The formats, their «dal» keys and the queue of a format replaced in one transaction; once it is stored, what + // follows no longer depends on the request (a closed tab must not leave half of it). + await queue.SaveSettingsAsync(before, after, ct).ConfigureAwait(false); + if (body.ConvertExisting == true) + { + // «Anche i N già in libreria» answers the question about the kind being changed: the other kind keeps + // what was answered for it («Solo i nuovi» included, Q29). + var photo = Changed(MediaKind.Photo, body.LibraryPhotoFormat, before, after); + var video = Changed(MediaKind.Video, body.LibraryVideoFormat, before, after); + if (photo is not null || video is not null) + { + queued = await queue.EnqueueExistingAsync(photo, video, CancellationToken.None).ConfigureAwait(false); + } + } + + return (before, after, queued); + } + + /// + /// The library format of when this request set it and it changed (the kind the question + /// «Convertire anche i N file già in libreria?» was asked about); null otherwise, or when it is «Originale». + /// + private static ExportFormat? Changed(MediaKind kind, string? requested, ExportSettings before, ExportSettings after) + { + var now = LibraryConversionRules.FormatFor(kind, after); + return requested is not null && now != LibraryConversionRules.FormatFor(kind, before) ? now : null; + } + + /// + /// A format of from its wire name; null for null or empty (nothing chosen). 400 for a name + /// that is not a format of that kind. + /// + public static ExportFormat? ParseFormat(string? text, MediaKind kind) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + + var name = text.Trim(); + var format = Enum.GetValues().FirstOrDefault(f => string.Equals(FormatName(f), name, StringComparison.OrdinalIgnoreCase), (ExportFormat)(-1)); + var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format); + if (!Enum.IsDefined(format) || !fits) + { + throw new BadRequestException(kind == MediaKind.Photo + ? "Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita." + : "Per i video si sceglie Originale o MP4."); + } + + return format; + } + + /// A frame format from its wire name: JPG, PNG or WEBP senza perdita; PNG when none is given (§16, domanda 35). + public static ExportFormat ParseFrameFormat(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return ExportFormat.Png; + } + + var format = ParseFormat(text, MediaKind.Photo); + return format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless + ? format.Value + : throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita."); + } + + /// Which frames, from the page's request. + public static ExportFramesRequest Frames(FramesRequestDto body) + { + ArgumentNullException.ThrowIfNull(body); + var mode = body.Mode?.Trim().ToLowerInvariant() switch + { + "istante" or "at" => FrameMode.At, + "ogni" or "every" => FrameMode.Every, + "numero" or "count" => FrameMode.Count, + _ => throw new BadRequestException("Modo dei fotogrammi sconosciuto: «Questo istante», «Uno ogni k secondi» o «N in tutto»."), + }; + return new ExportFramesRequest( + mode, + mode == FrameMode.At ? TimeSpan.FromMilliseconds(Math.Max(0, body.AtMs ?? 0)) : null, + mode == FrameMode.Every && body.EveryMs is { } every ? TimeSpan.FromMilliseconds(every) : null, + mode == FrameMode.Count ? body.Count : null, + ParseFrameFormat(body.Format)); + } + + /// Two copy rows of the same form: variant, format and frame instant (the full identity of §4.10 without the file). + public static bool SameForm(ExportCopy a, ExportCopy b) + { + ArgumentNullException.ThrowIfNull(a); + ArgumentNullException.ThrowIfNull(b); + return a.Variant == b.Variant && a.Format == b.Format && a.FrameAt == b.FrameAt; + } + + /// The wire name of a state of a conversion of the library; a failure that never converts is asIs. + public static string ConversionState(MediaConversion conversion) + { + ArgumentNullException.ThrowIfNull(conversion); + return conversion.State switch + { + MediaConversionState.Pending => "pending", + MediaConversionState.Converted => "converted", + MediaConversionState.Failed when LibraryConversionText.IsAsIs(conversion.LastError) => "asIs", + MediaConversionState.Failed => "failed", + MediaConversionState.Superseded => "superseded", + _ => "removed", + }; + } + + /// The state of the conversion of the library, for the settings and the Dashboard. + public static async Task ConversionAsync(IFebeStorage storage, LibraryConversionWorker worker, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(worker); + var status = await worker.StatusAsync(ct).ConfigureAwait(false); + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var parts = new List(); + if (status.Pending > 0) + { + parts.Add("In coda " + ItalianText.Number(status.Pending)); + } + + if (status.Converted > 0) + { + parts.Add("convertiti " + ItalianText.Number(status.Converted)); + } + + if (status.Failed > 0) + { + parts.Add("non riusciti " + ItalianText.Number(status.Failed)); + } + + if (status.AsIs > 0) + { + parts.Add("non si convertono " + ItalianText.Number(status.AsIs)); + } + + var text = parts.Count == 0 ? "Nessun file convertito" : ItalianText.Capitalize(string.Join(" · ", parts)); + if (status.Paused) + { + text = "In pausa · " + text; + } + + return new LibraryConversionDto(status.Pending, status.Converted, status.Failed, status.AsIs, status.Paused, status.Waiting, text, settings.ConvertsLibrary); + } + + private static string PreviewText(LibraryConversionPreview preview) => preview.Files switch + { + 0 => "Nessun file già in libreria da convertire.", + 1 => $"Anche quello già in libreria: l'originale occupa circa {ItalianText.Bytes(preview.Bytes)}; il convertito può occupare di più.", + var n => $"Anche i {ItalianText.Number(n)} già in libreria: gli originali occupano circa {ItalianText.Bytes(preview.Bytes)}; i convertiti possono occupare di più.", + }; + + private static string SettingsMessage(ExportSettings before, ExportSettings after, ExportSettingsRequest body, int queued) + { + var parts = new List(); + if (body.SamePost is not null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null) + { + return after.SamePost == SamePostCopies.OneOnly + ? "Fatto: lo stesso post in due account si copia una volta sola." + : "Fatto: lo stesso post in due account si copia una volta per ciascun account."; + } + + if (before.PhotoFormat != after.PhotoFormat || before.VideoFormat != after.VideoFormat) + { + parts.Add("i nuovi formati valgono per i file non ancora copiati"); + } + + if (before.ConvertsLibrary != after.ConvertsLibrary || before.LibraryPhotoFormat != after.LibraryPhotoFormat || before.LibraryVideoFormat != after.LibraryVideoFormat) + { + parts.Add(!after.ConvertsLibrary + ? "la conversione della libreria è spenta, i file convertiti restano dove sono" + : queued > 0 + ? $"si convertono i nuovi file e {ItalianText.Count(queued, "file già in libreria", "file già in libreria")}" + : "si convertono i nuovi file; l'originale resta"); + } + else if (queued > 0) + { + parts.Add($"{ItalianText.Count(queued, "file già in libreria entra", "file già in libreria entrano")} in coda"); + } + + return parts.Count == 0 ? "Fatto." : "Fatto: " + string.Join("; ", parts) + "."; + } + + /// Impostazioni → Esportazione: root, destinations, settings, formats and the conversion of the library. + public static async Task OverviewAsync(HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(hub); + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(library); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(services); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var root = hub.RootFor(context); + var d = SettingsApi.Deps.From(services); + var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock); + var state = ExportRoots.Evaluate(root); + var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); + var names = await UsernamesAsync(storage, ct).ConfigureAwait(false); + var mapped = new List(destinations.Count); + foreach (var destination in destinations) + { + var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); + mapped.Add(Destination(destination, names, counts, root, clock)); + } + + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var active = service.ActiveRunIds; + var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id)); + var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming; + var worker = services.GetService(typeof(LibraryConversionWorker)) as LibraryConversionWorker; + return new ExportOverviewDto( + new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder), + SamePost(settings.SamePost), + mapped.FirstOrDefault(x => x.Scope == "general"), + [.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)], + active, + unfinished, + new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders), + FormatName(settings.PhotoFormat), + FormatName(settings.VideoFormat), + FormatName(settings.LibraryPhotoFormat), + FormatName(settings.LibraryVideoFormat), + worker is null ? null : await ConversionAsync(storage, worker, ct).ConfigureAwait(false)); } /// The request of a «Copia in…»: exactly one selection. @@ -581,7 +945,16 @@ public static class ExportApi selection = new ExportSelection.Account(body.AccountId!.Value); } - return new ExportJobRequest(selection, body.CopyAgain); + var photo = ParseFormat(body.PhotoFormat, MediaKind.Photo); + var video = ParseFormat(body.VideoFormat, MediaKind.Video); + var formats = photo is null && video is null ? null : new ExportFormatChoice(photo, video); + var frames = body.Frames is { } f ? Frames(f) : null; + if (frames is not null && formats is not null) + { + throw new BadRequestException("I fotogrammi non si chiedono insieme ai formati delle copie."); + } + + return new ExportJobRequest(selection, body.CopyAgain, Formats: formats, Frames: frames); } // ---------------------------------------------------------------------------------------------- helpers @@ -630,7 +1003,13 @@ public static class ExportApi Clean(body.HighlightNamingScheme), Clean(body.ProfileNamingScheme), body.Automatic, - body.OnlyNew); + body.OnlyNew, + DestinationFormat(body.PhotoFormat, MediaKind.Photo), + DestinationFormat(body.VideoFormat, MediaKind.Video)); + + /// A destination's format: null, empty or general is «Come le impostazioni generali». + private static ExportFormat? DestinationFormat(string? text, MediaKind kind) => + string.Equals(text?.Trim(), "general", StringComparison.OrdinalIgnoreCase) ? null : ParseFormat(text, kind); private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); @@ -646,9 +1025,9 @@ public static class ExportApi _ => "finished", }; - private static ExportJobDto Job(ExportStart start, ExportRootOptions root) => new( + private static ExportJobDto Job(ExportStart start, ExportRootOptions root, bool frames = false) => new( [.. start.Runs.Select(r => r.Id)], - Plan(start.Plan, root), + Plan(start.Plan, root, frames), start.Runs.Count == 0 ? "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria." : "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione."); diff --git a/src/Febe.Web/Api/ExportDtos.cs b/src/Febe.Web/Api/ExportDtos.cs index 56b1111..75c2119 100644 --- a/src/Febe.Web/Api/ExportDtos.cs +++ b/src/Febe.Web/Api/ExportDtos.cs @@ -43,11 +43,16 @@ public sealed record ExportDestinationDto( bool? Reachable = null, long? FreeBytes = null, bool Orphan = false, - string? FormerUsername = null); + string? FormerUsername = null, + string? PhotoFormat = null, + string? VideoFormat = null); /// /// GET /api/export: Impostazioni → Esportazione and the notice of the Dashboard. : /// onePerAccount or oneOnly. : interrupted or paused jobs («Riprendi»). +/// Formats (tappa E3) on the wire: original, jpg, png, webplossless, mp4; the +/// library ones are original while the conversion of the library is off. : +/// the state of that conversion. /// public sealed record ExportOverviewDto( ExportRootDto Root, @@ -56,10 +61,45 @@ public sealed record ExportOverviewDto( IReadOnlyList Own, IReadOnlyList ActiveRunIds, int UnfinishedRuns, - ExportSchemesDto Library); + ExportSchemesDto Library, + string PhotoFormat = "original", + string VideoFormat = "original", + string LibraryPhotoFormat = "original", + string LibraryVideoFormat = "original", + LibraryConversionDto? LibraryConversion = null); -/// PUT /api/export/settings: «Lo stesso post in due account», onePerAccount or oneOnly. -public sealed record ExportSettingsRequest(string SamePost); +/// +/// The conversion of the library (tappa E3, spec §4.10): files in the queue, converted, failed («Riprova»), that never +/// convert (: «non si convertono»), «In pausa», and why it waits (Italian, null when it does +/// not): an import, a copy or a rebuild at work, an engine session, low space. : the status line +/// («In coda 12 · convertiti 340 · non riusciti 2 · non si convertono 3»). : a library format is +/// chosen. +/// +public sealed record LibraryConversionDto(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, string Text, bool On); + +/// +/// PUT /api/export/settings, every field optional (null keeps it): «Lo stesso post in due account» +/// (onePerAccount or oneOnly), the formats of the copies and of the library (wire names). +/// : the answer «Anche i N già in libreria» when a library format is turned on or +/// changed; it queues the files of the kinds whose library format this request changes, never those of the other. +/// +public sealed record ExportSettingsRequest( + string? SamePost = null, + string? PhotoFormat = null, + string? VideoFormat = null, + string? LibraryPhotoFormat = null, + string? LibraryVideoFormat = null, + bool? ConvertExisting = null); + +/// What PUT /api/export/settings did: a message, the overview after the change, the files queued. +public sealed record ExportSettingsSavedDto(string Message, ExportOverviewDto Overview, int Queued = 0); + +/// +/// «Converti anche i N file già in libreria?»: that would enter the queue, the bytes of their +/// originals («circa») and the line of the question («gli originali occupano circa 3,1 GB; i convertiti possono occupare +/// di più»). +/// +public sealed record LibraryConversionPreviewDto(int Files, long Bytes, string Text); /// Docker: the subfolders of a folder of /esporta. is "" for the root. public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList Folders); @@ -88,7 +128,9 @@ public sealed record ExportDestinationRequest( string? HighlightNamingScheme, string? ProfileNamingScheme, bool Automatic = false, - bool OnlyNew = true); + bool OnlyNew = true, + string? PhotoFormat = null, + string? VideoFormat = null); /// A saved destination (a change of folder gives a new id) and the warnings of its schemes. public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList Warnings); @@ -97,7 +139,10 @@ public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, /// What a «Copia in…» copies: exactly one of (files of «Tutte le foto» or the viewer), /// (a grouped selection), (the filter of the Libreria, as its query /// string, with grouped or files) or (every file of -/// the account). : «Copia di nuovo anche i tolti o superati». +/// the account). : «Copia di nuovo anche i tolti o superati». Tappa E3: +/// / override the destination's for this request only +/// (null: as the destination); makes it a frames job («Fotogrammi…» → «Nella cartella delle +/// copie»), without formats. /// public sealed record CopyJobRequestDto( IReadOnlyList? MediaIds, @@ -105,7 +150,20 @@ public sealed record CopyJobRequestDto( string? Query, string? Mode, long? AccountId, - bool CopyAgain = false); + bool CopyAgain = false, + string? PhotoFormat = null, + string? VideoFormat = null, + FramesRequestDto? Frames = null); + +/// +/// Which frames (spec §4.10 «Fotogrammi»): istante (at ), +/// ogni (every , at least 100) or numero ( in all, 1 to +/// 1.000); jpg, png (the default) or webplossless. +/// +public sealed record FramesRequestDto(string? Mode, long? AtMs = null, long? EveryMs = null, int? Count = null, string? Format = null); + +/// Files of a plan copied as they are, of one kind («3 HEIC copiati come sono»). +public sealed record ExportPlanAsIsDto(string Label, int Files); /// A destination of a plan. : why it cannot be written now (paused, not reachable). public sealed record ExportPlanDestinationDto( @@ -123,7 +181,12 @@ public sealed record ExportPlanDestinationDto( /// /// The summary of «Copia in…» (spec §10.3). /: what will be written /// (with «Copia di nuovo» the tolti/superati too). : of accounts that are not exported -/// (switch off, no destination, type not taken). : not in the library. +/// (switch off, no destination, type not taken). : not in the library. Tappa E3: +/// files predicted copied as they are («circa»), predicted +/// converted, «con perdita»; a frames job: , +/// , and (videos over 1.000 +/// frames: the job is refused). : the line of the dialog («312 file · 41 già copiati, saltati · +/// circa 3 HEIC copiati come sono · circa 4,2 GB · con perdita»). /// public sealed record ExportPlanDto( int Files, @@ -133,7 +196,15 @@ public sealed record ExportPlanDto( int NotExported, int Missing, IReadOnlyList Destinations, - bool HasDestination = true); + bool HasDestination = true, + IReadOnlyList? AsIs = null, + int Converted = 0, + bool Lossy = false, + int Videos = 0, + int PhotosSkipped = 0, + int Frames = 0, + int OverCap = 0, + string? Summary = null); /// The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed. public sealed record ExportJobDto(IReadOnlyList RunIds, ExportPlanDto Plan, string Message); @@ -174,24 +245,33 @@ public sealed record ExportRunDto( int Done, bool Running = false); -/// The files of one account in a job ( counts written and adopted files). -public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed); +/// +/// The files of one account in a job ( counts written and adopted files). +/// : files copied as they are, by kind («HEIC» → 3). +/// +public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed, IReadOnlyDictionary? AsIs = null); /// A file of the report that needs a look, with its reason in Italian. public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text); -/// The report of a job (at most 200 problems). +/// +/// The report of a job (at most 200 problems). (tappa E3): files copied or adopted with a note +/// (what a conversion could not keep, a file copied as it is), at most 200. +/// public sealed record ExportReportDto( ExportRunDto Run, IReadOnlyDictionary ByState, long BytesCopied, IReadOnlyList Accounts, - IReadOnlyList Problems); + IReadOnlyList Problems, + IReadOnlyList? Notes = null); /// /// A copy of a file of the viewer (spec §4.6, §4.10). : copied, removed, superseded, failed; -/// : whole (tappa E2 copies originals only). : with «Una copia -/// sola», the account it was copied for when it is another one. : «Copia di nuovo». +/// : whole, converted or frame; : the wire name of a converted copy or +/// of a frame (null for a whole one); and («0:01,25») for a +/// frame. : with «Una copia sola», the account it was copied for when it is another one. +/// : «Copia di nuovo» of that same form. : why it failed. /// public sealed record MediaCopyDto( long CopyId, @@ -203,7 +283,17 @@ public sealed record MediaCopyDto( long? FrameAtMs, LocalTimeDto At, string? ForAccount, - bool CanCopyAgain); + bool CanCopyAgain, + string? FrameLabel = null, + string? Notes = null); + +/// +/// A converted file of the library next to its original (tappa E3, spec §4.10): (wire name), +/// pending, converted, failed, asIs («non si converte»), +/// superseded or removed, its size, and : what was not kept, or why it failed or +/// does not convert. : the file is on disk («Scarica», «Mostra nella cartella»). +/// +public sealed record MediaConversionDto(long Id, string Format, string State, long? Bytes, string? Notes, bool Available, string? FileName); /// /// «Copie esterne» of the account card. : the effective one (its own folder, else the @@ -218,3 +308,51 @@ public sealed record ExportAccountDto( int NotCopied, int RemovedOrSuperseded, int Failed); + +// ---------------------------------------------------------------------------------------------- frames (tappa E3) + +/// +/// GET /api/media/{id}/frames/info: whether frames can be taken from the video (: +/// «Fotogramma non disponibile per questo video»), its length and its size as shown (rotation applied). +/// +public sealed record FrameInfoDto(bool Available, string? Unavailable, long DurationMs, int Width, int Height, bool HasAudio); + +/// +/// One instant of a frames request: the one asked for, the one really shown (the frame's identity, ms rounded up), its +/// label («0:01,25») and the suffix of its file name (_t0m01s250, _f001). +/// +public sealed record FrameInstantDto(int Index, long RequestedMs, long ActualMs, string Label, string Suffix); + +/// +/// GET /api/media/{id}/frames/instants: the instants of a mode for one video (at most 1.000). : +/// how many it asks; : why none is given (over 1.000, not available). +/// +public sealed record FrameInstantsDto(long DurationMs, int Total, bool OverCap, string? Problem, IReadOnlyList Instants); + +/// +/// The frames of a selection («Fotogrammi…» from the selection bars): exactly one of , +/// (every video of those entries) or with , +/// and which frames. +/// +public sealed record FramesSelectionRequest(IReadOnlyList? MediaIds, IReadOnlyList? EntryIds, string? Query, string? Mode, FramesRequestDto? Frames); + +/// +/// POST /api/frames/plan: what «Scarica» would give. : videos without frames (or +/// not on disk); : videos over 1.000 frames; : more than +/// 500 frames («Nella cartella delle copie»); : more than 20 (only outside engine sessions +/// and other long work). : why «Scarica» cannot run now; : the line +/// of the dialog («12 fotogrammi da 4 video · le 3 foto si saltano»). +/// +public sealed record FramesPlanDto(int Videos, int PhotosSkipped, int NotAvailable, int Frames, int OverCap, bool TooManyToDownload, bool NeedsQuiet, string? Problem, string Summary); + +/// A download of frames ready: open once within 5 minutes. +public sealed record FramesTokenDto(string Token, int Frames, string Url); + +/// A converted file of the library («Mostra nella cartella»). +public sealed record ConversionActionRequest(long ConversionId); + +/// +/// What «Elimina dalla libreria» would remove (tappa E3, spec §4.6): the entries, their files and the converted files of +/// the library made from them («elimino gli elementi interi, 9 file e 2 file convertiti»). +/// +public sealed record EntryDeletionPreviewDto(int Entries, int Files, int ConvertedFiles); diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs index afb1c94..8049afc 100644 --- a/src/Febe.Web/Api/FebeJsonContext.cs +++ b/src/Febe.Web/Api/FebeJsonContext.cs @@ -105,4 +105,14 @@ namespace Febe.Web.Api; [JsonSerializable(typeof(IReadOnlyList))] [JsonSerializable(typeof(ExportReportDto))] [JsonSerializable(typeof(ExportAccountDto))] +[JsonSerializable(typeof(ExportSettingsSavedDto))] +[JsonSerializable(typeof(LibraryConversionDto))] +[JsonSerializable(typeof(LibraryConversionPreviewDto))] +[JsonSerializable(typeof(FrameInfoDto))] +[JsonSerializable(typeof(FrameInstantsDto))] +[JsonSerializable(typeof(FramesSelectionRequest))] +[JsonSerializable(typeof(FramesPlanDto))] +[JsonSerializable(typeof(FramesTokenDto))] +[JsonSerializable(typeof(ConversionActionRequest))] +[JsonSerializable(typeof(EntryDeletionPreviewDto))] public sealed partial class FebeJsonContext : JsonSerializerContext; diff --git a/src/Febe.Web/Api/FramesApi.cs b/src/Febe.Web/Api/FramesApi.cs new file mode 100644 index 0000000..ccd47aa --- /dev/null +++ b/src/Febe.Web/Api/FramesApi.cs @@ -0,0 +1,424 @@ +using System.Globalization; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Core.Storage; +using Febe.Web.Export; +using Febe.Web.Library; +using Febe.Web.Native; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.StaticFiles; +using ItalianText = Febe.Core.Engine.ItalianText; + +namespace Febe.Web.Api; + +/// +/// Frames of videos and the converted files of the library (spec §4.10, tappa E3): what a video allows, a frame at an +/// instant (previews of the dialog «Fotogrammi…» and «Scarica» of one frame), the instants of a mode, the plan of +/// «Scarica» for a selection and its download (one image, or a zip made while it is sent), and the files of the +/// conversion of the library («Scarica», «Mostra nella cartella»). Frames to a folder of the copies go through +/// /api/export/plan and /start with frames. Nothing here writes a file. +/// +public static class FramesApi +{ + private static readonly FileExtensionContentTypeProvider ContentTypes = new(); + + public static void Map(IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + + endpoints.MapGet("/api/media/{id:long}/frames/info", async (long id, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) => + { + var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false); + var info = await frames.InfoAsync(video.Path, video.Media.Sha256, ct).ConfigureAwait(false); + return ApiHttp.Json( + new FrameInfoDto(info.Available, info.Unavailable, (long)info.Duration.TotalMilliseconds, info.Width, info.Height, info.HasAudio), + FebeJsonContext.Default.FrameInfoDto); + }); + + endpoints.MapGet("/api/media/{id:long}/frame", async (long id, long? at, string? format, int? max, string? download, HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) => + { + var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false); + int? side = max is { } m ? Math.Clamp(m, 16, FrameService.MaxPreview) : null; + var chosen = string.IsNullOrWhiteSpace(format) && side is not null ? ExportFormat.Jpg : ExportApi.ParseFrameFormat(format); + var instant = TimeSpan.FromMilliseconds(Math.Max(0, at ?? 0)); + var frame = await frames.FrameAsync(video.Path, video.Media.Sha256, instant, chosen, side, ct).ConfigureAwait(false); + if (download is "1" or "true") + { + context.Response.Headers.CacheControl = "private, no-cache"; + var name = FrameService.FileName(Stem(video.Media), FrameMode.At, frame.Actual, 0, 1, chosen); + return Results.File(frame.Data, frame.ContentType, name); + } + + // The same file, instant, size and format always give the same picture. + context.Response.Headers.CacheControl = "private, max-age=600"; + return Results.File(frame.Data, frame.ContentType); + }); + + endpoints.MapGet("/api/media/{id:long}/frames/instants", async (long id, string? mode, long? at, long? every, int? count, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) => + { + var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false); + var request = ExportApi.Frames(new FramesRequestDto(mode ?? "numero", at, every, count, "png")); + ExportPlanner.Validate(new ExportJobRequest(new ExportSelection.Media([id]), Frames: request)); + var info = await frames.InfoAsync(video.Path, video.Media.Sha256, ct).ConfigureAwait(false); + var durationMs = (long)info.Duration.TotalMilliseconds; + if (!info.Available) + { + return ApiHttp.Json(new FrameInstantsDto(durationMs, 0, false, info.Unavailable ?? VideoFrameReader.NotAvailableMessage, []), FebeJsonContext.Default.FrameInstantsDto); + } + + var total = ExportFrames.FrameCount(info.Duration, request); + if (total > ExportFrames.MaxPerVideo) + { + return ApiHttp.Json(new FrameInstantsDto(durationMs, (int)Math.Min(total, int.MaxValue), true, ExportFrames.OverCapMessage, []), FebeJsonContext.Default.FrameInstantsDto); + } + + var (_, targets) = await frames.LocateAsync(video.Path, video.Media.Sha256, request, ct).ConfigureAwait(false); + var list = targets.Select(t => new FrameInstantDto( + t.Index, + (long)t.Requested.TotalMilliseconds, + ExportFrames.ActualMs(t.Actual), + ExportFrames.Label(t.Actual), + ExportFrames.Suffix(request.Mode, t.Actual, t.Index, targets.Count))).ToList(); + return ApiHttp.Json(new FrameInstantsDto(durationMs, list.Count, false, null, list), FebeJsonContext.Default.FrameInstantsDto); + }); + + endpoints.MapPost("/api/frames/plan", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FramesSelectionRequest).ConfigureAwait(false); + var plan = await SelectionAsync(body, storage, files, frames, clock, ct).ConfigureAwait(false); + var problem = Problem(plan, gate, session); + return ApiHttp.Json( + new FramesPlanDto(plan.VideoCount, plan.Photos, plan.NotAvailable, plan.Frames, plan.OverCap, plan.Frames > FrameService.MaxDownload, plan.Frames > FrameService.MaxAnyTime, problem, Summary(plan)), + FebeJsonContext.Default.FramesPlanDto); + }); + + endpoints.MapPost("/api/frames/download-token", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FramesSelectionRequest).ConfigureAwait(false); + var plan = await SelectionAsync(body, storage, files, frames, clock, ct).ConfigureAwait(false); + if (plan.Frames == 0) + { + throw new BadRequestException(plan.OverCap > 0 ? ExportFrames.OverCapMessage : FrameService.NothingText); + } + + if (plan.Frames > FrameService.MaxDownload) + { + throw new BadRequestException(FrameService.TooManyText); + } + + if (Problem(plan, gate, session) is { } problem) + { + throw new ApiStatusException(409, problem); + } + + var token = frames.Register(new FrameDownloadPlan(plan.Request.Mode, plan.Request.Format, plan.Videos)); + return ApiHttp.Json(new FramesTokenDto(token, plan.Frames, "/api/frames/download/" + token), FebeJsonContext.Default.FramesTokenDto); + }); + + endpoints.MapGet("/api/frames/download/{token}", async (string token, HttpContext context, IFebeStorage storage, FebeLibrary library, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock) => + { + var plan = frames.Take(token) ?? throw new NotFoundException("Questo scaricamento non vale più: scegli di nuovo «Scarica»."); + var ct = context.RequestAborted; + if (plan.Frames == 1) + { + var video = plan.Videos.First(v => v.Instants.Count > 0); + var one = await frames.FrameAsync(video.Path, null, video.Instants[0], plan.Format, null, ct).ConfigureAwait(false); + var name = FrameService.FileName(video.Stem, plan.Mode, one.Actual, 0, video.Instants.Count, plan.Format); + context.Response.Headers.CacheControl = "private, no-cache"; + await Results.File(one.Data, one.ContentType, name).ExecuteAsync(context).ConfigureAwait(false); + return; + } + + IDisposable? lease = null; + if (plan.Frames > FrameService.MaxAnyTime) + { + if (session.InSession) + { + throw new ApiStatusException(409, FrameService.SessionText); + } + + if (!gate.TryEnter(LongWorkKind.FrameDownload, out lease, out var busy)) + { + throw new ApiStatusException(409, LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy ?? LongWorkKind.FrameDownload)); + } + } + + try + { + var publication = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).SetFileTimeToPublication; + context.Response.ContentType = "application/zip"; + context.Response.Headers.CacheControl = "private, no-cache"; + context.Response.Headers.ContentDisposition = $"attachment; filename=\"febe-fotogrammi-{FrameService.Day(clock.Now, clock.LocalZone)}.zip\""; + await context.Response.StartAsync(ct).ConfigureAwait(false); + try + { + await frames.WriteZipAsync(context.Response.Body, plan, publication, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is OperationCanceledException or IOException) + { + // The page went away, or stopped reading: the zip is left unfinished, so the browser says it failed. + context.Abort(); + } + } + finally + { + lease?.Dispose(); + } + }); + + endpoints.MapGet("/api/conversions/{id:long}/file", async (long id, string? download, HttpContext context, IFebeStorage storage, IConversionFileResolver files, CancellationToken ct) => + { + var path = await ConversionPathAsync(storage, files, id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Il file convertito non è sul disco."); + if (!ContentTypes.TryGetContentType(path, out var type)) + { + type = "application/octet-stream"; + } + + context.Response.Headers.CacheControl = "private, no-cache"; + return download is "1" or "true" + ? Results.File(path, type, Path.GetFileName(path), enableRangeProcessing: true) + : Results.File(path, type, enableRangeProcessing: true); + }); + + endpoints.MapPost("/api/conversions/show-in-folder", async (HttpContext context, IFebeStorage storage, IConversionFileResolver files, INativeShell shell, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConversionActionRequest).ConfigureAwait(false); + var path = await ConversionPathAsync(storage, files, body.ConversionId, ct).ConfigureAwait(false) + ?? throw new NotFoundException("Il file convertito non è sul disco: forse è stato spostato o cancellato fuori da Febe."); + if (!await shell.ShowInFolderAsync(path, ct).ConfigureAwait(false)) + { + throw new BadRequestException("Qui non si può aprire la cartella: usa «Scarica»."); + } + + return ApiHttp.Message("Cartella aperta."); + }); + } + + /// The rows of the converted files of one library file for the viewer (tappa E3, §16 domanda 30). + public static IReadOnlyList Conversions(IConversionFileResolver files, Account account, IEnumerable rows) + { + ArgumentNullException.ThrowIfNull(files); + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(rows); + return [.. rows + .Where(r => r.State != MediaConversionState.Removed) + .Select(r => + { + var path = files.Resolve(account, r); + return new MediaConversionDto( + r.Id, + ExportApi.FormatName(r.Format), + ExportApi.ConversionState(r), + r.Bytes, + LibraryConversionText.Note(r.LastError), + path is not null, + r.RelativePath is { } relative ? Path.GetFileName(LibraryLayout.ToPlatform(relative)) : null); + })]; + } + + // ---------------------------------------------------------------------------------------------- selection + + /// What «Scarica» would give for a selection: the videos with their instants, and what is left out. + /// Videos of the selection (with frames or not). + /// Frames in all (from the lengths of the database when the videos were not opened). + private sealed record FramesSelection(ExportFramesRequest Request, List Videos, int VideoCount, int Photos, int NotAvailable, int OverCap, int Frames); + + private static async Task SelectionAsync(FramesSelectionRequest body, IFebeStorage storage, IMediaFileResolver files, FrameService frames, IClock clock, CancellationToken ct) + { + var request = body.Frames is { } f ? ExportApi.Frames(f) : throw new BadRequestException("Scegli quali fotogrammi."); + var selection = ExportApi.Request(new CopyJobRequestDto(body.MediaIds, body.EntryIds, body.Query, body.Mode, null), clock).Selection; + ExportPlanner.Validate(new ExportJobRequest(selection, Frames: request)); + var accounts = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id); + + // The present videos of the selection, in media order; photos are counted and skipped. + var candidates = new List(); + var photos = 0; + var missing = 0; + long after = 0; + while (true) + { + var page = await storage.Exports.ListCandidatesAsync(selection, after, 500, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].MediaId; + foreach (var c in page) + { + if (c.MediaKind != MediaKind.Video) + { + photos++; + } + else if (!EntryStateRules.IsPresent(c.State) || c.RelativePath is null || !accounts.ContainsKey(c.AccountId)) + { + missing++; + } + else + { + candidates.Add(c); + } + } + } + + // Few enough to download: each video is opened (from the cache when it was seen) for its length and whether + // frames can be taken; otherwise the lengths of the database are enough to say «scegli la cartella delle copie». + var probe = candidates.Count <= FrameService.MaxDownload; + var videos = new List(); + var notAvailable = missing; + var overCap = 0; + var unprobedFrames = 0L; + foreach (var c in candidates) + { + var account = accounts[c.AccountId]; + TimeSpan duration; + string? path = null; + if (probe) + { + var media = await storage.Media.GetAsync(c.MediaId, ct).ConfigureAwait(false); + path = media is null ? null : files.Resolve(account, media); + if (path is null) + { + notAvailable++; + continue; + } + + var info = await frames.InfoAsync(path, c.Sha256, ct).ConfigureAwait(false); + if (!info.Available) + { + notAvailable++; + continue; + } + + duration = info.Duration; + } + else + { + duration = c.Duration ?? TimeSpan.Zero; + } + + var count = ExportFrames.FrameCount(duration, request); + if (count > ExportFrames.MaxPerVideo) + { + overCap++; + continue; + } + + if (!probe) + { + unprobedFrames += count; + continue; + } + + var entry = await storage.Entries.GetAsync(c.EntryId, ct).ConfigureAwait(false); + videos.Add(new FrameDownloadVideo( + account.Username, + path!, + Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(c.RelativePath!)), + ExportFrames.Instants(duration, request), + entry?.PublishedAt ?? clock.Now)); + } + + var total = probe ? videos.Sum(v => v.Instants.Count) : (int)Math.Min(unprobedFrames, int.MaxValue); + return new FramesSelection(request, videos, candidates.Count + missing, photos, notAvailable, overCap, total); + } + + /// Why «Scarica» cannot run now; null when it can. + private static string? Problem(FramesSelection plan, LongWorkGate gate, IEngineSessionState session) + { + if (plan.Frames == 0) + { + return plan.OverCap > 0 ? ExportFrames.OverCapMessage : FrameService.NothingText; + } + + if (plan.Frames > FrameService.MaxDownload) + { + return FrameService.TooManyText; + } + + if (plan.Frames > FrameService.MaxAnyTime) + { + if (session.InSession) + { + return FrameService.SessionText; + } + + if (gate.Busy is { } busy) + { + return LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy); + } + } + + return null; + } + + /// «12 fotogrammi da 4 video · le 3 foto si saltano · 3 video senza fotogrammi». + private static string Summary(FramesSelection plan) + { + var withFrames = plan.VideoCount - plan.NotAvailable - plan.OverCap; + var parts = new List + { + withFrames > 0 + ? $"{ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi")} da {ItalianText.Number(withFrames)} video" + : ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi"), + }; + if (plan.Photos > 0) + { + parts.Add(ExportApi.PhotosSkippedText(plan.Photos)); + } + + if (plan.NotAvailable > 0) + { + parts.Add(plan.NotAvailable == 1 ? "1 video senza fotogrammi" : $"{ItalianText.Number(plan.NotAvailable)} video senza fotogrammi"); + } + + if (plan.OverCap > 0) + { + parts.Add(plan.OverCap == 1 ? "1 video oltre 1.000 fotogrammi" : $"{ItalianText.Number(plan.OverCap)} video oltre 1.000 fotogrammi"); + } + + return string.Join(" · ", parts); + } + + // ---------------------------------------------------------------------------------------------- helpers + + private sealed record VideoFile(Account Account, Media Media, string Path); + + /// A present video of the library on disk; 404 otherwise. + private static async Task VideoAsync(IFebeStorage storage, IMediaFileResolver files, long mediaId, CancellationToken ct) + { + var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato."); + if (media.Kind != MediaKind.Video) + { + throw new BadRequestException("I fotogrammi si prendono solo dai video."); + } + + var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato."); + var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato."); + var path = files.Resolve(account, media) ?? throw new NotFoundException("Il file non è sul disco."); + return new VideoFile(account, media, path); + } + + private static string Stem(Media media) => + media.RelativePath is { } relative ? Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(relative)) : "video-" + media.Id.ToString(CultureInfo.InvariantCulture); + + /// The file of a Converted or Superseded conversion of a present account, or null. + private static async Task ConversionPathAsync(IFebeStorage storage, IConversionFileResolver files, long id, CancellationToken ct) + { + var conversion = await storage.Conversions.GetAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Conversione non trovata."); + if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded)) + { + throw new NotFoundException("Questa conversione non ha un file."); + } + + var media = await storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato."); + var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato."); + var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato."); + return files.Resolve(account, conversion); + } +} diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs index 1e2bee4..30afcda 100644 --- a/src/Febe.Web/Api/LibraryApi.cs +++ b/src/Febe.Web/Api/LibraryApi.cs @@ -5,6 +5,7 @@ using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; +using Febe.Web.Export; using Febe.Web.Library; using Febe.Web.Native; using Microsoft.AspNetCore.Builder; @@ -136,8 +137,8 @@ public static class LibraryApi return ApiHttp.Message("Cartella aperta."); }); - endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct) => - ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EntryDto)); + endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, FrameService frames, IConversionFileResolver conversions, CancellationToken ct) => + ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct, frames, conversions).ConfigureAwait(false), FebeJsonContext.Default.EntryDto)); endpoints.MapPost("/api/entries/{id:long}/open-on-instagram", async (long id, IFebeStorage storage, INativeShell shell, IClock clock, CancellationToken ct) => { @@ -165,12 +166,43 @@ public static class LibraryApi var results = await library.Deletion.DeleteManyAsync(body.Ids, mode, ct).ConfigureAwait(false); var deleted = results.Count(r => r.Found); var removed = results.Sum(r => r.DeletedFiles.Count); + var converted = results.Sum(r => r.ConvertedFiles); var problems = results.SelectMany(r => r.FailedFiles).ToList(); changes.Publish(new LibraryChange(clock.Now, null, "deleted")); var message = (deleted == 1 ? "Elemento eliminato dalla libreria" : $"{Core.Engine.ItalianText.Number(deleted)} elementi eliminati dalla libreria") + + (converted > 0 ? $", con {Core.Engine.ItalianText.Count(converted, "file convertito", "file convertiti")}" : string.Empty) + (mode == DeletionMode.Remember ? ": Febe non li scarica di nuovo." : ": se ricompaiono, Febe li scarica di nuovo.") + (problems.Count > 0 ? $" {Core.Engine.ItalianText.Count(problems.Count, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: chiudi i programmi che li usano e riprova." : string.Empty); - return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message), FebeJsonContext.Default.DeleteResultDto); + return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message, converted), FebeJsonContext.Default.DeleteResultDto); + }); + + // What «Elimina dalla libreria» would remove (tappa E3): the confirmation also counts the converted files. + endpoints.MapPost("/api/entries/delete-preview", async (HttpContext context, IFebeStorage storage, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.EntryIdsRequest).ConfigureAwait(false); + if (body.Ids.Count > 5000) + { + throw new BadRequestException("Troppi elementi in una richiesta."); + } + + var entries = 0; + var files = 0; + var converted = 0; + foreach (var id in body.Ids.Distinct()) + { + var stored = await storage.Entries.GetWithMediaAsync(id, ct).ConfigureAwait(false); + if (stored is null) + { + continue; + } + + entries++; + files += stored.Media.Count(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)); + converted += (await storage.Conversions.ListByEntryAsync(id, ct).ConfigureAwait(false)) + .Count(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null); + } + + return ApiHttp.Json(new EntryDeletionPreviewDto(entries, files, converted), FebeJsonContext.Default.EntryDeletionPreviewDto); }); endpoints.MapPost("/api/entries/export", async (HttpContext context, IFebeStorage storage, IClock clock) => @@ -220,7 +252,12 @@ public static class LibraryApi tile.FilePosition); } - public static async Task EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct) + /// + /// Everything the viewer shows of an entry. With , a video says whether frames can be taken + /// (from the cache by SHA-256, else probed within a short time: null when it takes longer); with + /// , each file lists its converted files of the library (tappa E3). + /// + public static async Task EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct, FrameService? frames = null, IConversionFileResolver? conversions = null) { ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(files); @@ -236,6 +273,7 @@ public static class LibraryApi var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account))); var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false); var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false); + var converted = conversions is null ? [] : await storage.Conversions.ListByEntryAsync(id, ct).ConfigureAwait(false); var media = new List(stored.Media.Count); foreach (var m in stored.Media) { @@ -263,7 +301,9 @@ public static class LibraryApi path is not null, ApiMapping.State(m.State), damaged, - copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false))); + copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false), + await FramesAvailableAsync(frames, m, path, ct).ConfigureAwait(false), + conversions is null ? null : FramesApi.Conversions(conversions, account, converted.Where(c => c.MediaId == m.Id)))); } return new EntryDto( @@ -311,9 +351,14 @@ public static class LibraryApi var tile = tiles[i]; if (tile.FilePosition is not null) { - if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark) && mark == ExportMark.Copied) + if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark)) { - list[i] = list[i] with { Copies = "copied" }; + list[i] = mark switch + { + ExportMark.Copied => list[i] with { Copies = "copied" }, + ExportMark.FrameOnly => list[i] with { Copies = "frameOnly" }, + _ => list[i], + }; } } else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies)) @@ -322,6 +367,7 @@ public static class LibraryApi { ExportMark.Copied => list[i] with { Copies = "copied" }, ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due }, + ExportMark.FrameOnly => list[i] with { Copies = "frameOnly" }, _ => list[i], }; } @@ -402,7 +448,7 @@ public static class LibraryApi && !destination.IsRetired && Enabled && Effective?.Id == destination.Id - && !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && c.Variant == copy.Variant); + && !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && ExportApi.SameForm(c, copy)); shown.Add(new MediaCopyDto( copy.Id, ExportDestinations.Label(destination), @@ -415,10 +461,12 @@ public static class LibraryApi _ => "frame", }, copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(), - copy.FrameAt is { } frame ? (long)frame.TotalMilliseconds : null, + copy.FrameAt is { } frame ? ExportFrames.ActualMs(frame) : null, ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone), own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null, - canCopyAgain)); + canCopyAgain, + copy.FrameAt is { } frameAt ? ExportFrames.Label(frameAt) : null, + copy.State == ExportCopyState.Failed ? copy.LastError : null)); if (shown.Count == MaxShown) { break; @@ -436,6 +484,30 @@ public static class LibraryApi /// Febe does not decode, a HEIC or a picture over the limit is told from its first bytes, without reading it whole. /// The file is only read, never touched (rule 12). /// + private static readonly TimeSpan FramesProbeTime = TimeSpan.FromSeconds(3); + + /// Whether «Fotogramma» works on a video on disk; null for a photo, a missing file or a slow probe. + private static async Task FramesAvailableAsync(FrameService? frames, Media media, string? path, CancellationToken ct) + { + if (frames is null || media.Kind != MediaKind.Video || path is null) + { + return null; + } + + try + { + return (await frames.InfoAsync(path, media.Sha256, ct).WaitAsync(FramesProbeTime, ct).ConfigureAwait(false)).Available; + } + catch (TimeoutException) + { + return null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } + private static async Task IsDamagedAsync(Media media, string? path, CancellationToken ct) => media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false); diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs index 87555f5..1bb9b53 100644 --- a/src/Febe.Web/Demo/DemoEngine.cs +++ b/src/Febe.Web/Demo/DemoEngine.cs @@ -390,12 +390,28 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask; } -/// Files of the demo: the shared sample pictures. Videos have only their cover. +/// Files of the demo: the shared sample pictures, and one short video for every video (tappa E3). public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver { public string? Resolve(Account account, Media media) { ArgumentNullException.ThrowIfNull(media); - return media.Kind == MediaKind.Photo && media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null; + return media.Kind switch + { + MediaKind.Photo => media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null, + MediaKind.Video => world.VideoFile is { } video && File.Exists(video) ? video : null, + _ => null, + }; + } +} + +/// The converted files of the demo's library: the rows seeded (tappa E3). +public sealed class DemoConversionFileResolver(DemoWorld world) : IConversionFileResolver +{ + public string? Resolve(Account account, MediaConversion conversion) + { + ArgumentNullException.ThrowIfNull(conversion); + return conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded + && world.ConversionFiles.TryGetValue(conversion.Id, out var path) && File.Exists(path) ? path : null; } } diff --git a/src/Febe.Web/Demo/DemoExport.cs b/src/Febe.Web/Demo/DemoExport.cs index 215d677..6582ad2 100644 --- a/src/Febe.Web/Demo/DemoExport.cs +++ b/src/Febe.Web/Demo/DemoExport.cs @@ -1,4 +1,6 @@ +using System.Security.Cryptography; using Febe.Core.Abstractions; +using Febe.Core.Codecs.Images; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; @@ -11,7 +13,8 @@ namespace Febe.Web.Demo; /// The copies to external folders of the demo (spec §10.6, tappa E2): a general folder «Disco USB», an own folder /// «Studio Lumen» for @studio.lumen.demo, @il.porto.demo not exported, and for @marta.demo about two thirds of its /// photos copied by the real engine (a completed job with its report), one «Tolto», one «Superato» and one «Errore», -/// and a job left «interrotto» for the Dashboard. Everything lives in the demo's temporary folder, whose «esporta» is +/// and a job left «interrotto» for the Dashboard; tappa E3 adds a copy converted to PNG, a frame of a video and two +/// conversions of the library («Convertito», «Non si converte»). Everything lives in the demo's temporary folder, whose «esporta» is /// the demo's /esporta: the counts, the marks and the «Copie» filter come from the same rows the engine wrote. /// public static class DemoExport @@ -117,6 +120,179 @@ public static class DemoExport } await HistoryAsync(database, world, general, marta, photos, rest, clock, ct).ConfigureAwait(false); + + // Tappa E3: a converted copy by the real engine (PNG, «Copia in…» → «Cambia»), a frame and two conversions. + if (rest.Skip(FormatsFrom).FirstOrDefault() is { } toConvert) + { + await service.StartAsync( + new ExportJobRequest(new ExportSelection.Media([toConvert.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)), + ct).ConfigureAwait(false); + await service.WaitAsync(ct).ConfigureAwait(false); + } + + await FrameAsync(database, world, general, marta, clock, ct).ConfigureAwait(false); + await ConversionsAsync(root, database, world, [.. rest.Skip(FormatsFrom + 1).Take(2)], clock, ct).ConfigureAwait(false); + } + + /// The instant the demo's frame copy was asked at; the demo video shows its 10th picture then (1.125 s). + public static readonly TimeSpan FrameAsked = TimeSpan.FromMilliseconds(1234); + + // rest[0..2] are «Tolto», «Superato» and «Errore», rest[3..14] the interrupted job. + private const int FormatsFrom = 15; + + /// + /// A frame of a video of @marta.demo in the general folder, as «Fotogrammi…» → «Nella cartella delle copie» writes it: + /// the demo shares one video file whose SHA-256 is not the one recorded, so the engine would refuse it (rule: the + /// frames are of the file recorded); the row and its PNG are written here. + /// + private static async Task FrameAsync(FebeDatabase database, DemoWorld world, ExportDestination general, Account marta, IClock clock, CancellationToken ct) + { + if (world.VideoFile is not { } videoFile || !File.Exists(videoFile) + || await VideoAsync(database, marta, ct).ConfigureAwait(false) is not { } video + || await database.Entries.GetAsync(video.EntryId, ct).ConfigureAwait(false) is not { } entry) + { + return; + } + + byte[] png; + TimeSpan actual; + await using (var stream = File.OpenRead(videoFile)) + { + using var reader = VideoFrameReader.Open(stream, out var info); + if (!info.Available) + { + return; + } + + var target = reader.Locate([FrameAsked])[0]; + using var frame = reader.Decode([target], ct).Single(); + png = ImageConverter.Encode(frame.Image, ImageFormat.Png, null); + actual = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual)); + } + + var suffix = ExportFrames.Suffix(FrameMode.At, actual, 0, 1); + var segments = ExportPaths.Segments(general, LibraryNaming.Default, marta, entry, video, null, false, world.Zone, new ExportNameOptions(".png", suffix)); + var relative = ExportPaths.RelativePathFor(general, segments, keepSuffix: suffix); + var framePath = Path.Combine(general.RootPath, LibraryLayout.ToPlatform(relative)); + Directory.CreateDirectory(Path.GetDirectoryName(framePath)!); + await using (var output = new FileStream(framePath, FileMode.CreateNew, FileAccess.Write)) + { + await output.WriteAsync(png, ct).ConfigureAwait(false); + } + + await database.Exports.AddCopyAsync( + new ExportCopy + { + DestinationId = general.Id, + AccountId = marta.Id, + MediaId = video.Id, + SourceSha256 = video.Sha256!, + Variant = ExportVariant.Frame, + Format = ExportFormat.Png, + FrameAt = actual, + State = ExportCopyState.Copied, + RelativePath = relative, + Bytes = png.Length, + CopySha256 = Convert.ToHexStringLower(SHA256.HashData(png)), + CopiedAt = clock.Now.AddDays(-1), + }, + ct).ConfigureAwait(false); + } + + /// + /// Two conversions of the library (spec §4.10): a PNG next to its original («Convertito», its file in the demo's + /// «convertiti» folder) and one that never converts («Non si converte»). The demo never runs the conversion. + /// + private static async Task ConversionsAsync(string root, FebeDatabase database, DemoWorld world, IReadOnlyList photos, IClock clock, CancellationToken ct) + { + var now = clock.Now; + if (photos.Count > 0 && photos[0] is { Sha256: { } sha, RelativePath: { } original } converted + && world.Pictures.TryGetValue(sha, out var source) && File.Exists(source)) + { + var result = await Task.Run(() => ImageConverter.Convert(File.ReadAllBytes(source), ImageFormat.Png), ct).ConfigureAwait(false); + var folder = Path.Combine(root, "convertiti"); + Directory.CreateDirectory(folder); + var file = Path.Combine(folder, sha + ".png"); + await File.WriteAllBytesAsync(file, result.Data, ct).ConfigureAwait(false); + var row = await database.Conversions.AddAsync( + new MediaConversion + { + MediaId = converted.Id, + Format = ExportFormat.Png, + State = MediaConversionState.Converted, + SourceSha256 = sha, + RelativePath = Path.ChangeExtension(original, ".png"), + Bytes = result.Data.Length, + Sha256 = Convert.ToHexStringLower(SHA256.HashData(result.Data)), + CreatedAt = now.AddDays(-4), + ConvertedAt = now.AddDays(-4), + StateChangedAt = now.AddDays(-4), + LastError = ExportText.JoinNotes([.. result.NotCarried, .. result.Losses]), + }, + ct).ConfigureAwait(false); + world.ConversionFiles[row.Id] = file; + } + + if (photos.Count > 1 && photos[1].Sha256 is { } asIsSha) + { + await database.Conversions.AddAsync( + new MediaConversion + { + MediaId = photos[1].Id, + Format = ExportFormat.Png, + State = MediaConversionState.Failed, + SourceSha256 = asIsSha, + CreatedAt = now.AddDays(-4), + StateChangedAt = now.AddDays(-4), + LastError = ImageConversionLosses.AsIsAnimated, + }, + ct).ConfigureAwait(false); + } + } + + /// + /// A present video of an account whose SHA-256 the fewest files share (the demo's videos take the SHA-256 of their + /// cover picture, and the marks of the copies go by SHA-256): the newest among those. + /// + private static async Task VideoAsync(FebeDatabase database, Account account, CancellationToken ct) + { + var files = new Dictionary(StringComparer.Ordinal); + var videos = new List(); + LibraryCursor? cursor = null; + do + { + var page = await database.Entries.QueryLibraryAsync( + new LibraryQuery { Filter = new LibraryFilter { AccountIds = [account.Id] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 }, + ct).ConfigureAwait(false); + foreach (var tile in page.Tiles) + { + if (tile.CoverSha256 is { } sha) + { + files[sha] = files.GetValueOrDefault(sha) + 1; + } + + if (tile.CoverKind == MediaKind.Video && tile.CoverMediaId is { } id) + { + videos.Add(id); + } + } + + cursor = page.Older; + } + while (cursor is not null); + + Media? best = null; + foreach (var id in videos) + { + if (await database.Media.GetAsync(id, ct).ConfigureAwait(false) is { Sha256: { } sha, RelativePath: not null } media + && EntryStateRules.IsPresent(media.State) + && (best is null || files.GetValueOrDefault(sha) < files.GetValueOrDefault(best.Sha256!))) + { + best = media; + } + } + + return best; } /// One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto». diff --git a/src/Febe.Web/Demo/DemoHost.cs b/src/Febe.Web/Demo/DemoHost.cs index 0774c2c..16cafe7 100644 --- a/src/Febe.Web/Demo/DemoHost.cs +++ b/src/Febe.Web/Demo/DemoHost.cs @@ -99,6 +99,7 @@ public sealed class DemoHost : IAsyncDisposable services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs index 60b86f0..4615f41 100644 --- a/src/Febe.Web/Demo/DemoSeeder.cs +++ b/src/Febe.Web/Demo/DemoSeeder.cs @@ -1,6 +1,8 @@ +using System.Collections.Concurrent; using System.Globalization; using System.Security.Cryptography; using Febe.Core.Abstractions; +using Febe.Core.Codecs.H264; using Febe.Core.Domain; using Febe.Core.Library; using Febe.Core.Storage; @@ -64,6 +66,15 @@ public sealed class DemoWorld /// Sample pictures in the proportions of a story (the browser preview of the demo). public IReadOnlyList StoryPictures { get; init; } = []; + + /// + /// The demo's one video file (H.264, 2 s, tappa E3), served for every video of the demo so that «Fotogramma» works. + /// Its bytes are not those recorded for the videos (they share the SHA-256 of their cover picture). + /// + public string? VideoFile { get; init; } + + /// The files of the seeded conversions of the library, by row id (written by ). + public ConcurrentDictionary ConversionFiles { get; } = new(); } /// @@ -583,8 +594,11 @@ public static class DemoSeeder var mine = accounts.First(a => a.Spec.Mine).Account; var variants = await DemoDuplicates.SeedAsync(storage, thumbnails, pictures, now, ct).ConfigureAwait(false); + var videoFile = Path.Combine(pictures, "video-dimostrativo.mp4"); + await File.WriteAllBytesAsync(videoFile, await Task.Run(H264PcmWriter.DemoVideo, ct).ConfigureAwait(false), ct).ConfigureAwait(false); return new DemoWorld { + VideoFile = videoFile, SeededAt = now, Zone = zone, Pictures = pool.Files.Concat(variants).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal), diff --git a/src/Febe.Web/Export/FrameService.cs b/src/Febe.Web/Export/FrameService.cs new file mode 100644 index 0000000..c7d0e3f --- /dev/null +++ b/src/Febe.Web/Export/FrameService.cs @@ -0,0 +1,471 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.IO.Compression; +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Web.Api; + +namespace Febe.Web.Export; + +/// A frame encoded for the page: its bytes, media type, extension and the instant really shown. +public sealed record EncodedFrame(byte[] Data, string ContentType, string Extension, TimeSpan Actual); + +/// The frames of one video in a download: where it is, its account and name, and the instants asked. +/// The account (first segment of the zip entries). +/// The library file. +/// The library file name without extension. +/// The instants asked, in increasing order. +/// When the entry was published (the time of the zip entries, D18). +public sealed record FrameDownloadVideo(string Username, string Path, string Stem, IReadOnlyList Instants, DateTimeOffset PublishedAt); + +/// A «Scarica» of frames waiting for its address to be opened. +public sealed record FrameDownloadPlan(FrameMode Mode, ExportFormat Format, IReadOnlyList Videos) +{ + /// The frames in all. + public int Frames => Videos.Sum(v => v.Instants.Count); +} + +/// +/// Frames of videos for the page (spec §4.10 «Fotogrammi», tappa E3, D14): what a video allows (kept for 64 files by +/// SHA-256), a single frame for the previews and «Scarica», and the zip of several. Previews and single frames go one at +/// a time (one decoder busy, never a queue of heavy work) within ; they are not long work and run at +/// any time. A zip of up to frames runs at any time too; from 21 to +/// it takes and never runs during an engine session. Nothing here writes a +/// file: the frames go to the page only. +/// +public sealed class FrameService(IClock clock) +{ + /// The longest side of a preview. + public const int MaxPreview = 480; + + /// The most frames of a zip at any time. + public const int MaxAnyTime = 20; + + /// The most frames of «Scarica». + public const int MaxDownload = 500; + + /// Video infos kept. + public const int CacheSize = 64; + + public const string TimeoutText = "Il fotogramma richiede troppo tempo: scegli la cartella delle copie"; + + public const string SessionText = "Il motore è in sessione: per più di 20 fotogrammi riprova fra poco"; + + public const string TooManyText = "Per più di 500 fotogrammi scegli la cartella delle copie"; + + public const string NothingText = "Nessun fotogramma da scaricare: scegli dei video con i fotogrammi disponibili."; + + private static readonly TimeSpan TokenLife = TimeSpan.FromMinutes(5); + + private readonly SemaphoreSlim _one = new(1, 1); + private readonly Lock _cacheGate = new(); + private readonly Dictionary _cache = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _tokens = new(StringComparer.Ordinal); + private long _uses; + + /// The time a preview or a single frame may take, waiting included. + public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30); + + /// + /// A write of the zip that makes no progress for this long aborts the download: each piece of 64 KB sent restarts + /// the time, so a slow link that keeps reading is never cut. + /// + public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60); + + /// The timers of (a seam: a test moves their time only as its link sends). + public TimeProvider StallTime { get; init; } = TimeProvider.System; + + /// What a video allows, from the cache by SHA-256 when known (the file is opened only the first time). + public async Task InfoAsync(string path, string? sha256, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(path); + if (sha256 is { Length: > 0 } && Cached(sha256) is { } cached) + { + return cached; + } + + var info = await Task.Run( + () => + { + using var stream = OpenRead(path); + using var reader = VideoFrameReader.Open(stream, out var found); + return found; + }, + ct).ConfigureAwait(false); + if (sha256 is { Length: > 0 }) + { + Remember(sha256, info); + } + + return info; + } + + /// + /// The instants of for the video at with the samples really shown; + /// empty when the video has no frames. over 1.000 frames. + /// + public Task<(VideoFrameInfo Info, IReadOnlyList Targets)> LocateAsync(string path, string? sha256, ExportFramesRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(request); + return Task.Run( + () => + { + using var stream = OpenRead(path); + using var reader = VideoFrameReader.Open(stream, out var info); + if (sha256 is { Length: > 0 }) + { + Remember(sha256, info); + } + + if (!info.Available) + { + return (info, (IReadOnlyList)[]); + } + + var instants = ExportFrames.Instants(info.Duration, request); + return (info, reader.Locate(instants)); + }, + ct); + } + + /// + /// The frame shown at , encoded in ; with + /// scaled down to fit it (a preview). One at a time, within : past it + /// 503. when the video has no frames. + /// + public async Task FrameAsync(string path, string? sha256, TimeSpan at, ExportFormat format, int? maxSide, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(path); + var image = MediaConverter.ImageFormatOf(format) ?? throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita."); + using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct); + budget.CancelAfter(Budget); + try + { + await _one.WaitAsync(budget.Token).ConfigureAwait(false); + try + { + return await Task.Run(() => Decode(path, sha256, at, image, maxSide, budget.Token), budget.Token).ConfigureAwait(false); + } + finally + { + _one.Release(); + } + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + throw new ApiStatusException(503, TimeoutText); + } + } + + /// Keeps a download for , for one use; returns its token. + public string Register(FrameDownloadPlan plan) + { + ArgumentNullException.ThrowIfNull(plan); + var now = clock.Now; + foreach (var (key, value) in _tokens) + { + if (value.Expires <= now) + { + _tokens.TryRemove(key, out _); + } + } + + var token = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16)); + _tokens[token] = (plan, now + TokenLife); + return token; + } + + /// The download of , taken once; null when unknown, used or expired. + public FrameDownloadPlan? Take(string token) + { + if (string.IsNullOrEmpty(token) || !_tokens.TryRemove(token, out var found)) + { + return null; + } + + return found.Expires > clock.Now ? found.Plan : null; + } + + /// The name of a frame file: the library stem, the suffix of its instant (D13), the format's extension. + public static string FileName(string stem, FrameMode mode, TimeSpan actual, int index, int count, ExportFormat format) => + WindowsFileNames.SanitizeSegment(stem + ExportFrames.Suffix(mode, actual, index, count) + MediaConverter.ExtensionOf(format)); + + /// + /// Writes the zip of into as it is made (not compressed: the + /// images are), entries account/name unique as the copies number them («x (2).png»), dated per + /// (the publication, else now), within the years a zip can hold. + /// + public async Task WriteZipAsync(Stream output, FrameDownloadPlan plan, bool publicationTime, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(plan); + var image = MediaConverter.ImageFormatOf(plan.Format) ?? throw new ArgumentException("Formato del fotogramma non valido.", nameof(plan)); + var guarded = new StallGuardStream(output, WriteStall, StallTime); + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false); + await using (zip.ConfigureAwait(false)) + { + foreach (var video in plan.Videos) + { + var folder = WindowsFileNames.SanitizeSegment(video.Username); + var time = EntryTime(publicationTime ? video.PublishedAt : clock.Now); + await foreach (var (index, frame) in FramesAsync(video, plan, image, ct).ConfigureAwait(false)) + { + var name = FileName(video.Stem, plan.Mode, frame.Actual, index, video.Instants.Count, plan.Format); + var relative = folder + "/" + name; + var suffix = ExportFrames.Suffix(plan.Mode, frame.Actual, index, video.Instants.Count); + for (var attempt = 2; !names.Add(relative); attempt++) + { + relative = ExportPaths.NumberedName("febe", folder + "/" + name, attempt, keepSuffix: suffix); + } + + var entry = zip.CreateEntry(relative, CompressionLevel.NoCompression); + entry.LastWriteTime = time; + var stream = await entry.OpenAsync(ct).ConfigureAwait(false); + await using (stream.ConfigureAwait(false)) + { + await stream.WriteAsync(frame.Data, ct).ConfigureAwait(false); + } + } + } + } + + await guarded.CompleteAsync(ct).ConfigureAwait(false); + } + + /// The frames of one video of a download, encoded, in decoding order, with their index among its instants. + public async IAsyncEnumerable<(int Index, EncodedFrame Frame)> FramesAsync(FrameDownloadVideo video, FrameDownloadPlan plan, ImageFormat image, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(video); + ArgumentNullException.ThrowIfNull(plan); + Stream stream; + try + { + stream = OpenRead(video.Path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + yield break; // the file went since the plan: its frames are left out + } + + await using (stream.ConfigureAwait(false)) + { + var (reader, info) = await Task.Run(() => (VideoFrameReader.Open(stream, out var found), found), ct).ConfigureAwait(false); + using (reader) + { + if (!info.Available) + { + yield break; + } + + var targets = reader.Locate(video.Instants); + using var frames = reader.Decode(targets, ct).GetEnumerator(); + var shown = new HashSet(); + while (await Task.Run(() => frames.MoveNext(), ct).ConfigureAwait(false)) + { + using var frame = frames.Current; + if (!shown.Add(frame.Actual.Ticks)) + { + continue; // two instants on the same picture give it once, as the copies do + } + + var data = await Task.Run(() => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false); + yield return (frame.Index, new EncodedFrame(data, ContentType(image), MediaConverter.ExtensionOf(plan.Format), frame.Actual)); + } + } + } + } + + /// The media type of an image format written by Febe. + public static string ContentType(ImageFormat format) => format switch + { + ImageFormat.Jpeg => "image/jpeg", + ImageFormat.Png => "image/png", + _ => "image/webp", + }; + + private EncodedFrame Decode(string path, string? sha256, TimeSpan at, ImageFormat image, int? maxSide, CancellationToken ct) + { + using var stream = OpenRead(path); + using var reader = VideoFrameReader.Open(stream, out var info); + if (sha256 is { Length: > 0 }) + { + Remember(sha256, info); + } + + if (!info.Available) + { + throw new NotFoundException(info.Unavailable ?? VideoFrameReader.NotAvailableMessage); + } + + var targets = reader.Locate([at]); + using var frame = reader.Decode(targets, ct).FirstOrDefault() ?? throw new NotFoundException(VideoFrameReader.NotAvailableMessage); + ct.ThrowIfCancellationRequested(); + var source = frame.Image; + if (maxSide is { } max && Math.Max(source.Width, source.Height) > max) + { + var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, max); + using var small = ImageResampler.Resize(source, width, height); + return new EncodedFrame(ImageConverter.Encode(small, image, null), ContentType(image), Extension(image), frame.Actual); + } + + return new EncodedFrame(ImageConverter.Encode(source, image, null), ContentType(image), Extension(image), frame.Actual); + } + + private static string Extension(ImageFormat image) => image switch + { + ImageFormat.Jpeg => ".jpg", + ImageFormat.Png => ".png", + _ => ".webp", + }; + + /// The time of a zip entry: within 1980-2107, the years a zip can hold. + private DateTimeOffset EntryTime(DateTimeOffset instant) + { + var local = TimeZoneInfo.ConvertTime(instant, clock.LocalZone); + var min = new DateTimeOffset(1980, 1, 1, 0, 0, 0, local.Offset); + var max = new DateTimeOffset(2107, 12, 31, 23, 59, 58, local.Offset); + return local < min ? min : local > max ? max : local; + } + + private VideoFrameInfo? Cached(string sha256) + { + lock (_cacheGate) + { + if (_cache.TryGetValue(sha256, out var found)) + { + _cache[sha256] = (found.Info, ++_uses); + return found.Info; + } + + return null; + } + } + + private void Remember(string sha256, VideoFrameInfo info) + { + lock (_cacheGate) + { + _cache[sha256] = (info, ++_uses); + if (_cache.Count > CacheSize) + { + var oldest = _cache.MinBy(p => p.Value.Used).Key; + _cache.Remove(oldest); + } + } + } + + private static FileStream OpenRead(string path) => + new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess); + + internal static string Day(DateTimeOffset now, TimeZoneInfo zone) => + LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + + /// + /// A write-only stream that gives up a write making no progress for a while (the page stopped reading). The zip of + /// .NET 10 writes the small data descriptor of each entry synchronously even through its asynchronous API: those + /// bytes are kept here and sent with the next asynchronous write, so the response never sees a synchronous write. + /// + private sealed class StallGuardStream(Stream inner, TimeSpan stall, TimeProvider time) : Stream + { + // A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL. + private const int MaxPending = 64 * 1024; + + // The bytes of one guarded write: the response buffer of Kestrel (64 KB). + private const int Piece = 64 * 1024; + + private readonly MemoryStream _pending = new(); + private long _position; + + 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 => _position; + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override async Task FlushAsync(CancellationToken cancellationToken) + { + await SendPendingAsync(cancellationToken).ConfigureAwait(false); + await inner.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + 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(); + + public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count)); + + public override void Write(ReadOnlySpan buffer) + { + if (_pending.Length + buffer.Length > MaxPending) + { + throw new NotSupportedException("Lo zip dei fotogrammi si scrive solo in modo asincrono."); + } + + _pending.Write(buffer); + _position += buffer.Length; + } + + public override void WriteByte(byte value) => Write([value]); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + await SendPendingAsync(cancellationToken).ConfigureAwait(false); + await GuardedAsync(buffer, cancellationToken).ConfigureAwait(false); + _position += buffer.Length; + } + + /// Sends what was written synchronously and flushes: call it once the zip is complete. + public Task CompleteAsync(CancellationToken ct) => FlushAsync(ct); + + private async Task SendPendingAsync(CancellationToken ct) + { + if (_pending.Length == 0) + { + return; + } + + var bytes = _pending.ToArray(); + _pending.SetLength(0); + await GuardedAsync(bytes, ct).ConfigureAwait(false); + } + + /// + /// Sends in pieces of bytes, each with its own time: a frame of + /// several megabytes on a slow link keeps going as long as every piece goes (a response write completes only once + /// the socket has taken nearly all of it), and stops after stall without one. + /// + private async Task GuardedAsync(ReadOnlyMemory buffer, CancellationToken ct) + { + for (var offset = 0; offset < buffer.Length; offset += Piece) + { + using var timer = new CancellationTokenSource(stall, time); + using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct, timer.Token); + await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false); + } + } + } +} diff --git a/src/Febe.Web/FebeWeb.cs b/src/Febe.Web/FebeWeb.cs index 013624c..8b6a397 100644 --- a/src/Febe.Web/FebeWeb.cs +++ b/src/Febe.Web/FebeWeb.cs @@ -4,6 +4,7 @@ using Febe.Core.Alerts; using Febe.Core.Engine; using Febe.Core.Export; using Febe.Core.Import; +using Febe.Core.Library.Conversion; using Febe.Core.Storage; using Febe.Web.Api; using Febe.Web.Connection; @@ -90,6 +91,20 @@ public static class FebeWeb : ExportRootOptions.AnyFolder); services.TryAddSingleton(sp => new SystemExportDisk(sp.GetRequiredService().Mounts)); services.TryAddSingleton(); + // The conversion of the library (tappa E3): the composition registers the worker it starts; without one (the + // demo, the tests) the endpoints get one that never runs, over the same database and gate. + services.TryAddSingleton(sp => new LibraryConversionQueue(sp.GetRequiredService(), sp.GetRequiredService())); + services.TryAddSingleton(sp => new LibraryConversionWorker(new LibraryConversionEnvironment + { + Storage = sp.GetRequiredService(), + Layout = () => sp.GetRequiredService().Layout, + Clock = sp.GetRequiredService(), + Gate = sp.GetRequiredService(), + Session = sp.GetRequiredService(), + })); + // Frames of videos (tappa E3): previews, single frames, «Scarica» of several in a zip. + services.TryAddSingleton(); + services.TryAddSingleton(); services.AddHttpContextAccessor(); if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password)) { @@ -152,6 +167,7 @@ public static class FebeWeb SettingsApi.Map(endpoints); ImportApi.Map(endpoints); ExportApi.Map(endpoints); + FramesApi.Map(endpoints); DuplicatesApi.Map(endpoints); SearchApi.Map(endpoints); RemoteViewSocket.Map(endpoints); diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index 0e764a5..18383b8 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -139,10 +139,14 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `GET /api/import/{id}/progress`, `POST /{id}/interrupt`, `/resume` | Passi 2 e 4: avanzamento, interruzione e ripresa | | `GET /api/import/{id}/review`, `PUT /{id}/folders`, `PUT /{id}/mode`, `GET /{id}/duplicates?after=&all=`, `POST /{id}/duplicates/{pairId}`, `GET /api/import/files/{fileId}/preview` | Passo 3: contatori, cartelle → account, Copia/Sposta, doppioni con anteprime | | `POST /api/import/{id}/copy`, `GET /{id}/report`, `GET /{id}/report.csv`, `POST /{id}/discard` | Copia, resoconto, CSV (UTF-8 con BOM, `;`), abbandono di un'importazione non copiata | -| `GET /api/export`, `PUT /api/export/settings` (`{ samePost: "onePerAccount"\|"oneOnly" }`) | Copie esterne (§4.10, `Api/ExportApi.cs`): radice (`docker`, `active`, `root`, `problem`, `pickFolder`), cartella generale, cartelle proprie, lavori in corso e da riprendere (`unfinishedRuns`), schemi della libreria | +| `GET /api/export`, `PUT /api/export/settings` (`{ samePost?, photoFormat?, videoFormat?, libraryPhotoFormat?, libraryVideoFormat?, convertExisting? }`, parziale) | Copie esterne (§4.10, `Api/ExportApi.cs`): radice (`docker`, `active`, `root`, `problem`, `pickFolder`), cartella generale, cartelle proprie, lavori in corso e da riprendere (`unfinishedRuns`), schemi della libreria, formati (`original`, `jpg`, `png`, `webplossless`, `mp4`) e stato della conversione della libreria (`libraryConversion`). Il salvataggio risponde `{ message, overview, queued }` | +| `GET /api/export/library-conversion`, `GET /library-conversion/preview?photo=&video=`, `POST /library-conversion/retry`, `/pause`, `/resume` | Conversione della libreria (tappa E3): `pending`, `converted`, `failed`, `asIs`, `paused`, `waiting`, `text`; la domanda «Converti anche i N già in libreria?» (`{ files, bytes, text }`); «Riprova», «Metti in pausa», «Riprendi» | | `GET /api/export/folders?path=`, `POST /api/export/pick-folder` (`{ destinationId }`), `/check-folder` (`{ path }`), `/naming-preview` | Scelta della cartella: in Docker l'elenco sotto `/esporta` (solo se attiva; `..` è 400), sul desktop la finestra del sistema; controllo con spazio libero e FAT32; «Risultato» dei nomi | -| `POST /api/export/destinations`, `PUT/DELETE /api/export/destinations/{id}`, `GET /{id}/status`, `POST /{id}/resume`, `/{id}/check` | Cartelle: tipi `postFoto`, `postVideo`, `storie`, `evidenza`, `taggati`, `profilo`; un cambio di cartella dà un id nuovo; togliere non cancella nulla; «Riprova» (sonda, poi riprende i lavori in pausa); «Controlla le copie» | -| `POST /api/export/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId, copyAgain }`, uno solo), `POST /api/export/copy-again` (`{ copyId }`) | «Copia in…»: riepilogo, avvio (`runIds`, il piano, un messaggio), «Copia di nuovo» di un file tolto o superato | +| `POST /api/export/destinations`, `PUT/DELETE /api/export/destinations/{id}`, `GET /{id}/status`, `POST /{id}/resume`, `/{id}/check` | Cartelle: tipi `postFoto`, `postVideo`, `storie`, `evidenza`, `taggati`, `profilo`; `photoFormat` e `videoFormat` (vuoti o `general`: come le impostazioni generali); un cambio di cartella dà un id nuovo; togliere non cancella nulla; «Riprova» (sonda, poi riprende i lavori in pausa); «Controlla le copie» | +| `POST /api/export/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId, copyAgain, photoFormat?, videoFormat?, frames? }`, uno solo), `POST /api/export/copy-again` (`{ copyId }`) | «Copia in…»: riepilogo (con `asIs`, `converted`, `lossy`, `videos`, `photosSkipped`, `frames`, `overCap`, `summary`), avvio (`runIds`, il piano, un messaggio), «Copia di nuovo» di un file tolto o superato nella sua forma esatta. `frames` (`{ mode: "istante"\|"ogni"\|"numero", atMs, everyMs, count, format }`) copia fotogrammi dei video invece dei file; non va insieme ai formati | +| `GET /api/media/{id}/frames/info`, `GET /api/media/{id}/frame?at=ms&format=&max=&download=1`, `GET /api/media/{id}/frames/instants?mode=&at=&every=&count=` (ms) | Fotogrammi (`Api/FramesApi.cs`, `Export/FrameService.cs`): se un video li dà; un fotogramma (anteprima con `max` fino a 480 px, JPG; scaricamento a piena risoluzione, PNG se non si sceglie, nome con l'istante vero); gli istanti di una modalità con etichette e suffissi. Uno alla volta, 30 s al più (503 dopo) | +| `POST /api/frames/plan`, `POST /api/frames/download-token` (`{ mediaIds \| entryIds \| query+mode, frames }`), `GET /api/frames/download/{token}` | «Fotogrammi…» → «Scarica»: riepilogo; un gettone in memoria (5 minuti, una volta sola); un fotogramma è un'immagine, da 2 a 500 uno zip scritto mentre parte (senza compressione, `/`). Oltre 20 serve il motore fermo e nessun altro lavoro lungo (409 altrimenti) | +| `GET /api/conversions/{id}/file[?download=1]`, `POST /api/conversions/show-in-folder` (`{ conversionId }`), `POST /api/entries/delete-preview` (`{ ids }`) | File convertiti della libreria (`conversions` di ogni file del visualizzatore, con `framesAvailable` per i video e `frameAtMs`, `frameLabel`, `notes` nelle copie); quanti file e file convertiti toglierebbe «Elimina dalla libreria» | | `GET /api/export/progress`, `GET /api/export/runs?limit=`, `POST /api/export/interrupt`, `/resume`, `/runs/{id}/resume`, `/runs/{id}/discard`, `GET /runs/{id}/report` | Scheda Esportazione della Dashboard: avanzamento, lavori, interruzione, ripresa, annullamento (i file copiati restano), resoconto (al più 200 problemi) | | `POST /api/accounts/{id}/export-enabled` (`{ value }`) | «Esporta questo account»: spento, nessuna copia dell'account, neanche da «Copia in…». La scheda (`GET /api/accounts/{id}`) ha `export` con i conteggi dei file dovuti | | `GET /icone/tutte.svg` | Tutte le icone di `wwwroot/icone` (disegnate per Febe) in un solo sprite (``) | @@ -265,6 +269,12 @@ scrive mai nella libreria vera e non usa la rete. propria di @studio.lumen.demo), `esporta/Chiavetta` (quella che dà la finestra di scelta); @il.porto.demo non si esporta; di @marta.demo circa due terzi delle foto copiati dal motore vero (un lavoro concluso con resoconto), un file tolto, uno superato, uno con errore e un lavoro interrotto da riprendere. In veste Docker la radice si chiama `/esporta`. +- Formati e fotogrammi (tappa E3): ogni video della dimostrazione è lo stesso video H.264 di 2 secondi + (`campioni/video-dimostrativo.mp4`, scritto da `H264PcmWriter`), così «Fotogramma» e «Fotogrammi…» → «Scarica» + funzionano; di @marta.demo una foto copiata in PNG dal motore vero, un fotogramma a 1,234 s (cioè 0:01,125, il + fotogramma mostrato in quel momento) già nella cartella generale, una foto con il suo PNG in libreria e una che «non si + converte». La conversione della libreria non parte mai. «Nella cartella delle copie» dei fotogrammi di un video + finisce in errore («non corrisponde»): i video condividono l'impronta della loro copertina, non quella del file. - I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i conti tornino. diff --git a/src/Febe.Web/Library/FebeLibrary.cs b/src/Febe.Web/Library/FebeLibrary.cs index 000b0f9..7898b4d 100644 --- a/src/Febe.Web/Library/FebeLibrary.cs +++ b/src/Febe.Web/Library/FebeLibrary.cs @@ -82,6 +82,41 @@ public sealed class LibraryFileResolver(FebeLibrary library) : IMediaFileResolve } } +/// +/// Where the file of a conversion of the library is on disk (tappa E3): only Converted and Superseded rows have one. +/// The demo maps its seeded rows; the real one uses the layout. +/// +public interface IConversionFileResolver +{ + /// Full path of an existing file, or null when the row has no file or it is not on disk. + string? Resolve(Account account, MediaConversion conversion); +} + +/// Converted files next to their originals, under the account folders of the library (spec §4.10). +public sealed class LibraryConversionFileResolver(FebeLibrary library) : IConversionFileResolver +{ + public string? Resolve(Account account, MediaConversion conversion) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(conversion); + if (conversion.RelativePath is null || conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded)) + { + return null; + } + + try + { + // FullPath refuses a path that leaves the account folder. + var path = library.Layout.FullPath(account, conversion.RelativePath); + return File.Exists(path) ? path : null; + } + catch (ArgumentException) + { + return null; + } + } +} + /// Something changed in the library: the open pages reload what they show. /// When. /// The account concerned, when there is only one. diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index 757ce33..b39c594 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -367,7 +367,7 @@ input[type=range].cursore:focus-visible{outline:2px solid var(--accento);outline .breve svg{flex:none;margin-top:1px} /* dialoghi */ -.velo.finestra{position:fixed;z-index:40;padding:16px} +.velo.finestra{position:fixed;z-index:55;padding:16px} .dialogo{max-height:calc(100vh - 32px);max-width:calc(100vw - 32px)} .dialogo header .btn.solo{margin-left:auto} .dialogo .contenuto{padding:10px 22px 18px;overflow:auto} @@ -1213,6 +1213,51 @@ p.aiuto.descrizione-copie{margin-top:8px} .problemi-copia li{min-height:0;padding:8px 14px} .problemi-copia .chi-cosa b{white-space:normal} +/* ---------- formati e fotogrammi (§4.10, tappa E3) ---------- */ +.formati-copie{display:flex;flex-direction:column;gap:12px} +.scelta-formato{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px} +.scelta-formato > .etichetta{width:56px;margin:0} +.scelta-formato .nota-formato{flex-basis:100%;margin-left:68px} +.scelta-formato .gruppo{flex-wrap:wrap} +.parte-formati .formati-copie{margin-top:10px} +.sezione-conversione .stato-conversione{margin-top:6px} +.sezione-conversione .stato-conversione .avviso{margin-top:10px} +.riga-formato{margin-top:4px;padding-top:12px;border-top:1px solid var(--bordo)} +.riga-formato-testa{display:flex;align-items:center;gap:8px;font-size:13.5px} +.riga-formato-testa > svg{color:var(--testo-2)} +.riga-formato .formati-copie{margin-top:12px} +.riga-formato .scelta-formato > .etichetta{width:100%} +.riga-formato .scelta-formato .nota-formato{margin-left:0} +.riepilogo-copia .con-perdita{color:var(--ambra);font-weight:600} +.vis .scheda dd.riga-copia .nota-copia{flex-basis:100%;font-size:12.5px;color:var(--testo-2)} +.vis .scheda .basso .nota-fotogramma{text-align:center;font-size:12.5px} +.tess .segno .solo-fotogrammi{padding:0 5px} +.tess .segno .solo-fotogrammi .cornice{display:block;width:11px;height:9px;border:1.6px solid currentColor;border-radius:2px;box-shadow:inset 0 0 0 1.4px rgba(0,0,0,.58),inset 0 0 0 3px currentColor} +.dialogo.fotogrammi{width:640px} +.dialogo.fotogrammi .gruppo{flex-wrap:wrap} +.modo-fotogrammi{margin-top:12px;display:flex;flex-direction:column;gap:8px} +.anteprima-fotogramma{display:flex;justify-content:center;align-items:center;min-height:120px;background:#141414;border-radius:var(--r-pannello);overflow:hidden} +.anteprima-fotogramma img{display:block;max-width:100%;max-height:320px;object-fit:contain} +input[type=range].cursore.scorri-fotogramma{width:100%} +.riga-tempo{display:flex;align-items:center;gap:10px;flex-wrap:wrap} +.riga-tempo > .etichetta{margin:0} +.riga-tempo .aiuto,.dialogo .riga-tempo .aiuto{margin:0} +.campo-tempo{width:auto} +.campo-tempo input{border:0;background:transparent;outline:none;width:9ch;font:inherit;color:inherit} +.striscia-fotogrammi{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end} +.striscia-fotogrammi:empty{display:none} +.fotogramma-piccolo{margin:0;display:flex;flex-direction:column;align-items:center;gap:3px} +.fotogramma-piccolo img{display:block;height:72px;width:auto;max-width:128px;object-fit:cover;border-radius:var(--r-tessera);background:var(--barra)} +.fotogramma-piccolo figcaption{font-size:12px;color:var(--testo-2)} +.altri-fotogrammi{font-size:12.5px;padding-bottom:20px} +.dialogo.fotogrammi .nota-perdita,.dialogo.fotogrammi .nota-audio{margin:8px 0 0} +.dialogo.fotogrammi .dati-video{margin-bottom:4px} +.riepilogo-fotogrammi{margin-top:12px} +.riepilogo-fotogrammi .avviso{margin-top:6px} +.scheda-conversione{padding:14px 16px} +.scheda-conversione .riga-conteggi{margin-top:0} +.scheda-conversione .avviso{margin:10px 0 0} + /* ---------- animazioni: solo in risposta a un gesto, e mai con le animazioni ridotte ---------- */ @keyframes febe-compare{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}} .dialogo,.menu,.breve{animation:febe-compare .14s ease-out} diff --git a/src/Febe.Web/wwwroot/js/pages/account.js b/src/Febe.Web/wwwroot/js/pages/account.js index 5c49dad..90ddfdc 100644 --- a/src/Febe.Web/wwwroot/js/pages/account.js +++ b/src/Febe.Web/wwwroot/js/pages/account.js @@ -5,6 +5,7 @@ // Copies to external folders (spec §4.10, tappa E2): in Contenuti the menu of the CSV icon, «Copia in…» in the // selection bar and the «Copie» filter; in Impostazioni the block «Copie esterne» under «Cartella», with «Esporta // questo account» (on unless switched off), the folder of the copies and «312 su 1.204 non ancora copiati». +// Tappa E3: «Fotogrammi…» in the selection bar of Contenuti, as in the Libreria. import { api, download, withCarried } from '../core/api.js'; import { caps, serverNow } from '../core/context.js'; @@ -19,6 +20,7 @@ import { Mosaic, justify, tileElement, defaultDayLabel, filesDayLabel, modeSwitc import { kindName, orderEditor, orderOrDefault } from './download-order.js'; import { openViewer } from './viewer.js'; import { copiesApi, copiesLabel, copiesMenu, copyDialog, destinationDialog, exportButton, exportMenu, separator } from './export-dialogs.js'; +import { framesDialog } from './frames.js'; const KINDS = [ { key: 'post', api: 'posts', stat: 'posts', label: 'scheda.tipi.posts' }, @@ -211,6 +213,10 @@ async function contentsTab(page, route, detail) { copySelected: hasDestination ? () => copyDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }) : null, + framesSelected: () => framesDialog({ + selection: mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }, + hasDestination, + }), deleteSelected: async () => { const { ids, files } = mosaic.selectedEntries(); const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null); diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js index 37d9730..4045da6 100644 --- a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js +++ b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js @@ -2,8 +2,10 @@ // work with its progress and «Interrompi»; the jobs to resume («Riprendi», «Annulla») and the folders in pause // («Riprova»); the last jobs, each with its resoconto. The progress is asked every second while a copy works, every five // seconds otherwise (decision D20), as the import does. A pause is an amber notice here, never the red strip. +// Tappa E3: the card «Conversione della libreria» (shown once it is on or has rows) and, in the resoconto, the files +// copied as they are per account and the «Note» (what a conversion could not keep, a file copied as it is). -import { api } from '../core/api.js'; +import { api, withCarried } from '../core/api.js'; import { h, icon, fill, later } from '../core/dom.js'; import { t, at, bytes, capitalize, number } from '../core/text.js'; import { confirmDialog, dialog, label, showError, toast } from '../core/ui.js'; @@ -23,8 +25,9 @@ export async function mountExport(page) { document.title = t('app.titoloPagina', { pagina: `${t('esportazione.dashboard.esportazione')} · ${t('attivita.titolo')}` }); const current = h('section.blocco.copia-in-corso'); const pending = h('section.blocco', { hidden: true }); + const conversion = h('section.blocco.conversione-libreria', { hidden: true }); const recent = h('section.blocco'); - fill(page.body, h('div.attivita.esportazione-dashboard', current, pending, recent)); + fill(page.body, h('div.attivita.esportazione-dashboard', current, pending, conversion, recent)); let overview = null; let runs = []; @@ -48,6 +51,7 @@ export async function mountExport(page) { api('/api/export/runs?limit=20', { signal: page.signal }), ]); drawPending(); + drawConversion(); drawRecent(); } catch (error) { if (error.name !== 'AbortError') showError(error); @@ -212,6 +216,38 @@ export async function mountExport(page) { again(); } + // ------------------------------------------------------------------------------------------- library conversion + function drawConversion() { + const c = overview && overview.libraryConversion; + conversion.hidden = !c || !(c.on || c.pending || c.converted || c.failed || c.asIs); + if (conversion.hidden) { + conversion.replaceChildren(); + return; + } + const buttons = []; + if (c.paused) buttons.push(h('button.btn.piccolo', { type: 'button', onclick: (e) => conversionCommand('resume', e.currentTarget) }, icon('play', 's'), t('esportazione.conversione.riprendi'))); + else if (c.on || c.pending) buttons.push(h('button.btn.piccolo', { type: 'button', onclick: (e) => conversionCommand('pause', e.currentTarget) }, icon('pause', 's'), t('esportazione.conversione.interrompi'))); + if (c.failed) buttons.push(h('button.btn.piccolo', { type: 'button', onclick: (e) => conversionCommand('retry', e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.conversione.riprova'))); + buttons.push(h('a.btn.nudo.piccolo', { href: withCarried('/impostazioni/esportazione') }, t('esportazione.dashboard.conversioneImpostazioni'))); + fill(conversion, + h('div.testa-blocco', h('h2', t('esportazione.dashboard.conversione'))), + h('div.pannello.scheda-conversione', + h('div.riga-conteggi', h('span', c.on ? c.text : `${c.text} · ${t('esportazione.dashboard.conversioneSpenta')}`), buttons), + c.waiting && !c.paused ? h('p.avviso.ambra', icon('hourglass', 's'), h('span', c.waiting)) : null)); + } + + async function conversionCommand(command, button) { + button.disabled = true; + try { + const result = await api(`/api/export/library-conversion/${command}`, { method: 'POST' }); + toast(result.message); + } catch (error) { + button.disabled = false; + showError(error); + } + again(); + } + // ------------------------------------------------------------------------------------------- ultimi lavori function drawRecent() { const head = h('div.testa-blocco', h('h2', t('esportazione.dashboard.ultimi'))); @@ -258,6 +294,9 @@ async function openReport(run) { if (r.completedAt) when.push(t('esportazione.dashboard.finita', { quando: at(r.completedAt) })); const states = FILE_STATES.filter((s) => report.byState[s]).map((s) => t(`esportazione.dashboard.statiFile.${s}`, { n: report.byState[s] })); if (report.bytesCopied) states.push(t('esportazione.dashboard.copiatiByte', { spazio: bytes(report.bytesCopied) })); + // Tappa E3: the files copied as they are, per kind («3 HEIC»), in a column only when some job file was. + const asIsText = (a) => Object.entries(a.asIs || {}).filter(([, n]) => n).map(([kind, n]) => `${number(n)} ${kind}`).join(', '); + const withAsIs = report.accounts.some((a) => asIsText(a)); const accounts = report.accounts.length ? h('div.pannello', h('table.tab.resoconto-account', h('thead', h('tr', @@ -265,13 +304,19 @@ async function openReport(run) { h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.copiati')), h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.gia')), h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.saltati')), - h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.falliti')))), + h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.falliti')), + withAsIs ? h('th', { scope: 'col' }, t('esportazione.dashboard.comeSono')) : null)), h('tbody', report.accounts.map((a) => h('tr', h('td', `@${a.username}`), h('td.num.dati', number(a.copied)), h('td.num.dati', number(a.alreadyCopied)), h('td.num.dati', number(a.skipped)), - h('td.num.dati', number(a.failed))))))) + h('td.num.dati', number(a.failed)), + withAsIs ? h('td.dati', asIsText(a)) : null))))) + : null; + const notes = report.notes && report.notes.length + ? h('div.pannello', h('ul.elenco-attivita.problemi-copia.note-copia', report.notes.map((p) => h('li', + h('div.chi-cosa', h('b', `@${p.username}`, p.path ? h('span.codice.dati', p.path) : null), h('span', p.text)))))) : null; const problems = report.problems.length ? h('div.pannello', h('ul.elenco-attivita.problemi-copia', report.problems.map((p) => h('li', @@ -287,7 +332,9 @@ async function openReport(run) { accounts ? h('h3', t('esportazione.dashboard.perAccount')) : null, accounts, h('h3', t('esportazione.dashboard.problemi')), - problems), + problems, + notes ? h('h3', t('esportazione.dashboard.note')) : null, + notes), footer: h('footer', h('div.destra', h('button.btn', { type: 'button', autofocus: true, onclick: () => close() }, t('comune.chiudi')))), }), }); diff --git a/src/Febe.Web/wwwroot/js/pages/export-dialogs.js b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js index eb4118f..494ec72 100644 --- a/src/Febe.Web/wwwroot/js/pages/export-dialogs.js +++ b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js @@ -2,12 +2,51 @@ // (folder: native picker on the desktop, the subfolders of /esporta in Docker; content types; «Come la libreria» or a // scheme of its own with the «Risultato» tree), «Copia in…» (the summary of what would be copied, one row per // destination, «Copia di nuovo anche i N tolti o superati» unchecked), the menu of the CSV icon and the «Copie» filter. -// «Automatica» and the formats are not shown in this tappa: there is nothing behind them yet (decisions D7, D8). +// Tappa E3: the formats (the destination's «Formati» with «Come le impostazioni generali» first; the row «Formato: come +// la destinazione · Cambia» of «Copia in…», whose summary says what is copied as it is and «con perdita»). +// «Automatica» is not shown: tappa E5 acts on it (decision D8 of E2). import { api } from '../core/api.js'; import { h, icon, fill, later } from '../core/dom.js'; import { t, bytes } from '../core/text.js'; -import { checkbox, dialog, menu, radio, showError, toast } from '../core/ui.js'; +import { checkbox, dialog, menu, radio, segmented, showError, toast } from '../core/ui.js'; +import { formatLabel } from './frames.js'; + +/** The formats of the copies by kind (wire names, decision D21), «Originale» first. */ +export const FORMATS = { photo: ['original', 'jpg', 'png', 'webplossless'], video: ['original', 'mp4'] }; + +/** + * The control of one format («Foto» or «Video»): a segmented choice with what it means under it («con perdita: qualità + * 92» for JPG, «solo rimuxaggio, mai ricodifica» for MP4). first: an option before the formats ({ value, label }: + * «Come le impostazioni generali», «Come la destinazione»). onchange(value) after a choice; the returned node has + * select(value) to set it back. + */ +export function formatChoice({ kind, value, first = null, onchange }) { + const name = t(`esportazione.formati.${kind === 'photo' ? 'foto' : 'video'}`); + const note = h('p.aiuto.nota-formato'); + const options = [...(first ? [first] : []), ...FORMATS[kind].map((f) => ({ value: f, label: formatLabel(f) }))]; + const drawNote = (v) => { + const key = v === 'jpg' ? 'conPerdita' : v === 'mp4' ? 'soloRimux' : null; + fill(note, key ? t(`esportazione.formati.${key}`) : null); + note.hidden = !key; + }; + const control = segmented({ + label: name, + value, + options, + onchange: (v) => { + drawNote(v); + if (onchange) onchange(v); + }, + }); + drawNote(value); + const box = h('div.scelta-formato', { dataset: { tipo: kind } }, h('span.etichetta', name), control, note); + box.select = (v) => { + control.select(v); + drawNote(v); + }; + return box; +} /** Content types of a destination, as the API names them, in the order of the dialog. */ export const TYPES = [ @@ -123,6 +162,8 @@ export async function destinationDialog({ scope, accountId = null, username = '' profile: (destination && destination.profileNamingScheme) || info.library.profile, errors: [], saving: false, + photoFormat: (destination && destination.photoFormat) || 'general', + videoFormat: (destination && destination.videoFormat) || 'general', }; return dialog({ @@ -345,6 +386,9 @@ export async function destinationDialog({ scope, accountId = null, username = '' // «Automatica» is kept as stored: tappa E5 acts on it (decision D8). automatic: destination ? destination.automatic : false, onlyNew: true, + // Tappa E3: «general» is «Come le impostazioni generali». + photoFormat: state.photoFormat, + videoFormat: state.videoFormat, }; try { const saved = await api(destination ? `/api/export/destinations/${destination.id}` : '/api/export/destinations', { method: destination ? 'PUT' : 'POST', body }); @@ -358,6 +402,12 @@ export async function destinationDialog({ scope, accountId = null, username = '' } } + // ------------------------------------------------------------------------------- formats (tappa E3) + const asGeneral = { value: 'general', label: t('esportazione.formati.generali') }; + const formatsPart = h('div.formati-copie', + formatChoice({ kind: 'photo', value: state.photoFormat, first: asGeneral, onchange: (v) => { state.photoFormat = v; } }), + formatChoice({ kind: 'video', value: state.videoFormat, first: asGeneral, onchange: (v) => { state.videoFormat = v; } })); + const body = h('div.contenuto', h('section.parte-dialogo', h('h3', t('esportazione.dialogo.cartella')), @@ -367,6 +417,10 @@ export async function destinationDialog({ scope, accountId = null, username = '' h('h3', t('esportazione.dialogo.tipi')), h('p.aiuto', t('esportazione.dialogo.tipiAiuto')), types, typesNote), + h('section.parte-dialogo.parte-formati', + h('h3', t('esportazione.dialogo.formati')), + h('p.aiuto', t('esportazione.dialogo.formatiAiuto')), + formatsPart), h('section.parte-dialogo', h('h3', t('esportazione.dialogo.nomi')), general ? h('p.aiuto', t('esportazione.dialogo.notaAccount')) : null, @@ -410,6 +464,8 @@ function samePath(a, b) { */ export function copyDialog(selection, { title } = {}) { let copyAgain = false; + // Tappa E3: the formats of this request only; null is «Come la destinazione». + const formats = { photo: null, video: null }; return dialog({ title: title || t('esportazione.copia.titolo'), className: 'copia-in', @@ -425,18 +481,55 @@ export function copyDialog(selection, { title } = {}) { let againCount = 0; let refocusAgain = false; + // «Formato: come la destinazione · Cambia»: the two controls open under the row, and a change asks the plan again. + const formatText = h('span.testo-formato'); + const asDestination = { value: 'destination', label: t('esportazione.formati.comeDestinazione') }; + const pick = (kind) => (v) => { + formats[kind] = v === 'destination' ? null : v; + drawFormat(); + load(); + }; + const formatControls = h('div.formati-copie', { hidden: true }, + formatChoice({ kind: 'photo', value: 'destination', first: asDestination, onchange: pick('photo') }), + formatChoice({ kind: 'video', value: 'destination', first: asDestination, onchange: pick('video') })); + const change = h('button.btn.nudo.piccolo', { + type: 'button', + 'aria-expanded': 'false', + onclick: () => { + formatControls.hidden = !formatControls.hidden; + change.setAttribute('aria-expanded', String(!formatControls.hidden)); + }, + }, t('esportazione.copia.cambia')); + const formatRow = h('div.riga-formato', h('div.riga-formato-testa', icon('sliders-horizontal', 's'), formatText, change), formatControls); + function drawFormat() { + const same = t('esportazione.formati.comeDestinazione').toLowerCase(); + fill(formatText, formats.photo || formats.video + ? t('esportazione.copia.formatoScelto', { foto: formats.photo ? formatLabel(formats.photo) : same, video: formats.video ? formatLabel(formats.video) : same }) + : t('esportazione.copia.formatoCome')); + } + drawFormat(); + const planBox = h('div.piano-copia', { 'aria-live': 'polite' }, h('p.aiuto', t('esportazione.copia.conto'))); + content.replaceChildren(planBox, formatRow); + + function request() { + const b = { ...selection, copyAgain }; + if (formats.photo) b.photoFormat = formats.photo; + if (formats.video) b.videoFormat = formats.video; + return b; + } + async function load() { const mine = ++token; start.disabled = true; try { - const result = await api('/api/export/plan', { method: 'POST', body: { ...selection, copyAgain } }); + const result = await api('/api/export/plan', { method: 'POST', body: request() }); if (mine !== token) return; plan = result; if (!copyAgain) againCount = result.removedOrSuperseded || 0; draw(); } catch (error) { if (mine !== token) return; - fill(content, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message))); + fill(planBox, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message))); } } @@ -447,7 +540,11 @@ export function copyDialog(selection, { title } = {}) { if (p.removedOrSuperseded) parts.push(t(copyAgain ? 'esportazione.copia.toltiDiNuovo' : 'esportazione.copia.tolti', { n: p.removedOrSuperseded })); if (p.notExported) parts.push(t('esportazione.copia.nonEsportati', { n: p.notExported })); if (p.missing) parts.push(t('esportazione.copia.mancanti', { n: p.missing })); + for (const a of p.asIs || []) { + if (a.files) parts.push(t('esportazione.copia.comeSono', { n: a.files, tipo: a.label })); + } if (p.files) parts.push(t('esportazione.copia.circa', { spazio: bytes(p.bytes) })); + if (p.lossy) parts.push(h('span.con-perdita', t('esportazione.copia.conPerdita'))); const summary = h('p.riepilogo-copia', parts.flatMap((x, i) => (i ? [' · ', x] : [x]))); const rows = p.destinations.filter((d) => d.files > 0 || d.problem).map((d) => h('li', icon('hard-drive', 's'), @@ -479,7 +576,7 @@ export function copyDialog(selection, { title } = {}) { const again = choice ? h('div.di-nuovo', choice, h('p.aiuto', t('esportazione.copia.diNuovoAiuto'))) : null; - fill(content, summary, rows.length ? h('ul.destinazioni-copia.pannello', rows) : null, empty, again); + fill(planBox, summary, rows.length ? h('ul.destinazioni-copia.pannello', rows) : null, empty, again); if (refocusAgain && choice) choice.input.focus(); refocusAgain = false; fill(start, icon('copy'), t('esportazione.copia.pulsante', { n: p.files })); @@ -491,7 +588,7 @@ export function copyDialog(selection, { title } = {}) { busy = true; start.disabled = true; try { - const job = await api('/api/export/start', { method: 'POST', body: { ...selection, copyAgain } }); + const job = await api('/api/export/start', { method: 'POST', body: request() }); toast(job.message, '', job.runIds.length ? { label: t('esportazione.copia.vediAvanzamento'), href: '/dashboard/esportazione' } : null); close(job); } catch (error) { diff --git a/src/Febe.Web/wwwroot/js/pages/frames.js b/src/Febe.Web/wwwroot/js/pages/frames.js new file mode 100644 index 0000000..1c93f2b --- /dev/null +++ b/src/Febe.Web/wwwroot/js/pages/frames.js @@ -0,0 +1,454 @@ +// «Fotogrammi…» (spec §4.10, §10.3, tappa E3; composed from the dialogs of mockup 13 and mockup 09): frames of a video +// from the viewer, opened at the player's time, or of the videos of a selection (Libreria and account tab; the photos +// are skipped and the dialog says so). Three ways to choose them: «Questo istante» (scrubber and time field with a +// preview), «Uno ogni k secondi», «N in tutto» (with a strip of the first previews); the format (JPG, PNG, WEBP senza +// perdita; PNG by default, JPG says «con perdita»); and where they go: «Scarica» (one image, or a zip) or «Nella +// cartella delle copie» (an export job to the folder of each account, only when one exists). «Il fotogramma non ha +// l'audio» is always said. The dialog never writes a file itself: the server does, through its usual addresses. + +import { api, withCarried } from '../core/api.js'; +import { h, icon, fill, later, uid } from '../core/dom.js'; +import { t, number, bytes } from '../core/text.js'; +import { dialog, radio, segmented, showError, toast } from '../core/ui.js'; + +/** Frame formats as the API names them (decision D21), with PNG first: the default (§16 domanda 35). */ +export const FRAME_FORMATS = ['png', 'jpg', 'webplossless']; + +/** How many previews the strip shows before «e altri N». */ +const STRIP = 6; + +/** The label of a format («JPG», «WEBP senza perdita», «Originale»). */ +export function formatLabel(format) { + return t(`esportazione.formati.${format || 'original'}`); +} + +/** «0:01», «0:01,25», «1:02:03» (decision D13): milliseconds only when the instant is not a whole second. */ +export function instantLabel(ms) { + const total = Math.max(0, Math.round(Number(ms) || 0)); + const whole = Math.floor(total / 1000); + const rest = total % 1000; + const hours = Math.floor(whole / 3600); + const minutes = Math.floor((whole % 3600) / 60); + const seconds = String(whole % 60).padStart(2, '0'); + const base = hours > 0 ? `${hours}:${String(minutes).padStart(2, '0')}:${seconds}` : `${minutes}:${seconds}`; + return rest ? `${base},${String(rest).padStart(3, '0').replace(/0+$/, '')}` : base; +} + +/** «0:12», «0:12,5», «12», «1:02:03,25» as milliseconds; null when it is not a time. */ +export function parseInstant(text) { + const value = String(text || '').trim().replace(',', '.'); + if (!/^(\d+:){0,2}\d+(\.\d{1,3})?$/.test(value)) return null; + const parts = value.split(':'); + let seconds = 0; + for (const part of parts) seconds = seconds * 60 + Number(part); + return Number.isFinite(seconds) ? Math.round(seconds * 1000) : null; +} + +/** «2», «0,5», «1.5» seconds as milliseconds; null when it is not a number. */ +function parseSeconds(text) { + const value = String(text || '').trim().replace(',', '.'); + if (!/^\d+(\.\d{1,3})?$/.test(value) && !/^\.\d{1,3}$/.test(value)) return null; + return Math.round(Number(value) * 1000); +} + +/** + * Opens «Fotogrammi…». From the viewer: { mediaId, atMs, hasDestination } (one video, at the player's time). From a + * selection: { selection: { mediaIds } | { entryIds } | { query, mode }, hasDestination }. hasDestination: a folder of + * the copies exists for the files, so «Nella cartella delle copie» can be chosen. Resolves when the dialog closes. + */ +export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDestination = false }) { + const single = mediaId != null; + const chosen = single ? { mediaIds: [mediaId] } : selection; + const state = { + mode: 'istante', + atMs: Math.max(0, Math.round(atMs || 0)), + every: '2', + count: '6', + format: 'png', + output: 'scarica', + info: null, + }; + + return dialog({ + title: t(single ? 'esportazione.fotogrammi.titolo' : 'esportazione.fotogrammi.titoloSelezione'), + className: 'fotogrammi', + build: (close) => { + const body = h('div.contenuto', h('p.aiuto', t('esportazione.fotogrammi.apro'))); + const start = h('button.btn.primo', { type: 'button', disabled: true, onclick: () => go() }, icon('download'), t('esportazione.fotogrammi.pulsanteScarica', { n: 0 })); + const footer = h('footer', h('div.destra', h('button.btn.nudo', { type: 'button', onclick: () => close(undefined) }, t('comune.annulla')), start)); + let busy = false; + let plan = null; + let planToken = 0; + let stripToken = 0; + let closed = false; + + // ------------------------------------------------------------------------------- which frames + const modeBox = h('div.modo-fotogrammi'); + const modes = segmented({ + label: t('esportazione.fotogrammi.quali'), + value: state.mode, + options: [ + { value: 'istante', label: t('esportazione.fotogrammi.istante') }, + { value: 'ogni', label: t('esportazione.fotogrammi.ogni') }, + { value: 'numero', label: t('esportazione.fotogrammi.numero') }, + ], + onchange: (v) => { + state.mode = v; + drawMode(); + changed(); + }, + }); + + const timeId = uid('istante'); + const timeField = h('input.dati', { type: 'text', id: timeId, value: instantLabel(state.atMs), inputmode: 'decimal', spellcheck: 'false', autocomplete: 'off', size: '9' }); + const timeBox = h('label.campo.campo-tempo', timeField); + const timeError = h('p.errore-testo', { hidden: true }, t('esportazione.fotogrammi.tempoErrato')); + const scrubber = h('input.cursore.scorri-fotogramma', { type: 'range', min: '0', max: '0', step: '1', value: String(state.atMs), 'aria-label': t('esportazione.fotogrammi.tempo') }); + const preview = h('div.anteprima-fotogramma', { 'aria-live': 'polite' }); + const shownLabel = h('p.aiuto.istante-mostrato', { 'aria-live': 'polite' }); + + const everyId = uid('ogni'); + const everyField = h('input.dati', { type: 'text', id: everyId, value: state.every, inputmode: 'decimal', spellcheck: 'false', autocomplete: 'off', size: '5' }); + const everyBox = h('label.campo.campo-tempo', everyField); + const everyError = h('p.errore-testo', { hidden: true }, t('esportazione.fotogrammi.ogniErrato')); + const countId = uid('numero'); + const countField = h('input.dati', { type: 'number', id: countId, value: state.count, min: '1', max: '1000', step: '1' }); + const countBox = h('label.campo.campo-tempo', countField); + const countError = h('p.errore-testo', { hidden: true }, t('esportazione.fotogrammi.numeroErrato')); + const strip = h('div.striscia-fotogrammi', { 'aria-live': 'polite' }); + + const typedTime = later(() => changed(), 250); + timeField.addEventListener('input', () => { + const ms = parseInstant(timeField.value); + timeError.hidden = ms != null; + timeBox.classList.toggle('errore', ms == null); + if (ms == null) { + drawStart(); + return; + } + state.atMs = clampToVideo(ms); + scrubber.value = String(state.atMs); + typedTime(); + }); + const scrubbed = later(() => changed(), 120); + scrubber.addEventListener('input', () => { + state.atMs = Number(scrubber.value); + timeField.value = instantLabel(state.atMs); + timeError.hidden = true; + timeBox.classList.remove('errore'); + scrubbed(); + }); + const typed = later(() => changed(), 300); + everyField.addEventListener('input', () => { + state.every = everyField.value; + typed(); + drawErrors(); + }); + countField.addEventListener('input', () => { + state.count = countField.value; + typed(); + drawErrors(); + }); + + function clampToVideo(ms) { + return state.info && state.info.durationMs ? Math.min(ms, state.info.durationMs) : ms; + } + + function everyMs() { + const ms = parseSeconds(state.every); + return ms != null && ms >= 100 ? ms : null; + } + + function countValue() { + const n = Number(state.count); + return Number.isInteger(n) && n >= 1 && n <= 1000 ? n : null; + } + + function drawErrors() { + everyError.hidden = state.mode !== 'ogni' || everyMs() != null; + everyBox.classList.toggle('errore', !everyError.hidden); + countError.hidden = state.mode !== 'numero' || countValue() != null; + countBox.classList.toggle('errore', !countError.hidden); + drawStart(); + } + + /** The request of the frames chosen, or null while a field is not valid. */ + function request() { + const base = { mode: state.mode, format: state.format }; + if (state.mode === 'istante') return parseInstant(timeField.value) == null ? null : { ...base, atMs: state.atMs }; + if (state.mode === 'ogni') return everyMs() == null ? null : { ...base, everyMs: everyMs() }; + return countValue() == null ? null : { ...base, count: countValue() }; + } + + function drawMode() { + if (state.mode === 'istante') { + fill(modeBox, + single ? preview : null, + single ? scrubber : null, + h('div.riga-tempo', + h('label.etichetta', { for: timeId }, t('esportazione.fotogrammi.tempo')), timeBox, + single ? shownLabel : h('p.aiuto', t('esportazione.fotogrammi.istanteSelezione'))), + timeError); + } else if (state.mode === 'ogni') { + fill(modeBox, + h('div.riga-tempo', + h('label.etichetta', { for: everyId }, t('esportazione.fotogrammi.ogniCampo')), + everyBox, h('span.muto', t('esportazione.fotogrammi.secondi'))), + everyError, + h('p.aiuto', t('esportazione.fotogrammi.ogniAiuto')), + single ? strip : null); + } else { + fill(modeBox, + h('div.riga-tempo', + h('label.etichetta', { for: countId }, t('esportazione.fotogrammi.numeroCampo')), + countBox), + countError, + h('p.aiuto', t('esportazione.fotogrammi.numeroAiuto')), + single ? strip : null); + } + drawErrors(); + } + + // ------------------------------------------------------------------------------- previews (one video) + function previewSrc(ms, max) { + return withCarried(`/api/media/${mediaId}/frame?at=${Math.max(0, Math.round(ms))}&max=${max}`); + } + + async function drawPreviews() { + if (!single) return; + const wanted = request(); + const mine = ++stripToken; + if (!wanted) return; + const q = new URLSearchParams({ mode: wanted.mode }); + if (wanted.atMs != null) q.set('at', String(wanted.atMs)); + if (wanted.everyMs != null) q.set('every', String(wanted.everyMs)); + if (wanted.count != null) q.set('count', String(wanted.count)); + if (state.mode === 'istante') { + // The picture follows the scrubber at once; the instant really shown comes with the list. + const img = preview.querySelector('img') || h('img', { alt: t('esportazione.fotogrammi.anteprima') }); + img.src = previewSrc(state.atMs, 480); + if (!img.isConnected) fill(preview, img); + } + let list; + try { + list = await api(`/api/media/${mediaId}/frames/instants?${q}`); + } catch (error) { + if (mine !== stripToken || closed) return; + fill(strip, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', error.message))); + return; + } + if (mine !== stripToken || closed) return; + if (state.mode === 'istante') { + const first = list.instants[0]; + fill(shownLabel, first ? t('esportazione.fotogrammi.mostrato', { istante: first.label }) : ''); + return; + } + if (list.problem) { + fill(strip, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', list.problem))); + return; + } + const shown = list.instants.slice(0, STRIP); + const others = Math.max(0, list.total - shown.length); + fill(strip, + shown.map((x) => h('figure.fotogramma-piccolo', + h('img', { src: previewSrc(x.actualMs, 160), alt: '', loading: 'lazy' }), + h('figcaption.dati', x.label))), + others ? h('span.altri-fotogrammi.muto', t('esportazione.fotogrammi.altri', { n: others })) : null); + } + + // ------------------------------------------------------------------------------- format and output + const lossyNote = h('p.aiuto.nota-perdita', { hidden: state.format !== 'jpg' }, icon('info', 'xs'), ' ', t('esportazione.formati.conPerdita')); + const formats = segmented({ + label: t('esportazione.fotogrammi.formato'), + value: state.format, + options: FRAME_FORMATS.map((f) => ({ value: f, label: formatLabel(f) })), + onchange: (v) => { + state.format = v; + lossyNote.hidden = v !== 'jpg'; + loadPlan(); + }, + }); + const outputName = uid('uscita'); + const pickOutput = (v) => { + state.output = v; + drawStart(); + loadPlan(); + }; + const outputs = h('div.scelte', { role: 'radiogroup', 'aria-label': t('esportazione.fotogrammi.uscita') }, + radio({ name: outputName, value: 'scarica', checked: true, onchange: pickOutput, labelNode: h('span', h('b', t('esportazione.fotogrammi.scarica')), h('small', t('esportazione.fotogrammi.scaricaAiuto'))) }), + (() => { + const r = radio({ + name: outputName, value: 'cartella', checked: false, onchange: pickOutput, + labelNode: h('span', h('b', t('esportazione.fotogrammi.cartella')), h('small', t(hasDestination ? 'esportazione.fotogrammi.cartellaAiuto' : 'esportazione.fotogrammi.nessunaCartella'))), + }); + if (!hasDestination) { + r.input.disabled = true; + r.classList.add('spenta'); + } + return r; + })()); + const summary = h('div.riepilogo-fotogrammi', { 'aria-live': 'polite' }); + + // ------------------------------------------------------------------------------- plan + const loadPlan = later(async () => { + const mine = ++planToken; + plan = null; + drawStart(); + const frames = request(); + if (!frames) { + summary.replaceChildren(); + return; + } + fill(summary, h('p.aiuto', t('esportazione.fotogrammi.conto'))); + try { + const result = state.output === 'cartella' + ? await api('/api/export/plan', { method: 'POST', body: { ...chosen, frames } }) + : await api('/api/frames/plan', { method: 'POST', body: { ...chosen, frames } }); + if (mine !== planToken || closed) return; + plan = { kind: state.output, ...result }; + drawSummary(); + } catch (error) { + if (mine !== planToken || closed) return; + fill(summary, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message))); + } + drawStart(); + }, 200); + + function drawSummary() { + const p = plan; + if (p.kind === 'cartella') { + const parts = [h('b', p.summary || t('esportazione.fotogrammi.quanti', { n: p.frames }))]; + if (p.notExported) parts.push(t('esportazione.copia.nonEsportati', { n: p.notExported })); + if (p.missing) parts.push(t('esportazione.copia.mancanti', { n: p.missing })); + const rows = (p.destinations || []).filter((d) => d.files > 0 || d.problem).map((d) => h('li', + icon('hard-drive', 's'), + h('div.chi-cosa', + h('b', t('esportazione.copia.verso', { nome: d.label }), ' ', h('span.dati.muto', `(${d.display})`)), + h('span', [ + d.scope === 'account' && d.username ? t('esportazione.copia.versoAccount', { nome: d.username }) : t('esportazione.copia.versoGenerale'), + t('esportazione.fotogrammi.quanti', { n: d.files }), + d.freeBytes != null ? t('esportazione.copia.liberi', { spazio: bytes(d.freeBytes) }) : null, + ].filter(Boolean).join(' · ')), + d.problem || d.paused ? h('div.avviso.ambra', icon('pause', 's'), h('span', t('esportazione.copia.inAttesa', { problema: d.problem || t('esportazione.inPausa') }))) : null))); + fill(summary, + h('p.riepilogo-copia', parts.flatMap((x, i) => (i ? [' · ', x] : [x]))), + rows.length ? h('ul.destinazioni-copia.pannello', rows) : null, + p.overCap ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('esportazione.fotogrammi.oltre'))) : null, + !p.frames && !p.overCap ? h('p.aiuto', t(p.hasDestination === false ? 'esportazione.copia.nessunaCartella' : 'esportazione.fotogrammi.nienteCartella')) : null); + } else { + fill(summary, + h('p.riepilogo-copia', h('b', p.summary)), + p.problem ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', p.problem)) : null, + !p.problem && p.needsQuiet ? h('p.aiuto', t('esportazione.fotogrammi.zipLungo')) : null); + } + } + + function count() { + if (!plan) return 0; + return plan.frames || 0; + } + + function drawStart() { + const n = count(); + const download = state.output === 'scarica'; + fill(start, icon(download ? 'download' : 'copy'), t(download ? 'esportazione.fotogrammi.pulsanteScarica' : 'esportazione.fotogrammi.pulsanteCopia', { n })); + const blocked = !plan || plan.kind !== state.output || !n || (download && plan.problem) || (!download && plan.overCap); + start.disabled = busy || Boolean(blocked) || !request(); + } + + function changed() { + drawPreviews(); + loadPlan(); + } + + // ------------------------------------------------------------------------------- go + async function go() { + const frames = request(); + if (!frames || busy || !plan) return; + busy = true; + drawStart(); + try { + if (state.output === 'cartella') { + const job = await api('/api/export/start', { method: 'POST', body: { ...chosen, frames } }); + toast(job.message, '', job.runIds.length ? { label: t('esportazione.copia.vediAvanzamento'), href: '/dashboard/esportazione' } : null); + close(job); + } else { + const ready = await api('/api/frames/download-token', { method: 'POST', body: { ...chosen, frames } }); + const a = h('a', { href: withCarried(ready.url), download: '' }); + a.hidden = true; + document.body.append(a); + a.click(); + a.remove(); + toast(t('esportazione.fotogrammi.scaricati', { n: ready.frames })); + close(ready); + } + } catch (error) { + busy = false; + drawStart(); + showError(error); + } + } + + // ------------------------------------------------------------------------------- layout + function drawAll() { + fill(body, + h('section.parte-dialogo', + h('h3', t('esportazione.fotogrammi.quali')), + modes, modeBox), + h('section.parte-dialogo', + h('h3', t('esportazione.fotogrammi.formato')), + formats, lossyNote, + h('p.aiuto.nota-audio', icon('volume-x', 'xs'), ' ', t('esportazione.fotogrammi.audio'))), + h('section.parte-dialogo', + h('h3', t('esportazione.fotogrammi.uscita')), + outputs, summary)); + drawMode(); + changed(); + } + + async function begin() { + if (!single) { + drawAll(); + return; + } + try { + state.info = await api(`/api/media/${mediaId}/frames/info`); + } catch (error) { + if (closed) return; + fill(body, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message))); + return; + } + if (closed) return; + if (!state.info.available) { + fill(body, h('div.avviso.ambra', icon('info', 's'), h('span', state.info.unavailable || t('esportazione.fotogrammi.nonDisponibile')))); + return; + } + scrubber.max = String(Math.max(0, state.info.durationMs)); + state.atMs = clampToVideo(state.atMs); + scrubber.value = String(state.atMs); + timeField.value = instantLabel(state.atMs); + drawAll(); + body.prepend(h('p.aiuto.dati-video', t('esportazione.fotogrammi.video', { + durata: instantLabel(state.info.durationMs), + l: number(state.info.width), + a: number(state.info.height), + }))); + } + + begin(); + return { + body, + footer, + onClose: () => { + closed = true; + planToken++; + stripToken++; + loadPlan.cancel(); + typed.cancel(); + typedTime.cancel(); + scrubbed.cancel(); + }, + }; + }, + }); +} diff --git a/src/Febe.Web/wwwroot/js/pages/library.js b/src/Febe.Web/wwwroot/js/pages/library.js index d2bda5b..faaae67 100644 --- a/src/Febe.Web/wwwroot/js/pages/library.js +++ b/src/Febe.Web/wwwroot/js/pages/library.js @@ -5,6 +5,8 @@ // «Tutte le foto» the selection is of files; the CSV list and «Elimina» work on the entries they belong to. // Copies to external folders (spec §4.10, tappa E2): the CSV icon is a menu («Esporta l'elenco (CSV)», «Copia i file // in…»), «Copia in…» in the selection bar and the «Copie» filter, these two only once a folder of the copies exists. +// Tappa E3: «Fotogrammi…» in the selection bar (always: the photos are skipped and the dialog says so), and the +// confirmation of «Elimina» counts the converted files of the library that go with the entries. import { api, download, withCarried } from '../core/api.js'; import { caps } from '../core/context.js'; @@ -17,6 +19,7 @@ import { Mosaic, modeSwitch, storedMode } from './mosaic.js'; import { welcome } from './welcome.js'; import { openViewer } from './viewer.js'; import { copiesApi, copiesLabel, copiesMenu, copyDialog, exportButton as exportMenuButton, exportMenu } from './export-dialogs.js'; +import { framesDialog } from './frames.js'; const KINDS = [ { key: 'tutto', api: 'all', label: 'libreria.tipi.all' }, @@ -303,7 +306,7 @@ export default { page.saveBar(null); return; } - page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected, copySelected: hasDestinations ? copySelected : null })); + page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected, copySelected: hasDestinations ? copySelected : null, framesSelected })); } function setSelecting(on) { @@ -326,6 +329,10 @@ export default { return copyDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }); } + function framesSelected() { + return framesDialog({ selection: mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }, hasDestination: hasDestinations }); + } + async function exportSelected() { try { await download('/api/entries/export', { ids: mosaic.selectedEntries().ids }, 'febe-elementi.csv'); @@ -447,10 +454,11 @@ export default { /** * The bar of the selection (Libreria and account view): how many are chosen, «Esporta l'elenco», «Copia in…» (only - * with copySelected, when a folder of the copies exists) and «Elimina». With «Tutte le foto» it counts the files and - * says how many entries they belong to: the CSV list and «Elimina» work on those, «Copia in…» on the chosen files. + * with copySelected, when a folder of the copies exists), «Fotogrammi…» (with framesSelected) and «Elimina». With + * «Tutte le foto» it counts the files and says how many entries they belong to: the CSV list and «Elimina» work on + * those, «Copia in…» and «Fotogrammi…» on the chosen files. */ -export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected, copySelected = null }) { +export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected, copySelected = null, framesSelected = null }) { const n = selected.size; const entries = mosaic.selectedEntries().ids.length; let note = t('selezione.nessuno'); @@ -462,6 +470,7 @@ export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteS h('button.btn.nudo', { type: 'button', onclick: cancel }, t('selezione.annulla')), h('button.btn', { type: 'button', disabled: !n, onclick: exportSelected }, icon('file-down'), t('selezione.esporta')), copySelected ? h('button.btn', { type: 'button', disabled: !n, onclick: copySelected }, icon('copy'), t('esportazione.selezione.copia')) : null, + framesSelected ? h('button.btn.fotogrammi-selezione', { type: 'button', disabled: !n, onclick: framesSelected }, icon('image'), t('esportazione.selezione.fotogrammi')) : null, h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: deleteSelected }, icon('trash-2'), t('selezione.elimina', { n: entries })))); } @@ -469,17 +478,31 @@ export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteS * «Elimina dalla libreria» with the confirmation of spec §4.6: by default the choice is remembered (state «eliminato», * never downloaded again); «Eliminalo e lascia che torni» forgets the entry. Returns the deleted keys, or null. * files: with «Tutte le foto», { files: chosen files, total: files of their entries }: the confirmation says that the - * whole entries go («3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»). + * whole entries go («3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»). Tappa E3: the + * converted files of the library made from those entries go too, and the confirmation counts them («… 9 file e 2 file + * convertiti»), asked of the server before it opens. */ export async function confirmDelete(ids, files = null) { const n = ids.length; - const whole = files - ? h('p', `${t('elimina.fileDi', { n: files.files, elementi: t('comune.elementi', { n }) })}: ${t('elimina.interi', { n, file: t('comune.file', { n: files.total }) })}`) - : null; + let converted = 0; + if (n && n <= 5000) { + try { + converted = (await api('/api/entries/delete-preview', { method: 'POST', body: { ids, mode: null } })).convertedFiles || 0; + } catch { + // the count is a courtesy: the deletion itself says what it removed + } + } + const convertedText = converted ? t('elimina.convertiti', { n: converted }) : ''; + let whole = null; + if (files) { + const filesText = t('comune.file', { n: files.total }); + const tail = converted ? t('elimina.interiConvertiti', { n, file: filesText, convertiti: convertedText }) : t('elimina.interi', { n, file: filesText }); + whole = h('p', `${t('elimina.fileDi', { n: files.files, elementi: t('comune.elementi', { n }) })}: ${tail}`); + } const mode = await confirmDialog({ title: t('elimina.titolo', { n }), text: t('elimina.testo', { n }), - extra: h('div', whole, h('p.aiuto', t('elimina.tornaSpiega'))), + extra: h('div', whole, !files && converted ? h('p.conta-convertiti', t('elimina.ancheConvertiti', { n: converted })) : null, h('p.aiuto', t('elimina.tornaSpiega'))), buttons: [ { label: t('comune.annulla'), value: undefined, kind: 'nudo' }, { label: t('elimina.torna', { n }), value: 'allowReturn' }, diff --git a/src/Febe.Web/wwwroot/js/pages/mosaic.js b/src/Febe.Web/wwwroot/js/pages/mosaic.js index be8677e..f8bf405 100644 --- a/src/Febe.Web/wwwroot/js/pages/mosaic.js +++ b/src/Febe.Web/wwwroot/js/pages/mosaic.js @@ -143,6 +143,10 @@ export function tileElement(tile, width, height, { selected = false, today = '', const parte = t('esportazione.segno.parte', { n: tile.copiesDone || 0, totale: tile.copiesDue || 0 }); marks.push(h('span.copia.parte', { title: parte }, icon('copy'), `${tile.copiesDone || 0}/${tile.copiesDue || 0}`)); description.push(parte); + } else if (tile.copies === 'frameOnly') { + // Tappa E3 (decision D4): only frames of it were copied, never the file. A frame drawn in CSS, no icon file. + marks.push(h('span.solo-fotogrammi', { title: t('esportazione.segno.fotogrammi') }, h('i.cornice', { 'aria-hidden': 'true' }))); + description.push(t('esportazione.segno.fotogrammi')); } const el = h(`button.tess${selected ? '.scelta' : ''}`, { type: 'button', diff --git a/src/Febe.Web/wwwroot/js/pages/settings-export.js b/src/Febe.Web/wwwroot/js/pages/settings-export.js index 876bf92..23202ec 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings-export.js +++ b/src/Febe.Web/wwwroot/js/pages/settings-export.js @@ -1,14 +1,17 @@ // Impostazioni → Esportazione (spec §4.10, §10.3, tappa E2; composed from mockups 08 and 07): the general folder of // the copies with its state («In pausa» with «Riprova», or the counts with «Controlla le copie»), «Lo stesso post in // due account», the folders of the accounts, and in Docker the note on /esporta. Everything acts at once: there is no -// save bar. The formats, the conversion of the library and «Automatica» come with later tappe (decisions D7, D8). +// save bar. Tappa E3: «Formati delle copie» (Foto and Video, JPG says «con perdita: qualità 92», MP4 «solo +// rimuxaggio, mai ricodifica») and «Conversione della libreria» (the same two controls; turning one on asks «Convertire +// anche i N file già in libreria?» with «Solo i nuovi» first; the status line with «Interrompi», «Riprendi» and +// «Riprova i non riusciti»). «Automatica» comes with tappa E5 (decision D8 of E2). import { api, withCarried } from '../core/api.js'; import { h, icon, fill, later } from '../core/dom.js'; -import { t } from '../core/text.js'; +import { t, bytes } from '../core/text.js'; import { confirmDialog, label, segmented, showError, toast } from '../core/ui.js'; import { heading } from './settings.js'; -import { countsText, describe, destinationDialog } from './export-dialogs.js'; +import { countsText, describe, destinationDialog, formatChoice } from './export-dialogs.js'; export default async function exportSettings(page, box) { let overview = await api('/api/export', { signal: page.signal }); @@ -127,6 +130,110 @@ export default async function exportSettings(page, box) { }, }); + // ------------------------------------------------------------------------------------------- formats (tappa E3) + /** PUT /api/export/settings with some fields; the overview that comes back is the page's. */ + async function saveSettings(fields) { + const result = await api('/api/export/settings', { method: 'PUT', body: fields }); + if (result.overview) overview = result.overview; + toast(result.message); + return result; + } + + function copyFormat(kind) { + const key = kind === 'photo' ? 'photoFormat' : 'videoFormat'; + const control = formatChoice({ + kind, + value: overview[key] || 'original', + onchange: async (v) => { + const before = overview[key]; + try { + await saveSettings({ [key]: v }); + } catch (error) { + control.select(before || 'original'); + showError(error); + } + }, + }); + return control; + } + const formatsBox = h('div.formati-copie', copyFormat('photo'), copyFormat('video')); + + // ------------------------------------------------------------------------------------------- library conversion + const conversionStatus = h('div.stato-conversione', { 'aria-live': 'polite' }); + + function libraryFormat(kind) { + const key = kind === 'photo' ? 'libraryPhotoFormat' : 'libraryVideoFormat'; + const control = formatChoice({ + kind, + value: overview[key] || 'original', + onchange: async (v) => { + const before = overview[key] || 'original'; + try { + let convertExisting = false; + if (v !== 'original') { + // «Convertire anche i N file già in libreria?» (§16 domanda 29): «Solo i nuovi» first; closed, nothing changes. + const q = new URLSearchParams({ [kind]: v }); + const preview = await api(`/api/export/library-conversion/preview?${q}`); + if (preview.files > 0) { + const answer = await confirmDialog({ + title: t('esportazione.conversione.domanda', { n: preview.files }), + text: t('esportazione.conversione.domandaTesto'), + extra: h('p.aiuto.spazio-conversione', t('esportazione.conversione.spazio', { n: preview.files, spazio: bytes(preview.bytes) })), + buttons: [ + { label: t('esportazione.conversione.anche', { n: preview.files }), value: 'all', kind: '' }, + { label: t('esportazione.conversione.soloNuovi'), value: 'new', kind: 'primo', autofocus: true }, + ], + }); + if (!answer) { + control.select(before); + return; + } + convertExisting = answer === 'all'; + } + } + await saveSettings({ [key]: v, convertExisting }); + drawConversion(); + } catch (error) { + control.select(before); + showError(error); + } + }, + }); + return control; + } + const libraryBox = h('div.formati-copie', libraryFormat('photo'), libraryFormat('video')); + + /** «In coda 12 · convertiti 340 · non riusciti 2 · non si convertono 3», why it waits, and its commands. */ + function drawConversion() { + const c = overview.libraryConversion; + if (!c) { + conversionStatus.replaceChildren(); + return; + } + const busy = c.pending > 0 || c.on; + const buttons = []; + if (c.paused) buttons.push(h('button.btn.piccolo', { type: 'button', onclick: (e) => conversionCommand('resume', e.currentTarget) }, icon('play', 's'), t('esportazione.conversione.riprendi'))); + else if (busy) buttons.push(h('button.btn.piccolo', { type: 'button', onclick: (e) => conversionCommand('pause', e.currentTarget) }, icon('pause', 's'), t('esportazione.conversione.interrompi'))); + if (c.failed > 0) buttons.push(h('button.btn.piccolo', { type: 'button', onclick: (e) => conversionCommand('retry', e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.conversione.riprova'))); + fill(conversionStatus, + h('div.riga-conteggi', + h('span.muto', c.on || c.pending || c.converted || c.failed || c.asIs ? c.text : t('esportazione.conversione.spenta')), + buttons), + c.waiting && !c.paused ? h('div.avviso.ambra', icon('hourglass', 's'), h('span', c.waiting)) : null); + } + + async function conversionCommand(command, button) { + button.disabled = true; + try { + const result = await api(`/api/export/library-conversion/${command}`, { method: 'POST' }); + toast(result.message); + await reload(); + } catch (error) { + button.disabled = false; + showError(error); + } + } + // ------------------------------------------------------------------------------------------- own folders function drawOwn() { const own = overview.own || []; @@ -173,14 +280,17 @@ export default async function exportSettings(page, box) { drawGeneral(); drawOwn(); drawNotes(); + drawConversion(); } draw(); fill(box, h('div.sezione', heading(t('esportazione.titolo'), t('esportazione.aiuto')), noteBox, pendingBox), h('div.sezione', heading(t('esportazione.generale'), t('esportazione.generaleAiuto')), generalBox), + h('div.sezione.sezione-formati', heading(t('esportazione.formati.titolo'), t('esportazione.formati.aiuto')), formatsBox), h('div.sezione', heading(t('esportazione.stessoPost'), t('esportazione.stessoPostAiuto')), samePost), - h('div.sezione', heading(t('esportazione.cartelleAccount'), t('esportazione.cartelleAccountAiuto')), ownBox)); + h('div.sezione', heading(t('esportazione.cartelleAccount'), t('esportazione.cartelleAccountAiuto')), ownBox), + h('div.sezione.sezione-conversione', heading(t('esportazione.conversione.titolo'), t('esportazione.conversione.aiuto')), libraryBox, conversionStatus)); // Copies finished, a folder paused or changed elsewhere (another tab, an account card): the page follows. const onChange = later(() => reload(), 500); diff --git a/src/Febe.Web/wwwroot/js/pages/viewer.js b/src/Febe.Web/wwwroot/js/pages/viewer.js index bccffe5..b66946f 100644 --- a/src/Febe.Web/wwwroot/js/pages/viewer.js +++ b/src/Febe.Web/wwwroot/js/pages/viewer.js @@ -1,7 +1,9 @@ // Visualizzatore (mockup 02, spec §4.6): covers the whole window; arrows and arrow keys move through the files of the // series and then to the next entry; Esc closes; videos start muted. The side panel shows the data, the files and the // provenance, and the actions: «Mostra nella cartella» (desktop) or «Scarica» (browser), «Apri su Instagram» (in -// Alberto's own browser, never in Febe's), «Elimina dalla libreria». +// Alberto's own browser, never in Febe's), «Elimina dalla libreria». Tappa E3: «Fotogramma» on a video whose frames +// can be taken (the dialog «Fotogrammi…» opens at the player's time), the copy rows with their form («· intero», «· JPG», +// «· fotogramma a 0:01 · PNG») and the converted files of the library next to the original («Convertito in PNG»). import { api, withCarried } from '../core/api.js'; import { caps, serverNow } from '../core/context.js'; @@ -11,6 +13,7 @@ import { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from ' import { avatar, label, showError, toast } from '../core/ui.js'; import { confirmDelete } from './library.js'; import { copyAgain, copyDialog } from './export-dialogs.js'; +import { formatLabel, framesDialog } from './frames.js'; const KIND_ICON = { post: 'image', story: 'circle-dashed', highlight: 'star', tagged: 'square-user', profile: 'circle-user' }; @@ -255,7 +258,8 @@ export function openViewer({ tile, source, origin, onDeleted }) { entry.author ? row(t('vis.autore'), `@${entry.author}`) : null, entry.media.length > 1 ? row(t('vis.posizione'), t('vis.posizioneDi', { n: fileIndex + 1, totale: entry.media.length })) : null, entry.highlights.length ? row(t('vis.raccolte'), entry.highlights.join(', ')) : null, - media && media.copies ? media.copies.map((c) => copyRow(c, media)) : null)), + media && media.copies ? media.copies.map((c) => copyRow(c, media)) : null, + media && media.conversions ? media.conversions.map((c) => conversionRow(c)) : null)), h('section', h('h3', t('vis.provenienza')), h('dl', row(t('vis.origine'), t(entry.provenance === 'imported' ? 'vis.importato' : 'vis.scaricato')), row(t('vis.quando'), downloaded)))); @@ -276,6 +280,14 @@ export function openViewer({ tile, source, origin, onDeleted }) { if (entry.canCopy && media && media.available) { actions.push(h('button.btn', { type: 'button', onclick: () => copyDialog({ mediaIds: [media.id] }) }, icon('copy'), t('esportazione.vis.copiaIn'))); } + // «Fotogramma» (spec §4.6, §4.10): only on a video whose frames can be taken; the others say why not. + if (media && media.kind === 'video' && media.available && !media.damaged) { + if (media.framesAvailable === false) { + actions.push(h('p.aiuto.nota-fotogramma', icon('info', 'xs'), ' ', t('esportazione.vis.fotogrammaNo'))); + } else { + actions.push(h('button.btn.azione-fotogramma', { type: 'button', onclick: () => openFrames(media) }, icon('image'), t('esportazione.vis.fotogrammaAzione'))); + } + } if (entry.state !== 'deleted') { actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina'))); } @@ -290,7 +302,7 @@ export function openViewer({ tile, source, origin, onDeleted }) { const today = caps().today; const vars = { cartella: copy.destination, giorno: shortDay(copy.at.day, today), nome: copy.forAccount || '' }; const key = { copied: copy.forAccount ? 'copiatoPer' : 'copiato', removed: 'tolto', superseded: 'superato' }[copy.state] || 'fallito'; - const text = t(`esportazione.vis.${key}`, vars) + (copy.destinationRetired ? ` (${t('esportazione.vis.tolta')})` : ''); + const text = t(`esportazione.vis.${key}`, vars) + copyForm(copy) + (copy.destinationRetired ? ` (${t('esportazione.vis.tolta')})` : ''); const busy = copying.has(copy.copyId); const again = copy.canCopyAgain ? h('button.btn.nudo.piccolo.copia-di-nuovo', { @@ -310,7 +322,47 @@ export function openViewer({ tile, source, origin, onDeleted }) { }, }, icon('rotate-cw', 's'), t(busy ? 'esportazione.vis.inCopia' : 'esportazione.vis.diNuovo')) : null; - return [h('dt', t('esportazione.vis.copia')), h('dd.riga-copia', h('span', text), again)]; + return [h('dt', t('esportazione.vis.copia')), h('dd.riga-copia', h('span', text), again, copy.notes ? h('span.nota-copia', copy.notes) : null)]; + } + + /** «· intero», «· JPG», «· fotogramma a 0:01 · PNG» (decision D13 for the label of the instant). */ + function copyForm(copy) { + if (copy.variant === 'frame') return t('esportazione.vis.fotogramma', { istante: copy.frameLabel || '', formato: formatLabel(copy.format) }); + if (copy.variant === 'converted') return t('esportazione.vis.formato', { formato: formatLabel(copy.format) }); + return t('esportazione.vis.intero'); + } + + /** + * A converted file of the library next to its original (§16 domanda 30): «Convertito in PNG · 2,1 MB» with «Scarica» + * or «Mostra nella cartella», and what was not kept (or why it does not convert) as a second line. + */ + function conversionRow(c) { + const vars = { formato: formatLabel(c.format), spazio: bytes(c.bytes || 0) }; + const text = t(`esportazione.vis.conversioni.${c.state}`, vars); + let action = null; + if (c.available && (c.state === 'converted' || c.state === 'superseded')) { + action = caps().showInFolder + ? h('button.btn.nudo.piccolo', { type: 'button', onclick: () => showConversion(c.id) }, icon('folder-open', 's'), t('esportazione.vis.mostraConvertito')) + : h('a.btn.nudo.piccolo', { href: withCarried(`/api/conversions/${c.id}/file?download=1`), download: c.fileName || '' }, icon('download', 's'), t('esportazione.vis.scaricaConvertito')); + } + return [h('dt', t('esportazione.vis.conversione')), h('dd.riga-copia.riga-conversione', h('span', text), action, c.notes ? h('span.nota-copia', c.notes) : null)]; + } + + async function showConversion(conversionId) { + try { + const result = await api('/api/conversions/show-in-folder', { method: 'POST', body: { conversionId } }); + toast(result.message); + } catch (error) { + showError(error); + } + } + + /** «Fotogrammi…» at the instant the player shows; the video waits while the dialog is open. */ + function openFrames(media) { + const video = stage.querySelector('video'); + const atMs = video && Number.isFinite(video.currentTime) ? Math.round(video.currentTime * 1000) : 0; + if (video) video.pause(); + framesDialog({ mediaId: media.id, atMs, hasDestination: Boolean(entry.canCopy) }); } async function showInFolder(mediaId) { @@ -358,5 +410,4 @@ export function openViewer({ tile, source, origin, onDeleted }) { document.body.append(box); closeButton.focus(); load(tile.id, 0, files && tile.cover ? tile.cover.mediaId : null); - void withCarried; } diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index e72d376..9a06c5f 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -178,7 +178,10 @@ "torna": "Eliminalo e lascia che torni|Eliminali e lascia che tornino", "tornaSpiega": "Con «lascia che torni» Febe dimentica l'elemento: se è ancora su Instagram, al prossimo controllo lo scarica di nuovo.", "fileDi": "1 file scelto appartiene a {elementi}|{n} file scelti appartengono a {elementi}", - "interi": "elimino l'elemento intero, {file}.|elimino gli elementi interi, {file}." + "interi": "elimino l'elemento intero, {file}.|elimino gli elementi interi, {file}.", + "interiConvertiti": "elimino l'elemento intero, {file} e {convertiti}.|elimino gli elementi interi, {file} e {convertiti}.", + "convertiti": "1 file convertito|{n} file convertiti", + "ancheConvertiti": "Si cancella anche 1 file convertito della libreria, fatto da questi file.|Si cancellano anche {n} file convertiti della libreria, fatti da questi file." }, "vis": { "etichetta": "Visualizzatore", @@ -1123,6 +1126,35 @@ "eraDi": "era di @{nome}", "daRiprendere": "1 copia da riprendere.|{n} copie da riprendere.", "apriEsportazione": "Apri l'esportazione", + "formati": { + "titolo": "Formati delle copie", + "aiuto": "Il formato dei file nelle cartelle delle copie. Un file già in quel formato si copia byte per byte; HEIC, AVIF, raw, immagini animate e ciò che non si converte si copiano come sono, e il resoconto lo dice. Un formato nuovo vale per i file non ancora copiati.", + "foto": "Foto", + "video": "Video", + "original": "Originale", + "jpg": "JPG", + "png": "PNG", + "webplossless": "WEBP senza perdita", + "mp4": "MP4", + "generali": "Come le impostazioni generali", + "comeDestinazione": "Come la destinazione", + "conPerdita": "con perdita: qualità 92", + "soloRimux": "solo rimuxaggio, mai ricodifica", + "originale": "i file si copiano come sono" + }, + "conversione": { + "titolo": "Conversione della libreria", + "aiuto": "Febe può aggiungere nella libreria, accanto a ogni foto o video, il file convertito nel formato scelto. Il file convertito si aggiunge: l'originale resta, con il suo nome, e resta lui il file che si copia e da cui si prendono i fotogrammi. Lavora in sottofondo, mai durante una sessione del motore, e lascia il passo a importazioni, copie e ricostruzioni.", + "domanda": "Convertire anche il file già in libreria?|Convertire anche i {n} file già in libreria?", + "domandaTesto": "Da adesso ogni file nuovo si converte dopo lo scaricamento o l'importazione. Quelli già in libreria si convertono solo se lo chiedi.", + "spazio": "L'originale occupa circa {spazio}; il convertito può occupare di più.|Gli originali occupano circa {spazio}; i convertiti possono occupare di più.", + "soloNuovi": "Solo i nuovi", + "anche": "Anche quello già in libreria|Anche i {n} già in libreria", + "spenta": "Spenta: nessun file della libreria si converte.", + "interrompi": "Interrompi", + "riprendi": "Riprendi", + "riprova": "Riprova i non riusciti" + }, "dockerNota": "Le cartelle delle copie sono sottocartelle di {radice}, il disco o la condivisione montata nel contenitore. Febe non crea mai la cartella scelta: deve esistere già.", "dialogo": { "titoloGenerale": "Cartella generale delle copie", @@ -1154,6 +1186,8 @@ "schemaProfilo": "Schema per le foto del profilo", "segnaposto": "Segnaposto: {elenco}.", "risultato": "Risultato", + "formati": "Formati", + "formatiAiuto": "Il formato dei file copiati in questa cartella. «Come le impostazioni generali» segue Impostazioni → Esportazione, anche quando cambia.", "salva": "Salva la cartella" }, "tipi": { @@ -1185,7 +1219,12 @@ "nessunaCartella": "Nessuna cartella delle copie: scegline una in Impostazioni → Esportazione.", "nienteNonEsportati": "Niente da copiare: questi file sono di account che non si esportano o di tipi che la cartella non copia.", "pulsante": "Copia 1 file|Copia {n} file", - "vediAvanzamento": "Apri l'esportazione" + "vediAvanzamento": "Apri l'esportazione", + "formatoCome": "Formato: come la destinazione", + "formatoScelto": "Formato: foto {foto} · video {video}", + "cambia": "Cambia", + "comeSono": "circa 1 {tipo} copiato com'è|circa {n} {tipo} copiati come sono", + "conPerdita": "con perdita" }, "filtro": { "titolo": "Copie", @@ -1196,19 +1235,35 @@ }, "segno": { "copiato": "copiato", - "parte": "copiato in parte, {n} file di {totale}" + "parte": "copiato in parte, {n} file di {totale}", + "fotogrammi": "Solo fotogrammi" }, "vis": { "copia": "Copia", - "copiato": "Copiato in {cartella} il {giorno} · intero", - "copiatoPer": "Copiato per @{nome} in {cartella} il {giorno} · intero", + "copiato": "Copiato in {cartella} il {giorno}", + "copiatoPer": "Copiato per @{nome} in {cartella} il {giorno}", + "intero": " · intero", + "formato": " · {formato}", + "fotogramma": " · fotogramma a {istante} · {formato}", "tolto": "Tolto da {cartella} il {giorno}", "superato": "Superato in {cartella} il {giorno}", "fallito": "Non riuscito in {cartella} il {giorno}", "tolta": "cartella tolta", "diNuovo": "Copia di nuovo", "inCopia": "In copia…", - "copiaIn": "Copia in…" + "copiaIn": "Copia in…", + "fotogrammaAzione": "Fotogramma", + "fotogrammaNo": "Fotogramma non disponibile per questo video", + "conversione": "Convertito", + "conversioni": { + "converted": "Convertito in {formato} · {spazio}", + "superseded": "Convertito in {formato}, da una versione di prima · {spazio}", + "pending": "In coda per la conversione in {formato}", + "failed": "Conversione in {formato} non riuscita", + "asIs": "Non si converte in {formato}" + }, + "scaricaConvertito": "Scarica", + "mostraConvertito": "Mostra nella cartella" }, "account": { "titolo": "Copie esterne", @@ -1232,7 +1287,48 @@ "copiaIn": "Copia in…" }, "selezione": { - "copia": "Copia in…" + "copia": "Copia in…", + "fotogrammi": "Fotogrammi…" + }, + "fotogrammi": { + "titolo": "Fotogrammi", + "titoloSelezione": "Fotogrammi dei video scelti", + "apro": "Apro il video…", + "video": "Video di {durata}, {l} × {a} pixel.", + "quali": "Quali fotogrammi", + "istante": "Questo istante", + "ogni": "Uno ogni k secondi", + "numero": "N in tutto", + "tempo": "Istante", + "tempoErrato": "Scrivi l'istante come 0:12 o 0:12,5.", + "istanteSelezione": "Lo stesso istante in ogni video; oltre la fine, l'ultimo fotogramma.", + "mostrato": "Fotogramma a {istante}", + "anteprima": "Anteprima del fotogramma", + "ogniCampo": "Uno ogni", + "secondi": "secondi", + "ogniErrato": "Almeno 0,1 secondi.", + "ogniAiuto": "Dall'inizio del video: 0:00, poi ogni k secondi fino alla fine.", + "numeroCampo": "Fotogrammi in tutto", + "numeroErrato": "Da 1 a 1.000.", + "numeroAiuto": "Distribuiti in parti uguali, ognuno al centro della sua parte.", + "altri": "e altro 1|e altri {n}", + "formato": "Formato", + "audio": "Il fotogramma non ha l'audio.", + "uscita": "Dove", + "scarica": "Scarica", + "scaricaAiuto": "Un fotogramma si scarica com'è; più fotogrammi in uno zip.", + "cartella": "Nella cartella delle copie", + "cartellaAiuto": "Nella cartella delle copie di ogni account, accanto alle copie, con l'istante nel nome.", + "nessunaCartella": "Serve una cartella delle copie: scegline una in Impostazioni → Esportazione.", + "nonDisponibile": "Fotogramma non disponibile per questo video", + "conto": "Conto i fotogrammi…", + "quanti": "1 fotogramma|{n} fotogrammi", + "oltre": "Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo", + "nienteCartella": "Niente da copiare: i video scelti non hanno fotogrammi, non si esportano o non sono in libreria.", + "zipLungo": "Più di 20 fotogrammi: lo zip si prepara solo fuori dalle sessioni del motore e quando nessun altro lavoro lungo è in corso.", + "pulsanteScarica": "Scarica 1 fotogramma|Scarica {n} fotogrammi", + "pulsanteCopia": "Copia 1 fotogramma|Copia {n} fotogrammi", + "scaricati": "Scaricamento del fotogramma avviato.|Scaricamento dei {n} fotogrammi avviato." }, "libreria": { "menu": "Esporta", @@ -1299,6 +1395,11 @@ "falliti": "Non riusciti" }, "problemi": "File da guardare", + "note": "Note", + "comeSono": "Come sono", + "conversione": "Conversione della libreria", + "conversioneSpenta": "Spenta: si accende in Impostazioni → Esportazione.", + "conversioneImpostazioni": "Apri le impostazioni", "nessunProblema": "Nessun file da guardare.", "avvisoDaRiprendere": "1 copia da riprendere.|{n} copie da riprendere." } diff --git a/tests/Febe.Tests/Data/ExportConstraintTests.cs b/tests/Febe.Tests/Data/ExportConstraintTests.cs index 8109321..9ee2ea1 100644 --- a/tests/Febe.Tests/Data/ExportConstraintTests.cs +++ b/tests/Febe.Tests/Data/ExportConstraintTests.cs @@ -342,15 +342,21 @@ public sealed class ExportConstraintTests var w = await CreateAsync(db); await InsertAsync(db, "export_copy", w.CopyRow()); await InsertAsync(db, "export_run", w.RunRow(("destination_id", w.Own))); - var conversion = await InsertAsync(db, "media_conversion", w.ConversionRow()); + // A conversion with its file: RemoveAsync drops only the rows without one (Pending, Failed, Removed, tappa E3 WP2). + var conversion = await InsertAsync( + db, + "media_conversion", + w.ConversionRow(("state", "Converted"), ("relative_path", "marta.demo/x.jpg"), ("bytes", 1L), ("sha256", Make.Sha(2)), ("converted_at", 0L))); var withCopy = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.General))); Assert.AreEqual(19, withCopy.SqliteErrorCode, "una destinazione con copie si ritira, non si cancella"); var withRun = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM export_destination WHERE id = @id", ("@id", w.Own))); Assert.AreEqual(19, withRun.SqliteErrorCode, "una destinazione con lavori si ritira, non si cancella"); - var entry = await Assert.ThrowsExactlyAsync(() => db.Entries.RemoveAsync(w.MartaEntry)); - Assert.AreEqual(19, entry.SqliteErrorCode, "un file con un convertito registrato non si cancella"); + var raw = await Assert.ThrowsExactlyAsync(() => ExecuteAsync(db, "DELETE FROM entry WHERE id = @id", ("@id", w.MartaEntry))); + Assert.AreEqual(19, raw.SqliteErrorCode, "un file con un convertito registrato non si cancella"); + var entry = await Assert.ThrowsExactlyAsync(() => db.Entries.RemoveAsync(w.MartaEntry)); + Assert.AreEqual(19, Assert.IsInstanceOfType(entry.InnerException).SqliteErrorCode, "nemmeno attraverso il magazzino"); Assert.IsNotNull(await db.Entries.GetAsync(w.MartaEntry)); Assert.IsNotNull(await db.Media.GetAsync(w.MartaMedia)); Assert.IsNotNull(await db.Conversions.GetAsync(conversion)); @@ -603,6 +609,7 @@ public sealed class ExportConstraintTests ("ListItemsAsync", ExportStore.ItemsOfRunSql(false), [("@r", run), ("@after", 0L), ("@limit", 500L)], false), ("ListItemsAsync (stato)", ExportStore.ItemsOfRunSql(true), [("@r", run), ("@s", "Pending"), ("@after", 0L), ("@limit", 500L)], false), ("ListPendingAsync", MediaConversionStore.PendingSql, [("@after", 0L), ("@limit", 500L)], false), + ("FirstItemIdAsync", ExportStore.FirstItemSql, [("@r", run), ("@m", 1L), ("@v", "Frame"), ("@f", "Png")], false), }; var problems = new List(); foreach (var (name, sql, parameters, sortAllowed) in lookups) @@ -637,7 +644,12 @@ public sealed class ExportConstraintTests var lookupsE2 = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[] { ("FindReplacedCopyAsync", ExportStore.ReplacedCopySql, [("@h", Make.Sha(5008)), ("@d", w.General), ("@a", w.Marta)], false), - ("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original"), ("@a", w.Marta)], true), + ("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@a", w.Marta)], true), + + // Tappa E3 (D3): the lookups of a file in any form but a frame sort the few rows of one SHA-256. + ("ListCurrentCopiesAnyFormAsync", ExportStore.CurrentCopiesAnyFormSql, [("@h", Make.Sha(17)), ("@d", w.General), ("@a", w.Marta)], true), + ("FindLatestCopyAnyFormAsync", ExportStore.LatestCopyAnyFormSql, [("@h", Make.Sha(17)), ("@d", w.General), ("@a", w.Marta)], true), + ("ClearFailedAsync", ExportStore.ClearFailedSql, [("@h", Make.Sha(17)), ("@d", w.General), ("@a", w.Marta), ("@v", "Converted"), ("@f", "Png")], false), ("GetCopyStatesAsync", ExportStore.CopyStatesSql(shas), Shas(("@d", w.General)), false), ("GetCopyStatesAsync (sostituiti)", ExportStore.ReplacedStatesSql(shas), Shas(("@d", w.General)), false), }; diff --git a/tests/Febe.Tests/Data/ExportStoreTests.cs b/tests/Febe.Tests/Data/ExportStoreTests.cs index fbb28fb..55508c8 100644 --- a/tests/Febe.Tests/Data/ExportStoreTests.cs +++ b/tests/Febe.Tests/Data/ExportStoreTests.cs @@ -534,26 +534,37 @@ public sealed class ExportStoreTests using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); var w = await CreateAsync(db); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original)); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1))); var own = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own)); var general = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia)); await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Removed }); - Assert.AreEqual(general.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id, "the newest Copied row"); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Jpg), "another format"); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(2), ExportVariant.Whole, ExportFormat.Original)); + Assert.AreEqual(general.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1)))!.Id, "the newest Copied row"); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(2))); + + // Tappa E3 (D3): a file copied in any form but a frame counts; a frame never does. + var converted = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/c.jpg", account: w.Luca, media: w.LucaMedia) with + { + SourceSha256 = Make.Sha(3), CopySha256 = Make.Sha(4), Variant = ExportVariant.Converted, Format = ExportFormat.Jpg, + }); + Assert.AreEqual(converted.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(3)))!.Id, "a Converted Jpg copy counts"); + await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/f_t0m01s000.png", account: w.Luca, media: w.LucaMedia) with + { + SourceSha256 = Make.Sha(7), CopySha256 = Make.Sha(8), Variant = ExportVariant.Frame, Format = ExportFormat.Png, FrameAt = TimeSpan.FromSeconds(1), + }); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(7)), "a frame does not count"); await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1)); - Assert.AreEqual(own.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id); + Assert.AreEqual(own.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1)))!.Id); await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1)); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original), "a retired folder is not in use"); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1)), "a retired folder is not in use"); // A copy whose account was removed has no account to be «per un altro account». var third = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"G:\Nuova")); var orphan = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg", destination: third.Id)); await db.Accounts.DeleteAsync(w.Marta); Assert.IsNull((await db.Exports.GetCopyAsync(orphan.Id))!.AccountId); - Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original)); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1))); } [TestMethod] diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs index 688b495..621b7e7 100644 --- a/tests/Febe.Tests/Data/LibraryScaleTests.cs +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -83,6 +83,9 @@ public sealed class LibraryScaleTests var copies = await FillCopiesAsync(db, temp, accountIds, ct); fill.Stop(); TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); + TestContext.WriteLine($"Copie: {copies.Copied:N0} copiate (di cui {copies.Converted:N0} convertite), {copies.Removed:N0} tolte, {copies.Superseded:N0} superate, {copies.Frames:N0} fotogrammi, su {copies.Due:N0} file da copiare"); + Assert.IsGreaterThan(0, copies.Converted, "converted copies in the fill"); + Assert.IsGreaterThan(0, copies.Frames, "frames in the fill"); // Plans differ with and without ANALYZE statistics: both must be fast. // The fill stays outside the timings. @@ -111,26 +114,46 @@ public sealed class LibraryScaleTests var destination = $"(CASE e.account_id WHEN {accountIds[OwnAccount]} THEN {own.Id} ELSE {general.Id} END)"; var due = $"m.sha256 IS NOT NULL AND e.account_id <> {accountIds[OffAccount]} AND (e.account_id <> {accountIds[OwnAccount]} OR m.kind = 'Photo')"; - int Insert(WriteContext w, string state, string source, string supersededBy, string which) => w.Command( - $""" - INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, state, superseded_by_sha256, - origin, relative_path, bytes, copy_sha256, copied_at) - SELECT {destination}, e.account_id, m.id, {source}, 'Whole', 'Original', '{state}', {supersededBy}, - 'Written', 'p/' || m.id || '.jpg', 1000, {source}, 1767225600000 - FROM media m JOIN entry e ON e.id = m.entry_id - WHERE {due} AND {which} - """).ExecuteNonQuery(); + int Insert(WriteContext w, string state, string source, string supersededBy, string which, Form? form = null) + { + var f = form ?? Form.Whole; + return w.Command( + $""" + INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, frame_at_ms, state, superseded_by_sha256, + origin, relative_path, bytes, copy_sha256, copied_at) + SELECT {destination}, e.account_id, m.id, {source}, '{f.Variant}', {f.Format}, {f.FrameAt}, '{state}', {supersededBy}, + 'Written', 'p/' || m.id || '{f.Suffix}', 1000, {f.CopySha ?? source}, 1767225600000 + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE {due} AND {which} + """).ExecuteNonQuery(); + } + + // Tappa E3: three in ten of the copied files are converted copies (PNG, or MP4 for a video), which count as + // copied; one video in fifty has a frame in its folder, copied or not, and one in a hundred a frame «Tolto»: + // frames never count in the «Copie» filter (D4), so the counts asserted stay those of the whole copies. + var converted = new Form("Converted", "(CASE m.kind WHEN 'Video' THEN 'Mp4' ELSE 'Png' END)", "NULL", ".c", "'c' || substr(m.sha256, 2)"); + var frame = new Form("Frame", "'Png'", "1000", "_t0m01s000.png", "'f' || substr(m.sha256, 2)"); return await db.WriteAsync( - w => new CopiesWorld( - Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0"), - Insert(w, "Removed", "m.sha256", "NULL", $"{Spread} % 3 <> 0 AND {Spread} % 50 = 1"), + w => + { + var whole = Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0 AND {Spread} % 10 >= 3"); + var convertedCopies = Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0 AND {Spread} % 10 < 3", converted); + var removed = Insert(w, "Removed", "m.sha256", "NULL", $"{Spread} % 3 <> 0 AND {Spread} % 50 = 1"); // The old original of a file replaced in the library («Tieni il più grande», a rebuild). - Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"), - DueFiles(), - accountIds[OwnAccount]), + var superseded = Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"); + var frames = Insert(w, "Copied", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 50 = 7", frame) + + Insert(w, "Removed", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 100 = 9", frame); + return new CopiesWorld(whole + convertedCopies, removed, superseded, DueFiles(), accountIds[OwnAccount], convertedCopies, frames); + }, ct); } + /// The form of the copies an insert writes: variant, format and instant (SQL), name suffix, copy SHA (SQL). + private sealed record Form(string Variant, string Format, string FrameAt, string Suffix, string? CopySha) + { + public static readonly Form Whole = new("Whole", "'Original'", "NULL", ".jpg", null); + } + /// The due files of the fill, from its rules: every file, but none of account 7 and only the photos of account 4. private static int DueFiles() => Enumerable.Range(0, Entries).Sum(n => (n % Accounts) switch { @@ -285,6 +308,9 @@ public sealed class LibraryScaleTests Assert.AreEqual(copies.Due - copies.Copied - copies.Removed - copies.Superseded, files[LibraryCopiesFilter.NotCopied]); } - /// What the export fill wrote: copies by state, the due files, and the account with its own folder. - private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId); + /// + /// What the export fill wrote: copies by state ( with the converted ones), the due files, the + /// account with its own folder, and of tappa E3 the converted copies and the frames (copied and «Tolto»). + /// + private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId, int Converted, int Frames); } diff --git a/tests/Febe.Tests/Docs/GuideTests.cs b/tests/Febe.Tests/Docs/GuideTests.cs index 624749d..d28d58d 100644 --- a/tests/Febe.Tests/Docs/GuideTests.cs +++ b/tests/Febe.Tests/Docs/GuideTests.cs @@ -51,6 +51,7 @@ public sealed partial class GuideTests ["esportazione CSV dell'elenco (§4.8)", new[] { "Libreria" }, new[] { "esporta l'elenco", "`;`", "utf-8 con bom" }], ["copie esterne fuori dal controllo di Febe (§13.2)", new[] { "Esportazione", "Sicurezza-e-riservatezza" }, new[] { "escono dal controllo di febe", "non le cifra", "non le cancella" }], ["le copie esterne: interruttore acceso, radice mai creata, /esporta montata (§4.10)", new[] { "Esportazione" }, new[] { "«esporta questo account»", "è acceso", "febe non la crea mai", "febe_esporta=1", "/esporta", "«copia di nuovo»", "non si ricopiano mai da soli", "dashboard" }], + ["formati, fotogrammi e conversione della libreria (§4.10, tappa E3)", new[] { "Esportazione" }, new[] { "con perdita", "qualità 92", "solo rimuxaggio, mai ricodifica", "già copiato in un altro formato", "il fotogramma non ha l'audio", "fotogramma non disponibile per questo video", "zip", "«solo i nuovi»", "l'originale resta" }], ["/esporta in Docker: variabile e volume facoltativo (§11)", new[] { "Installazione-Docker-e-Unraid", "Problemi-comuni" }, new[] { "/esporta", "febe_esporta" }], ["Telegram: BotFather e identificativo della chat (§13.3)", new[] { "Avvisi-e-Telegram" }, new[] { "@botfather", "/newbot", "getupdates", "\"chat\":{\"id\":", "invia una prova" }], ["pagina sui problemi comuni (M8)", new[] { "Problemi-comuni" }, new[] { "formato non riconosciuto", "disco quasi pieno", "no usable sandbox", "manca la password dell'interfaccia" }], diff --git a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs index 4ec8a32..6c330b3 100644 --- a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs +++ b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs @@ -199,8 +199,77 @@ public sealed partial class SpecificationConsistencyTests ["le tabelle dell'esportazione sono usate da E2", "| `export_destination`", new[] { "usate dalla tappa e2", "nessuna riga vuol dire acceso" }], ["§16 propone le risposte delle domande di E2", "| 22 |", new[] { "copia in…", "anche a mano", "così fa la tappa e2" }], ["la riga del mockup 06 rimanda alle schermate di D1","| `06-attivita.png` |", new[] { "superato dalla dashboard (qui sotto, «schermate della tappa d1»)" }], + ["dalla tappa E3 ci sono formati e fotogrammi, mancano solo i comandi di E4", "Decisioni di Alberto del 18 novembre 2026 (issue #58", new[] { "dalla tappa e3 (28 novembre 2026)", "«fotogrammi…», «fotogramma»", "«conversione della libreria»", "fino a e4 i suoi comandi («è un video fermo?», «salva il fotogramma») mancano" }], + ["«già copiato» guarda il file, non il formato, come proposta", "- **«Già copiato» guarda il file, non il formato**", new[] { "§16 domanda 28", "in qualunque formato", "i fotogrammi non contano", "l'identità registrata resta quella completa", "«già copiato in un altro formato»", "rifà proprio quella copia", "usa i formati di adesso" }], + ["il formato si sceglie dalla copia, dalla destinazione, dalle impostazioni, e si riconosce dai byte", "- **Quale formato** (tappa E3)", new[] { "«copia in…»", "«come le impostazioni generali»", "dai byte, non dall'estensione", "byte per byte", "§16 domanda 36", "`qt `" }], + ["oltre la specifica si copiano come sono CMYK, più di 8 bit e le immagini troppo grandi", "- **Copiati come sono anche**", new[] { "§16 domande 31 e 38", "cmyk", "più di 8 bit", "40 megapixel", "16.384 pixel", "512 mb", "profilo grigio" }], + ["il rimuxaggio tiene l'elenco di modifiche e dice le tracce tolte", "- **Rimuxaggio** (tappa E3)", new[] { "h.264 o hevc", "aac o mp3", "priming", "«tracce tolte: 1»", "più di un taglio", "senza tenerli tutti in memoria" }], + ["il riepilogo prevede le note e lo spazio si controlla sul convertito", "- **Note e spazio** (tappa E3)", new[] { "«come sono»", "«con perdita»", "«circa»", "dimensione del convertito" }], + ["la conversione della libreria aggiunge, chiede «Solo i nuovi» e non è mai fonte di un'esportazione", "- **Conversione della libreria** (tappa E3)", new[] { "accanto all'originale", "mai una sovrascrittura", "mai durante una sessione del motore", "lascia il passo a importazione, copie e ricostruzione", "«solo i nuovi»", "§16 domanda 29", "non è mai la fonte di un'esportazione", "§16 domanda 30", "«riprova i non riusciti»", "9 file e 2 file convertiti", "la ricostruzione non converte", "§16 domanda 37" }], + ["i fotogrammi: istanti, limiti, niente metadati, PNG", "- **Quali fotogrammi** (tappa E3)", new[] { "tempo di presentazione", "oltre la fine l'ultimo", "(i + ½) · durata / n", "§16 domanda 33", "§16 domanda 38", "20.000 per richiesta", "480 pixel", "senza metadati", "§16 domanda 32", "png", "§16 domanda 35" }], + ["nomi e uscite dei fotogrammi, zip compreso", "- **Nomi e uscite dei fotogrammi**", new[] { "`_t0m12s340`", "`_f001`", "`_fotogramma`", "da 2 a 20", "da 21 a 500", "oltre 500", "§16 domanda 34", "`febe-fotogrammi-aaaa-mm-gg.zip`", "stessi file dovuti", "«fotogramma non disponibile per questo video»" }], + ["un fotogramma non fa «Copiato»", "- **Un fotogramma non fa «Copiato».**", new[] { "arrotondato in su", "«solo fotogrammi»", "si riscrive a una nuova richiesta", "«una copia sola» non vale per i fotogrammi" }], + ["la conversione della libreria cede il passo ai lavori lunghi", "- Copie, conversioni e analisi lunghe", new[] { "cede il passo a tutte e tre", "più di 20 fotogrammi" }], + ["l'adozione dei convertiti guarda prima la lunghezza e la forma", "- **Adozione per percorso**", new[] { "prima la lunghezza, poi lo sha-256", "stessa forma" }], + ["un elemento con soli fotogrammi ha il suo segno", "- Per elemento, calcolato al momento", new[] { "solo le copie intere o convertite", "«solo fotogrammi»" }], + ["le tabelle dell'esportazione sono usate da E3", "| `export_destination`", new[] { "dalla tappa e3", "senza una migrazione nuova", "`video_analysis` aspetta e4", "elenchi di codici", "`last_error` dice ciò che non si è tenuto" }], + ["il visualizzatore ha «Fotogramma» e i convertiti, «È un video fermo?» con E4", "- Visualizzatore (mockup 02)", new[] { "«fotogramma» per i video (tappa e3", "«è un video fermo?» a richiesta (tappa e4)", "«convertito in png · 2,1 mb»" }], + ["eliminare toglie i convertiti e la conferma li conta", "- Eliminare chiede conferma", new[] { "file convertiti della libreria", "la conferma li conta" }], + ["le schermate dell'esportazione hanno formati, conversione e fotogrammi", "Schermate dell'esportazione (§4.10", new[] { "«formati delle copie»", "«conversione della libreria»", "«riprova i non riusciti»", "«formato: come la destinazione · cambia»", "«solo fotogrammi»", "dalla tappa e4 «è un video fermo?»", "dalla tappa e5 «automatica»" }], + ["il glossario ha la conversione della libreria", "| Conversione della libreria |", new[] { "`libraryconversion`", "accanto all'originale" }], + ["il glossario ha il file convertito", "| File convertito |", new[] { "`mediaconversion`", "`media_conversion`" }], + ["il glossario ha «Solo fotogrammi»", "| Solo fotogrammi |", new[] { "`exportmark.frameonly`" }], + ["il glossario ha «Copiato com'è»", "| Copiato com'è |", new[] { "una nota" }], ]; + /// The questions of tappa E3 (spec §16, 28–38): each one is a proposal that the stage applies, like E2's. + [TestMethod] + public void TheQuestionsOfStageE3AreProposalsTheStageApplies() + { + var lines = Read("docs", "SPECIFICA.md").Split('\n'); + var problems = new List(); + for (var number = 28; number <= 38; number++) + { + 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); + problems.AddRange(new[] { "e3, prima di unire", "così fa la tappa e3" }.Where(p => !text.Contains(p, StringComparison.Ordinal)).Select(p => $"la domanda {number} di §16 non dice «{p}»")); + } + + Assert.IsEmpty(problems, string.Join("\n", problems)); + } + + /// + /// E3 is built: no document still says that formats, frames or the library conversion come with E3 or are missing until + /// then (the screenshots of E2 may say what they did not show, in the past tense). + /// + [TestMethod] + public void NoDocumentWaitsForE3() + { + var root = Root(); + var files = CurrentDocuments.Append("docs/prove-dal-vivo.md").Select(f => Path.Combine([root, .. f.Split('/')])) + .Concat(Directory.EnumerateFiles(GuideTests.GuideFolder(), "*.md")) + .ToList(); + string[] waiting = + [ + "fino a e3 ed e4", "arrivano con la tappa e3", "aspettano e4 ed e3", "non ci sono (e3)", "la conversione la fa la tappa e3.", + "in questa versione (tappa e2)", + ]; + var problems = new List(); + foreach (var file in files) + { + var text = GuideTests.Normalize(File.ReadAllText(file)); + problems.AddRange(waiting.Where(p => text.Contains(p, StringComparison.Ordinal)).Select(p => $"{Path.GetRelativePath(root, file)} dice ancora «{p}»")); + } + + Assert.IsEmpty(problems, string.Join("\n", problems)); + } + /// /// The confirmation of «Elimina» with «Tutte le foto» that spec §4.6 quotes is the text the interface builds from /// testi/it.json (library.js: «elimina.fileDi», then «: », then «elimina.interi»), with 3 files of 2 entries, 9 files. diff --git a/tests/Febe.Tests/Export/ExportConversionTests.cs b/tests/Febe.Tests/Export/ExportConversionTests.cs new file mode 100644 index 0000000..b588040 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportConversionTests.cs @@ -0,0 +1,407 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Core.Storage; +using Febe.Tests.Codecs.Containers; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The copy job of tappa E3 on real folders (WP1.7): converted copies, byte copies of the same format, files copied as +/// they are with a note, the format chosen by the request, the destination or the settings (D1), «già copiato» in any +/// form (D3), adoption of a converted file (D10), «Copia di nuovo» of a form (D11), the space of the converted size +/// (D17) and the file time (D18). The media are built by the tests; more frames are in . +/// +[TestClass] +public sealed class ExportConversionTests +{ + private static readonly byte[] PngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task APhotoIsConvertedAndThenCountsAsCopiedInAnyForm() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "960", 31); + var media = post.Media[0]; + await bed.GeneralAsync(ct: ct); + + var start = await bed.CopyAsync( + new ExportJobRequest(new ExportSelection.Media([media.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)), ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportVariant.Converted, ExportFormat.Png), (item.State, item.Variant, item.Format)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png, media.Sha256), (copy.Variant, copy.Format, copy.SourceSha256)); + Assert.AreEqual("marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".png"), copy.RelativePath); + + var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)); + var bytes = await File.ReadAllBytesAsync(file, ct); + CollectionAssert.AreEqual(PngSignature, bytes[..8]); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), copy.CopySha256); + Assert.AreNotEqual(media.Sha256, copy.CopySha256); + Assert.AreEqual(bytes.Length, copy.Bytes); + Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, media)), "no byte copy next to it"); + + // «Già copiato» is any form but a frame (D3): a copy of the account in Originale writes nothing more. + var again = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var second = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, copy.Id, ExportText.Notes.CopiedInAnotherFormat), (second.State, second.CopyId, second.Note)); + Assert.AreEqual("Già copiato in un altro formato", ExportText.Note(second.Note)); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task AFrameIsWrittenWithItsInstantAndLeavesTheVideoToCopy() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D")); + var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "961", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")]); + var video = post.Media[0]; + await bed.GeneralAsync(ct: ct); + + var frames = new ExportFramesRequest(FrameMode.At, TimeSpan.Zero, null, null, ExportFormat.Png); + var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: frames), ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Completed, run.State); + var item = (await bed.ItemsAsync(run.Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportVariant.Frame, ExportFormat.Png, (TimeSpan?)TimeSpan.Zero), (item.State, item.Variant, item.Format, item.FrameAt)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Frame, ExportFormat.Png, video.Sha256), (copy.Variant, copy.Format, copy.SourceSha256)); + Assert.IsNotNull(copy.FrameAt); + StringAssert.Contains(copy.RelativePath, "_t0m00s"); + StringAssert.EndsWith(copy.RelativePath, ".png"); + + var bytes = await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct); + CollectionAssert.AreEqual(PngSignature, bytes[..8]); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), copy.CopySha256); + + // A frame never makes the file copied (D4): the mark says so, and «Copia in…» copies the video itself. + Assert.AreEqual(ExportMark.FrameOnly, (await bed.Db.Exports.GetFileMarksAsync([video.Id], ct))[video.Id]); + var whole = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copied = (await bed.ItemsAsync(whole.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportVariant.Whole), (copied.State, copied.Variant)); + Assert.AreEqual(ExportMark.Copied, (await bed.Db.Exports.GetFileMarksAsync([video.Id], ct))[video.Id]); + + // The same instant asked again is «Già copiato» (its exact identity, D12). + var repeat = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: frames), ct); + var same = (await bed.ItemsAsync(repeat.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, copy.Id), (same.State, same.CopyId)); + Assert.HasCount(2, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task JpgToJpgIsAByteCopyAndTheLibraryIsUntouched() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Jpg, ct); + var post = await bed.PostAsync(bed.Marta, "962", 33); + var media = post.Media[0]; + await bed.GeneralAsync(ct: ct); + var library = Fingerprint.Of(bed.Temp.Combine("libreria")); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + Assert.AreEqual((1, 0, false), (start.Plan.Files, start.Plan.Converted, start.Plan.Lossy), "a JPEG to JPG is not a conversion, nor «con perdita»"); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, (string?)null), (item.State, item.Note)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (copy.Variant, copy.Format, copy.CopySha256)); + CollectionAssert.AreEqual(await File.ReadAllBytesAsync(bed.LibraryFile(bed.Marta, media), ct), await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, media), ct)); + Fingerprint.AreEqual(library, Fingerprint.Of(bed.Temp.Combine("libreria")), "the library is never touched"); + } + + [TestMethod] + public async Task APngIsConvertedToTheDestinationFormatWithItsNoteAndTime() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Png, ct); // the destination's format wins over this one + using var picture = Imaging.TestImages.Gradient(40, 30, seed: 6); // with transparent pixels + var post = await SaveAsync(bed, bed.Marta, "963", ImageConverter.Encode(picture, ImageFormat.Png, null), ".png"); + var media = post.Media[0]; + await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Jpg), ct); + var library = Fingerprint.Of(bed.Temp.Combine("libreria")); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + Assert.AreEqual((1, 1, true), (start.Plan.Files, start.Plan.Converted, start.Plan.Lossy)); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.TransparencyWhite), (item.State, item.Note)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Jpg, media.Sha256), (copy.Variant, copy.Format, copy.SourceSha256)); + Assert.AreEqual("marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".jpg"), copy.RelativePath); + var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)); + var bytes = await File.ReadAllBytesAsync(file, ct); + CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 0xFF }, bytes[..3]); + Assert.AreEqual((Convert.ToHexStringLower(SHA256.HashData(bytes)), (long?)bytes.Length), (copy.CopySha256, copy.Bytes)); + Assert.AreEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(file), "«libreria.data-file-pubblicazione» is on"); + Fingerprint.AreEqual(library, Fingerprint.Of(bed.Temp.Combine("libreria")), "the original stays as it is"); + + // The report lists the note, in Italian. + var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct); + var line = report.Notes.Single(); + Assert.AreEqual((item.Id, ExportItemState.Copied), (line.ItemId, line.State)); + Assert.AreEqual(ExportText.Note(ExportText.Notes.TransparencyWhite), line.Text); + Assert.IsEmpty(report.Accounts.Single().AsIs); + } + + [TestMethod] + public void TheFormatIsTheRequestsThenTheDestinationsThenTheSettings() + { + var settings = ExportSettings.Default with { PhotoFormat = ExportFormat.Png, VideoFormat = ExportFormat.Mp4 }; + var destination = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = "/copie", ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }; + var jpgHere = destination with { PhotoFormat = ExportFormat.Jpg, VideoFormat = ExportFormat.Original }; + + Assert.AreEqual(ExportFormat.Png, ExportConversions.Resolve(MediaKind.Photo, null, destination, settings)); + Assert.AreEqual(ExportFormat.Mp4, ExportConversions.Resolve(MediaKind.Video, null, destination, settings)); + Assert.AreEqual(ExportFormat.Jpg, ExportConversions.Resolve(MediaKind.Photo, null, jpgHere, settings)); + Assert.AreEqual(ExportFormat.Original, ExportConversions.Resolve(MediaKind.Video, null, jpgHere, settings)); + Assert.AreEqual(ExportFormat.WebpLossless, ExportConversions.Resolve(MediaKind.Photo, new ExportFormatChoice(ExportFormat.WebpLossless, null), jpgHere, settings)); + Assert.AreEqual(ExportFormat.Mp4, ExportConversions.Resolve(MediaKind.Video, new ExportFormatChoice(null, ExportFormat.Mp4), jpgHere, settings)); + Assert.AreEqual(ExportFormat.Jpg, ExportConversions.Resolve(MediaKind.Photo, new ExportFormatChoice(ExportFormat.Mp4, null), jpgHere, settings), "a video format is not a photo's"); + } + + [TestMethod] + public async Task TheRequestOverridesTheDestination() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "964", 34); + await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Png), ct); + + var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id]), Formats: new ExportFormatChoice(ExportFormat.WebpLossless, null)), ct); + + var copy = (await bed.Db.Exports.GetCopyAsync((await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single().CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.WebpLossless), (copy.Variant, copy.Format)); + StringAssert.EndsWith(copy.RelativePath, ".webp"); + Assert.AreEqual(ImageFormat.WebP, ImageFormatSniffer.Detect(await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct))); + } + + [TestMethod] + public async Task HeicIsCopiedAsItIsWithANoteAndTheReportCountsIt() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Jpg, ct); + byte[] heic = [0, 0, 0, 0x18, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, 0, 0, 0, 8, .. "free"u8, .. new byte[64]]; + var post = await SaveAsync(bed, bed.Marta, "965", heic, ".heic"); + var media = post.Media[0]; + await bed.GeneralAsync(ct: ct); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + Assert.AreEqual(new ExportPlanAsIs("HEIC", 1), start.Plan.AsIs.Single(), "predicted from the name"); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.AsIsHeif), (item.State, item.Note)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (copy.Variant, copy.Format, copy.CopySha256)); + CollectionAssert.AreEqual(heic, await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, media), ct)); + + var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(1, report.Accounts.Single().AsIs["HEIC"]); + Assert.AreEqual(ExportText.Note(ExportText.Notes.AsIsHeif), report.Notes.Single().Text); + } + + [TestMethod] + public async Task AConvertedFileAtThePathIsAdoptedAndASameSizeDifferentFileIsNot() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Jpg, ct); + var same = await SavePngAsync(bed, "966", 35); + var other = await SavePngAsync(bed, "967", 36); + await bed.GeneralAsync(ct: ct); + + // An earlier conversion of the same file (the bytes Febe makes), and one of the other file with a byte changed. + var adopted = ConvertedPath(bed, same.Media[0], ".jpg"); + var foreign = ConvertedPath(bed, other.Media[0], ".jpg"); + Directory.CreateDirectory(Path.GetDirectoryName(adopted)!); + Directory.CreateDirectory(Path.GetDirectoryName(foreign)!); + var conversion = await ConvertAsync(bed, same.Media[0], ExportFormat.Jpg, ct); + await File.WriteAllBytesAsync(adopted, conversion, ct); + var handDate = new DateTime(2020, 5, 1, 12, 0, 0, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(adopted, handDate); + var changed = await ConvertAsync(bed, other.Media[0], ExportFormat.Jpg, ct); + changed[^10] ^= 0x01; + await File.WriteAllBytesAsync(foreign, changed, ct); + var before = Fingerprint.Of(bed.Usb); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + + var items = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).ToDictionary(i => i.MediaId!.Value); + var adoption = items[same.Media[0].Id]; + Assert.AreEqual(ExportItemState.Adopted, adoption.State); + var copy = (await bed.Db.Exports.GetCopyAsync(adoption.CopyId!.Value, ct))!; + Assert.AreEqual((ExportCopyOrigin.Adopted, ExportVariant.Converted, ExportFormat.Jpg), (copy.Origin, copy.Variant, copy.Format)); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(conversion)), copy.CopySha256); + Assert.AreEqual(handDate, File.GetLastWriteTimeUtc(adopted), "adopted, not written again"); + + var written = items[other.Media[0].Id]; + Assert.AreEqual(ExportItemState.Copied, written.State); + StringAssert.Contains(written.Note, ExportText.Notes.NameTaken); + StringAssert.EndsWith(written.RelativePath, " (2).jpg"); + var after = Fingerprint.Of(bed.Usb); + foreach (var (path, print) in before) + { + Assert.AreEqual(print, after[path], path); + } + + Assert.AreEqual(before.Count + 1, after.Count); + } + + [TestMethod] + public async Task SpaceIsCheckedOnTheConvertedSize() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await FormatsAsync(bed, ExportFormat.Png, ct); + var post = await bed.PostAsync(bed.Marta, "968", 37); + var media = post.Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + long png = (await ConvertAsync(bed, media, ExportFormat.Png, ct)).Length; + Assert.IsGreaterThan(media.Bytes!.Value, png, "the PNG of a small JPEG is bigger"); + + bed.Disk.Free = media.Bytes!.Value + ExportSpace.Margin; // enough for the original, not for its PNG + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Paused, run.State); + StringAssert.Contains(run.LastError, "margine di 64 MB"); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + + bed.Disk.Free = png + ExportSpace.Margin; + await bed.Service.ResumeAsync([run.Id], ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + Assert.AreEqual(png, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single().Bytes); + } + + [TestMethod] + public async Task ARemovedWholeCopyIsNotCopiedAgainInTheNewFormatUntilAskedAndExactIgnoresOtherForms() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await SavePngAsync(bed, "969", 38); + var media = post.Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + var first = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var whole = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value; + File.Delete(bed.GeneralCopy(bed.Marta, media)); + + // The format changes to JPG: the file was copied («Tolto» now), so it is not copied again by itself (D3). + await FormatsAsync(bed, ExportFormat.Jpg, ct); + var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Removed, (long?)whole), (item.State, item.Note, item.CopyId)); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); + + // «Copia di nuovo» from the dialog writes the current form: a JPG. + var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct); + var converted = (await bed.Db.Exports.GetCopyAsync((await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Jpg, ExportCopyState.Copied), (converted.Variant, converted.Format, converted.State)); + Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(whole, ct))!.State); + + // «Copia di nuovo» of the removed row from the viewer: its own form, whatever else is copied (D11). + var exact = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([media.Id]), CopyAgain: true, Exact: new ExportCopyRequest(ExportVariant.Whole, ExportFormat.Original, null)), ct); + var back = (await bed.ItemsAsync(exact.Runs.Single().Id, ct)).Single(); + Assert.AreEqual(ExportItemState.Copied, back.State); + var restored = (await bed.Db.Exports.GetCopyAsync(back.CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original), (restored.Variant, restored.Format)); + Assert.AreNotEqual(whole, restored.Id); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, media))); + Assert.HasCount(2, Fingerprint.Of(bed.Usb), "the JPG and the PNG"); + Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(converted.Id, ct))!.State); + + // The JPG asked again exactly: «Già copiato». + var twice = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([media.Id]), CopyAgain: true, Exact: new ExportCopyRequest(ExportVariant.Converted, ExportFormat.Jpg, null)), ct); + var same = (await bed.ItemsAsync(twice.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, (long?)converted.Id), (same.State, same.CopyId)); + Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); + } + + [TestMethod] + public async Task OneCopyOnlyIgnoresTheFormat() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await (ExportSettings.Default with { SamePost = SamePostCopies.OneOnly, PhotoFormat = ExportFormat.Jpg }).SaveAsync(bed.Db.Settings, ct); + using var image = TestImages.Scene(39, 64, 48); + var png = TestImages.Png(image); + await SaveAsync(bed, bed.Marta, "970", png, ".png"); + await SaveAsync(bed, bed.Luca, "970", png, ".png"); + await bed.GeneralAsync(ct: ct); + + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var luca = await bed.CopyAccountAsync(bed.Luca, ct: ct); + + var item = (await bed.ItemsAsync(luca.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (item.State, item.Note)); + Assert.AreEqual(ExportVariant.Converted, (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.Variant); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task AChangedSourceFailsTheConversionAndAStaleFailedRowIsClearedLater() + { + var ct = TestContext.CancellationToken; + var corrupt = true; + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = new CorruptingExportFileSystem(path => corrupt && path.EndsWith(".jpg", StringComparison.Ordinal)) }); + await FormatsAsync(bed, ExportFormat.Png, ct); + var post = await bed.PostAsync(bed.Marta, "971", 40); + var usb = await bed.GeneralAsync(ct: ct); + + var failed = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(failed.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Failed, ExportText.Notes.SourceChanged), (item.State, item.Note)); + var row = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + Assert.AreEqual((ExportCopyState.Failed, ExportVariant.Converted, ExportFormat.Png), (row.State, row.Variant, row.Format)); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + + // The disk reads well again and the format is back to Originale: the copy is written, the old failure goes. + corrupt = false; + await FormatsAsync(bed, ExportFormat.Original, ct); + var copied = await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.AreEqual(ExportItemState.Copied, (await bed.ItemsAsync(copied.Runs.Single().Id, ct)).Single().State); + var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct); + Assert.AreEqual((ExportCopyState.Copied, ExportVariant.Whole), (copies.Single().State, copies.Single().Variant), "the «Non riuscito» row of the other form has no use"); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + } + + private static Task FormatsAsync(ExportTestBed bed, ExportFormat photo, CancellationToken ct) => + (ExportSettings.Default with { PhotoFormat = photo }).SaveAsync(bed.Db.Settings, ct); + + private static Task SaveAsync(ExportTestBed bed, Account account, string code, byte[] bytes, string extension) => + bed.Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-1)), [new TestFile(Make.Photo(1), bytes, extension)]); + + private static Task SavePngAsync(ExportTestBed bed, string code, int scene) + { + using var image = TestImages.Scene(scene, 64, 48); + return SaveAsync(bed, bed.Marta, code, TestImages.Png(image), ".png"); + } + + /// Where the general folder gets the converted copy of a file of marta.demo. + private static string ConvertedPath(ExportTestBed bed, Media media, string extension) => + Path.Combine(bed.Usb, bed.Marta.Username, LibraryLayout.ToPlatform(Path.ChangeExtension(media.RelativePath!, extension))); + + /// The bytes Febe makes of a library file in a format. + private static async Task ConvertAsync(ExportTestBed bed, Media media, ExportFormat format, CancellationToken ct) + { + var path = bed.LibraryFile(bed.Marta, media); + using var conversion = await MediaConverter.PrepareAsync(() => File.OpenRead(path), media.RelativePath!, media.Kind, format, media.Sha256!, new ConversionThrottle(), ct); + Assert.AreEqual(ExportVariant.Converted, conversion.Variant); + using var output = new MemoryStream(); + await conversion.Produce!(output, ct); + return output.ToArray(); + } +} diff --git a/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs index 1902b26..ac0d597 100644 --- a/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs +++ b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs @@ -100,7 +100,7 @@ public sealed class ExportCopiesFilterTests Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.Own, [(w.Marta, Make.Sha(1))], ct))[(w.Marta, Make.Sha(1))]); Assert.IsNotNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(1), ct)); Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Luca, Make.Sha(1), ct)); - Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct: ct))!.Id); + Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ct: ct))!.Id); var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct); Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId); diff --git a/tests/Febe.Tests/Export/ExportFoundationTests.cs b/tests/Febe.Tests/Export/ExportFoundationTests.cs index 7c0bd10..73672f1 100644 --- a/tests/Febe.Tests/Export/ExportFoundationTests.cs +++ b/tests/Febe.Tests/Export/ExportFoundationTests.cs @@ -37,6 +37,79 @@ public sealed class ExportFoundationTests rebuild.Dispose(); } + [TestMethod] + public void AForegroundLeasePreemptsTheBackgroundOneAndBusyIgnoresIt() + { + var gate = new LongWorkGate(); + Assert.IsTrue(gate.TryEnterBackground(out var background)); + Assert.IsNull(gate.Busy, "Busy ignores the background lease"); + Assert.IsTrue(gate.BackgroundRunning); + Assert.IsFalse(gate.TryEnterBackground(out _)); + + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _)); + Assert.IsTrue(background.Preempted.IsCancellationRequested); + Assert.IsTrue(background.IsPreempted); + Assert.IsFalse(background.TryBeginCommit(out _), "no commit once pre-empted"); + Assert.IsFalse(gate.BackgroundRunning); + Assert.AreEqual(LongWorkKind.Import, gate.Busy); + background.Dispose(); + + Assert.IsFalse(gate.TryEnterBackground(out _), "the background waits for the foreground"); + import.Dispose(); + Assert.IsTrue(gate.TryEnterBackground(out var again)); + again.Dispose(); + Assert.IsFalse(gate.BackgroundRunning); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var export, out _)); + export.Dispose(); + } + + [TestMethod] + public async Task AForegroundLeaseWaitsForACommit() + { + var gate = new LongWorkGate(); + Assert.IsTrue(gate.TryEnterBackground(out var background)); + Assert.IsTrue(background.TryBeginCommit(out var commit)); + var entering = Task.Run(() => gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _) ? lease : null, TestContext.CancellationToken); + while (!background.Preempted.IsCancellationRequested) + { + await Task.Yield(); + } + + Assert.IsFalse(entering.IsCompleted, "the rebuild waits for the commit"); + commit.Dispose(); + var rebuild = await entering; + Assert.IsNotNull(rebuild); + rebuild.Dispose(); + background.Dispose(); + + // A commit that does not end in time: the foreground job is refused with its own message. + var quick = new LongWorkGate { CommitWait = TimeSpan.FromMilliseconds(20) }; + Assert.IsTrue(quick.TryEnterBackground(out var slow)); + Assert.IsTrue(slow.TryBeginCommit(out var held)); + Assert.IsFalse(quick.TryEnter(LongWorkKind.Export, out _, out var busy)); + Assert.AreEqual(LongWorkKind.LibraryConversion, busy); + Assert.IsNull(quick.Busy); + held.Dispose(); + slow.Dispose(); + } + + [TestMethod] + public void NewKindsHaveTheirOwnMessages() + { + Assert.AreEqual( + "La conversione della libreria sta salvando un file: riprova fra un attimo.", + LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.LibraryConversion)); + Assert.AreEqual( + "Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi importa.", + LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.FrameDownload)); + Assert.AreEqual( + "C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi scarica i fotogrammi.", + LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Import)); + Assert.AreEqual( + "La ricostruzione del database è in corso: aspetta che finisca.", + LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Rebuild)); + } + [TestMethod] public async Task AnImportDoesNotStartWhileTheGateIsHeld() { diff --git a/tests/Febe.Tests/Export/ExportFrameNamesTests.cs b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs new file mode 100644 index 0000000..db03fcf --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs @@ -0,0 +1,122 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Tests.Codecs.Containers; + +namespace Febe.Tests.Export; + +/// +/// Instants, suffixes and labels of frames (tappa E3, D12 and D13), the protected suffix of the shortening and of the +/// numbered names (WP1.8), and the environment-free media conversion (WP1.6b). +/// +[TestClass] +public sealed class ExportFrameNamesTests +{ + [TestMethod] + public void EveryKSecondsStartsAtZeroAndStopsBeforeTheEnd() + { + var instants = ExportFrames.Every(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(500)); + + CollectionAssert.AreEqual( + new[] { 0, 500, 1000, 1500 }.Select(ms => TimeSpan.FromMilliseconds(ms)).ToArray(), + instants.ToArray()); + Assert.ThrowsExactly(() => ExportFrames.Every(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(50))); + var over = Assert.ThrowsExactly(() => ExportFrames.Every(TimeSpan.FromHours(1), TimeSpan.FromSeconds(1))); + StringAssert.StartsWith(over.Message, ExportFrames.OverCapMessage); + } + + [TestMethod] + public void NInAllAreCentred() + { + var instants = ExportFrames.Spread(TimeSpan.FromSeconds(4), 4); + + CollectionAssert.AreEqual( + new[] { 500, 1500, 2500, 3500 }.Select(ms => TimeSpan.FromMilliseconds(ms)).ToArray(), + instants.ToArray()); + Assert.ThrowsExactly(() => ExportFrames.Spread(TimeSpan.FromSeconds(4), 1001)); + } + + [TestMethod] + public void SuffixesAndLabels() + { + var actual = TimeSpan.FromTicks((12_340 * TimeSpan.TicksPerMillisecond) - 3); // rounded up to 12.340 s + + Assert.AreEqual("_t0m12s340", ExportFrames.Suffix(FrameMode.At, actual, 0, 1)); + Assert.AreEqual("_t1m05s000", ExportFrames.Suffix(FrameMode.Every, TimeSpan.FromSeconds(65), 3, 9)); + Assert.AreEqual("_f001", ExportFrames.Suffix(FrameMode.Count, actual, 0, 12)); + Assert.AreEqual("_f0042", ExportFrames.Suffix(FrameMode.Count, actual, 41, 1000)); + Assert.AreEqual("0:01", ExportFrames.Label(TimeSpan.FromSeconds(1))); + Assert.AreEqual("0:01,25", ExportFrames.Label(TimeSpan.FromMilliseconds(1250))); + Assert.AreEqual("2:03,007", ExportFrames.Label(TimeSpan.FromMilliseconds(123_007))); + } + + [TestMethod] + public void AKeptSuffixIsNotCutAndNumberingComesAfterIt() + { + var root = "/destinazione/" + new string('d', 120); + var name = new string('n', 200) + "_t0m12s340.png"; + + var fitted = WindowsFileNames.FitPath(root, ["post", name], keepSuffix: "_t0m12s340"); + Assert.EndsWith("_t0m12s340.png", fitted[^1]); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, root.Length + fitted.Sum(s => s.Length + 1)); + CollectionAssert.AreEqual( + WindowsFileNames.FitPath(root, ["post", name]).ToArray(), + WindowsFileNames.FitPath(root, ["post", name], keepSuffix: null).ToArray(), + "Senza suffisso nulla cambia."); + + var numbered = ExportPaths.NumberedName(root, "post/" + name, 2, keepSuffix: "_t0m12s340"); + Assert.EndsWith("_t0m12s340 (2).png", numbered); + Assert.AreEqual("post/a_f001 (3).png", ExportPaths.NumberedName("/d", "post/a_f001.png", 3, keepSuffix: "_f001")); + } + + [TestMethod] + public async Task APhotoIsConvertedWithItsShaAndAChangedSourceIsRefused() + { + using var picture = Imaging.TestImages.Gradient(40, 30, seed: 5); + var png = ImageConverter.Encode(picture, ImageFormat.Png, null); + var sha = Convert.ToHexStringLower(SHA256.HashData(png)); + + using var jpg = await MediaConverter.PrepareAsync(() => new MemoryStream(png), "a/b.png", MediaKind.Photo, + ExportFormat.Jpg, sha, new ConversionThrottle(), CancellationToken.None); + using var output = new MemoryStream(); + await jpg.Produce(output, CancellationToken.None); + + Assert.AreEqual(ExportVariant.Converted, jpg.Variant); + Assert.AreEqual(".jpg", jpg.Extension); + Assert.AreEqual(jpg.Length, output.Length); + Assert.AreEqual(jpg.Sha256, Convert.ToHexStringLower(SHA256.HashData(output.ToArray()))); + CollectionAssert.Contains(jpg.Notes.ToList(), ImageConversionLosses.TransparencyWhite); + + using var same = await MediaConverter.PrepareAsync(() => new MemoryStream(png), "a/b.png", MediaKind.Photo, + ExportFormat.Png, sha, ConversionThrottle.Shared, CancellationToken.None); + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, sha, ".png"), (same.Variant, same.Format, same.Sha256, same.Extension)); + + await Assert.ThrowsExactlyAsync(() => MediaConverter.PrepareAsync(() => new MemoryStream(png), + "a/b.png", MediaKind.Photo, ExportFormat.Jpg, new string('0', 64), ConversionThrottle.Shared, CancellationToken.None)); + } + + [TestMethod] + public async Task AVideoIsRemuxedOrCopiedWithTheReason() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var mkv = TestVideos.Matroska(es); + var sha = Convert.ToHexStringLower(SHA256.HashData(mkv)); + + using var remux = await MediaConverter.PrepareAsync(() => new MemoryStream(mkv), "v.mkv", MediaKind.Video, + ExportFormat.Mp4, sha, ConversionThrottle.Shared, CancellationToken.None); + using var output = new MemoryStream(); + await remux.Produce(output, CancellationToken.None); + Assert.AreEqual((ExportVariant.Converted, ".mp4", (string?)null), (remux.Variant, remux.Extension, remux.Sha256)); + Assert.AreEqual(remux.Length, output.Length); + + var garbage = new byte[2048]; + using var asIs = await MediaConverter.PrepareAsync(() => new MemoryStream(garbage), "v.mov", MediaKind.Video, + ExportFormat.Mp4, sha, ConversionThrottle.Shared, CancellationToken.None); + Assert.AreEqual(ExportVariant.Whole, asIs.Variant); + Assert.HasCount(1, asIs.Notes); + StringAssert.StartsWith(asIs.Notes[0], MediaConversionResult.AsIsNotRemuxable + ":"); + } +} diff --git a/tests/Febe.Tests/Export/ExportFramesTests.cs b/tests/Febe.Tests/Export/ExportFramesTests.cs new file mode 100644 index 0000000..c451db6 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFramesTests.cs @@ -0,0 +1,364 @@ +using Febe.Core.Abstractions; +using Febe.Core.Codecs.Containers; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Codecs.Containers; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// «Fotogrammi…» → «Nella cartella delle copie» (tappa E3, D4 and D12-D14): frames go to the destination of each +/// account with their suffix, one copy per frame shown, never making the video «Copiato»; photos, accounts that are not +/// exported and videos without frames are skipped; the job waits for engine sessions; a removed frame is written again +/// on request; a request over the cap is refused before anything is recorded. The videos are built by the tests. +/// +[TestClass] +public sealed class ExportFramesTests +{ + private static readonly ElementaryStream Stream = ElementaryStream.Load("BA1_Sony_D"); + private static readonly byte[] Mp4 = TestVideos.Mp4(Stream); + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task FramesGoToTheDestinationWithTheirSuffixes() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var duration = TimeSpan.FromMilliseconds((long)Duration(Mp4).TotalMilliseconds); // as the library keeps it + var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "990", Make.T0.AddDays(-2)), [ + new TestFile(Make.Video(1) with { Duration = duration }, Mp4, ".mp4"), + ])).Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + + // «N in tutto»: _f001…_f003, PNG. + var count = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, 3, ExportFormat.Png)), ct); + Assert.AreEqual((1, 3, 3), (count.Plan.Videos, count.Plan.Frames, count.Plan.Files)); + Assert.AreEqual(0L, count.Plan.Bytes, "frames have no size before they are made"); + var items = await bed.ItemsAsync(count.Runs.Single().Id, ct); + Assert.IsTrue(items.All(i => i.State == ExportItemState.Copied && i.Variant == ExportVariant.Frame && i.Format == ExportFormat.Png)); + CollectionAssert.AreEqual( + ExportFrames.Spread(duration, 3).Select(t => (TimeSpan?)TimeSpan.FromMilliseconds((long)t.TotalMilliseconds)).ToArray(), + items.Select(i => i.FrameAt).ToArray(), + "the item keeps the instant asked (in milliseconds)"); + var stem = Path.ChangeExtension(video.RelativePath!, null); + CollectionAssert.AreEqual( + new[] { "_f001", "_f002", "_f003" }.Select(s => "marta.demo/" + stem + s + ".png").ToArray(), + items.Select(i => i.RelativePath).ToArray()); + + // «Uno ogni k secondi»: the actual instant of the frame shown, rounded up to the millisecond, in the name and the row. + var every = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(250), null, ExportFormat.Jpg)), ct); + var shown = Locate(Mp4, ExportFrames.Every(duration, TimeSpan.FromMilliseconds(250))); + var frames = await bed.ItemsAsync(every.Runs.Single().Id, ct); + Assert.HasCount(shown.Count, frames); + for (var i = 0; i < shown.Count; i++) + { + var copy = (await bed.Db.Exports.GetCopyAsync(frames[i].CopyId!.Value, ct))!; + Assert.AreEqual((ExportVariant.Frame, ExportFormat.Jpg, video.Sha256), (copy.Variant, copy.Format, copy.SourceSha256)); + Assert.AreEqual(TimeSpan.FromMilliseconds(ExportFrames.ActualMs(shown[i].Actual)), copy.FrameAt); + Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Every, shown[i].Actual, i, shown.Count) + ".jpg", copy.RelativePath); + var bytes = await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct); + CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 0xFF }, bytes[..3]); + } + + StringAssert.EndsWith(frames[0].RelativePath, "_t0m00s000.jpg"); + Assert.HasCount(3 + shown.Count, Fingerprint.Of(bed.Usb)); + Assert.IsTrue(every.Plan.Lossy, "JPG frames are «con perdita»"); + Assert.IsFalse(count.Plan.Lossy); + Assert.IsTrue(File.Exists(bed.LibraryFile(bed.Marta, video))); + Assert.HasCount(3 + shown.Count, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); + } + + [TestMethod] + public async Task TheSameFrameShownIsCopiedOnceAndABatchSpansPages() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var still = TestVideos.Mp4(Stream.FirstPictureRepeated(30)); // one second, 30 samples + var video = (await SaveVideoAsync(bed, bed.Marta, "991", still, ".mp4")).Media[0]; + await bed.GeneralAsync(ct: ct); + + // 600 instants (more than a page of the copier, at least a millisecond apart) on 30 frames: each frame shown once. + const int N = 600; + var targets = Locate(still, ExportFrames.Spread(Duration(still), N)); + var leaders = targets.Select((t, i) => (t.Sample, i)).GroupBy(x => x.Sample).Select(g => g.First().i).ToList(); + Assert.HasCount(30, leaders); + + var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, N, ExportFormat.Png)), ct); + + var items = await bed.ItemsAsync(start.Runs.Single().Id, ct); + Assert.HasCount(N, items); + Assert.AreEqual(leaders.Count, items.Count(i => i.State == ExportItemState.Copied)); + Assert.AreEqual(N - leaders.Count, items.Count(i => i.State == ExportItemState.AlreadyCopied)); + Assert.HasCount(leaders.Count, Fingerprint.Of(bed.Usb)); + var stem = Path.ChangeExtension(video.RelativePath!, null); + foreach (var k in leaders) + { + Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Count, targets[k].Actual, k, N) + ".png", items[k].RelativePath, $"frame {k}"); + } + + // A follower points at its leader's copy. + for (var k = 0; k < N; k++) + { + Assert.AreEqual(items[leaders.First(l => targets[l].Sample == targets[k].Sample)].CopyId, items[k].CopyId, $"item {k}"); + } + } + + [TestMethod] + public async Task FramesDoNotMakeTheFileCopied() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "992", Make.T0.AddDays(-2)), [ + new TestFile(Make.Video(1) with { Duration = null }, Mp4, ".mp4"), + new TestFile(Make.Video(2) with { Duration = null }, TestVideos.Mov(Stream), ".mov"), + ]); + var (first, second) = (post.Media[0], post.Media[1]); + await bed.GeneralAsync(ct: ct); + + await bed.CopyAsync(Frames(first, new ExportFramesRequest(FrameMode.At, TimeSpan.FromMilliseconds(300), null, null, ExportFormat.Png)), ct); + + Assert.AreEqual(new ExportEntryCopies(2, 0, 1), (await bed.Db.Exports.GetEntryCopyCountsAsync([post.Entry.Id], ct))[post.Entry.Id]); + Assert.AreEqual(ExportMark.FrameOnly, (await bed.Db.Exports.GetEntryMarksAsync([post.Entry.Id], ct))[post.Entry.Id]); + var files = await bed.Db.Exports.GetFileMarksAsync([first.Id, second.Id], ct); + Assert.AreEqual((ExportMark.FrameOnly, ExportMark.None), (files[first.Id], files[second.Id])); + Assert.IsTrue((await EntriesAsync(bed, LibraryCopiesFilter.NotCopied, ct)).Contains(post.Entry.Id), "still «Non ancora copiato»"); + Assert.IsFalse((await EntriesAsync(bed, LibraryCopiesFilter.Copied, ct)).Contains(post.Entry.Id)); + Assert.AreEqual(2, (await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)).NotCopied); + + // The second video copied whole: «Copiato in parte», the first one is still not copied. + await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([second.Id])), ct); + Assert.AreEqual(new ExportEntryCopies(2, 1, 1), (await bed.Db.Exports.GetEntryCopyCountsAsync([post.Entry.Id], ct))[post.Entry.Id]); + Assert.AreEqual(ExportMark.Partly, (await bed.Db.Exports.GetEntryMarksAsync([post.Entry.Id], ct))[post.Entry.Id]); + Assert.AreEqual(1, (await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)).NotCopied); + + // «Copia in…» of the entry copies the first video whole (the frame does not count) and nothing else. + var whole = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct); + Assert.AreEqual((1, 1), (whole.Plan.Files, whole.Plan.AlreadyCopied)); + Assert.AreEqual(ExportMark.Copied, (await bed.Db.Exports.GetEntryMarksAsync([post.Entry.Id], ct))[post.Entry.Id]); + Assert.HasCount(3, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task PhotosAccountsNotExportedAndVideosWithoutFramesAreSkipped() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var mixed = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "993", Make.T0.AddDays(-2)), [ + ExportTestBed.Photo(1, 50), + new TestFile(Make.Video(2) with { Duration = null }, Mp4, ".mp4"), + ]); + var noise = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "994", Make.T0.AddDays(-3)), [TestFile.Video(1, 4000)]); + var luca = await SaveVideoAsync(bed, bed.Luca, "995", TestVideos.Mov(Stream), ".mov"); + await bed.GeneralAsync(ct: ct); + await bed.Service.Destinations.SetAccountEnabledAsync(bed.Luca.Id, false, ct); + + var request = new ExportJobRequest( + new ExportSelection.Entries([mixed.Entry.Id, noise.Entry.Id, luca.Entry.Id]), + Frames: new ExportFramesRequest(FrameMode.At, TimeSpan.Zero, null, null, ExportFormat.Png)); + var start = await bed.CopyAsync(request, ct); + + Assert.AreEqual((1, 1, 2), (start.Plan.PhotosSkipped, start.Plan.NotExported, start.Plan.Videos)); + var items = await bed.ItemsAsync(start.Runs.Single().Id, ct); + Assert.HasCount(2, items, "no item for the photo, nor for the account that is not exported"); + Assert.AreEqual(ExportItemState.Copied, items.Single(i => i.MediaId == mixed.Media[1].Id).State); + var unavailable = items.Single(i => i.MediaId == noise.Media[0].Id); + Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.FrameNotAvailable, (long?)null), (unavailable.State, unavailable.Note, unavailable.CopyId)); + Assert.AreEqual("Fotogramma non disponibile per questo video", ExportText.Note(unavailable.Note)); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(start.Runs.Single().DestinationId, ct: ct), "no copy row for a frame that is not there"); + } + + [TestMethod] + public async Task AFramesJobWaitsForTheEngineSession() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(env => env with { Session = new CountedSession(3) }); + var video = (await SaveVideoAsync(bed, bed.Marta, "996", Mp4, ".mp4")).Media[0]; + await bed.GeneralAsync(ct: ct); + var before = bed.Clock.Now; + + var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, 2, ExportFormat.Png)), ct); + + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs.Single().Id, ct)).State); + Assert.IsGreaterThanOrEqualTo(before + TimeSpan.FromSeconds(10), bed.Clock.Now, "polled while the session ran"); + Assert.HasCount(2, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task ARemovedFrameIsWrittenAgainOnRequest() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var video = (await SaveVideoAsync(bed, bed.Marta, "997", Mp4, ".mp4")).Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + var request = Frames(video, new ExportFramesRequest(FrameMode.At, TimeSpan.FromMilliseconds(400), null, null, ExportFormat.WebpLossless)); + var first = (await bed.ItemsAsync((await bed.CopyAsync(request, ct)).Runs.Single().Id, ct)).Single(); + var path = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(first.RelativePath!)); + var bytes = await File.ReadAllBytesAsync(path, ct); + File.Delete(path); + await bed.Service.CheckCopiesAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(first.CopyId!.Value, ct))!.State); + + // An explicit frames request writes it again (D14), without «Copia di nuovo»: the same bytes, a new row. + var second = (await bed.ItemsAsync((await bed.CopyAsync(request, ct)).Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, first.RelativePath), (second.State, second.RelativePath)); + Assert.AreNotEqual(first.CopyId, second.CopyId); + CollectionAssert.AreEqual(bytes, await File.ReadAllBytesAsync(path, ct), "the same frame gives the same bytes"); + Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(first.CopyId!.Value, ct))!.State); + + // Asked once more while it is there: «Già copiato». + var third = (await bed.ItemsAsync((await bed.CopyAsync(request, ct)).Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, second.CopyId), (third.State, third.CopyId)); + } + + [TestMethod] + public async Task OverTheCapIsRefusedBeforeAnythingIsRecorded() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "998", Make.T0.AddDays(-2)), [ + new TestFile(Make.Video(1) with { Duration = TimeSpan.FromSeconds(200) }, Mp4, ".mp4"), + ])).Media[0]; + await bed.GeneralAsync(ct: ct); + var request = Frames(video, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(100), null, ExportFormat.Png)); + + Assert.AreEqual(1, (await bed.Service.PlanAsync(request, ct)).OverCap); + var refused = await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(request, ct)); + StringAssert.StartsWith(refused.Message, ExportFrames.OverCapMessage); + Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task NInAllOnAVideoShorterThanNMillisecondsNamesEachFrameByItsPosition() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var still = TestVideos.Mp4(Stream.FirstPictureRepeated(18)); // 0,6 s: 1.000 instants cannot all be a millisecond apart + var video = (await SaveVideoAsync(bed, bed.Marta, "993", still, ".mp4")).Media[0]; + await bed.GeneralAsync(ct: ct); + const int N = 1000; + + // The instants are whole milliseconds (the item, the preview and the download locate the same one); the first of + // those on one millisecond is the item, the others are counted as already there. + var instants = ExportFrames.Spread(Duration(still), N); + Assert.IsTrue(instants.All(t => t.Ticks % TimeSpan.TicksPerMillisecond == 0)); + var firsts = instants.Select((t, i) => (Ms: (long)t.TotalMilliseconds, Index: i)).GroupBy(x => x.Ms).Select(g => g.First()).ToList(); + Assert.IsLessThan(N, firsts.Count); + + var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, N, ExportFormat.Png)), ct); + + Assert.AreEqual((firsts.Count, N - firsts.Count), (start.Plan.Frames, start.Plan.AlreadyCopied), "the plan says what is recorded"); + var items = await bed.ItemsAsync(start.Runs.Single().Id, ct); + CollectionAssert.AreEqual(firsts.Select(f => (TimeSpan?)TimeSpan.FromMilliseconds(f.Ms)).ToArray(), items.Select(i => i.FrameAt).ToArray()); + + // Each frame written is named by its position among the N instants, as «Scarica» names it, not by its row. + var targets = Locate(still, [.. firsts.Select(f => TimeSpan.FromMilliseconds(f.Ms))]); + var stem = Path.ChangeExtension(video.RelativePath!, null); + var leaders = targets.Select((t, k) => (t.Sample, k)).GroupBy(x => x.Sample).Select(g => g.First().k).ToList(); + Assert.HasCount(leaders.Count, Fingerprint.Of(bed.Usb)); + foreach (var k in leaders) + { + Assert.AreEqual(ExportItemState.Copied, items[k].State); + Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Count, targets[k].Actual, firsts[k].Index, N) + ".png", items[k].RelativePath, $"frame {k}"); + } + + Assert.AreNotEqual(leaders.Count - 1, firsts[leaders[^1]].Index, "the positions skip the instants on one millisecond"); + } + + [TestMethod] + public async Task VideosOfUnknownLengthCountAgainstTheCapsBeforeAnythingIsRecorded() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await bed.GeneralAsync(ct: ct); + + // One video of 200 s the library has no length for, one every 0,1 s: 2.000 frames, refused before any run. + var long200 = (await SaveVideoAsync(bed, bed.Marta, "980", LongStill(200), ".mp4")).Media[0]; + var every = Frames(long200, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(100), null, ExportFormat.Png)); + var overCap = await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(every, ct)); + StringAssert.StartsWith(overCap.Message, ExportFrames.OverCapMessage); + Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); + + // 21 videos of a second without a length, 1.000 each: 21.000 frames, over the 20.000 of a request. + var still = Stream.FirstPictureRepeated(30); + var ids = new List(); + for (var i = 0; i < 21; i++) + { + ids.Add((await SaveVideoAsync(bed, bed.Marta, $"96{i:D2}", TestVideos.Mp4(still, Make.T0.AddDays(-i)), ".mp4")).Media[0].Id); + } + + var many = new ExportJobRequest(new ExportSelection.Media(ids), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 1000, ExportFormat.Png)); + var tooMany = await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(many, ct)); + StringAssert.StartsWith(tooMany.Message, ExportService.TooManyFramesText); + Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + + Assert.AreEqual(21, (await bed.Service.PlanAsync(many, ct)).Frames, "the dialog does not read the files: «circa» one a video"); + + // Two of them, 3 each: measured when the job is recorded, the plan of the start says what was recorded. + var two = new ExportJobRequest(new ExportSelection.Media(ids.Take(2).ToList()), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 3, ExportFormat.Png)); + var started = await bed.CopyAsync(two, ct); + Assert.AreEqual((2, 6), (started.Plan.Videos, started.Plan.Frames)); + Assert.HasCount(6, await bed.ItemsAsync(started.Runs.Single().Id, ct)); + } + + /// A video of one still picture shown for . + private static byte[] LongStill(int seconds) + { + var es = Stream.FirstPictureRepeated(1); + var bytes = es.LengthPrefixed(0); + var track = new Mp4OutputTrack + { + IsVideo = true, + Timescale = TestVideos.Timescale, + Samples = [new Mp4OutputSample(bytes.Length, 0, 0, true)], + WriteSample = (_, s) => s.Write(bytes), + Width = es.Width, + Height = es.Height, + AvcConfiguration = es.AvcC, + LastSampleDuration = (long)seconds * TestVideos.Timescale, + }; + using var output = new MemoryStream(); + Mp4Writer.Write(output, [track]); + return output.ToArray(); + } + + private static ExportJobRequest Frames(Media video, ExportFramesRequest frames) => new(new ExportSelection.Media([video.Id]), Frames: frames); + + /// A video whose length the library does not know (it is read when the job is recorded). + private static Task SaveVideoAsync(ExportTestBed bed, Account account, string code, byte[] bytes, string extension) => + bed.Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-2)), [new TestFile(Make.Video(1) with { Duration = null }, bytes, extension)]); + + private static TimeSpan Duration(byte[] video) + { + using var stream = new MemoryStream(video); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + return info.Duration; + } + + private static IReadOnlyList Locate(byte[] video, IReadOnlyList instants) + { + using var stream = new MemoryStream(video); + using var reader = VideoFrameReader.Open(stream, out _); + return reader.Locate(instants); + } + + private static async Task> EntriesAsync(ExportTestBed bed, LibraryCopiesFilter filter, CancellationToken ct) => + [.. (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)]; + + /// An engine session for the first looks, then none. + private sealed class CountedSession(int polls) : IEngineSessionState + { + private int _left = polls; + + public bool InSession => Interlocked.Decrement(ref _left) >= 0; + } +} diff --git a/tests/Febe.Tests/Export/ExportPathsTests.cs b/tests/Febe.Tests/Export/ExportPathsTests.cs index af336df..ba30b4c 100644 --- a/tests/Febe.Tests/Export/ExportPathsTests.cs +++ b/tests/Febe.Tests/Export/ExportPathsTests.cs @@ -150,6 +150,53 @@ public sealed class ExportPathsTests Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + numbered.Length); } + [TestMethod] + public void TheTargetExtensionReplacesTheSourceOneAndAFrameSuffixFollowsTheStem() + { + // Tappa E3 (WP1.8): a converted copy takes the extension of its format, a frame adds its suffix before it. + var asJpg = new ExportNameOptions(".jpg", null); + var png = Photo(1) with { RelativePath = "post/2026/vecchio_1.PNG" }; + CollectionAssert.AreEqual( + new[] { "marta.demo", "post", "2026", "2026-10-13_10-00-00_C500_1.jpg" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome, asJpg).ToArray()); + var frame = new ExportNameOptions(".png", "_t0m01s250"); + CollectionAssert.AreEqual( + new[] { "marta.demo", "post", "2026", "2026-10-13_10-00-00_C500_1_t0m01s250.png" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome, frame).ToArray()); + + // A file of «importati/» keeps its name, with the extension swapped too. + var imported = Photo(1) with { RelativePath = "importati/vacanze/IMG 0001.HEIC.mov" }; + CollectionAssert.AreEqual( + new[] { "marta.demo", "importati", "vacanze", "IMG 0001.HEIC.mp4" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome, new ExportNameOptions(".mp4", null)).ToArray()); + CollectionAssert.AreEqual( + new[] { "marta.demo", "importati", "vacanze", "IMG 0001.HEIC_f001.png" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome, new ExportNameOptions(".png", "_f001")).ToArray()); + + // No options: nothing changes. + CollectionAssert.AreEqual( + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome).ToArray(), + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), png, null, false, TestZones.Rome, new ExportNameOptions(null, null)).ToArray()); + } + + [TestMethod] + public void TheFrameSuffixSurvivesTheShorteningTo240() + { + var root = Path.Combine(Path.GetTempPath(), new string('r', 120)); + var deep = General() with { RootPath = root }; + var segments = new[] { "marta.demo", new string('a', 60), new string('b', 80) + "_t12m05s340.png" }; + + var fitted = ExportPaths.RelativePathFor(deep, segments, keepSuffix: "_t12m05s340"); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + fitted.Length); + StringAssert.EndsWith(fitted, "_t12m05s340.png"); + + // The numbered names of the safe writer keep it and put the number after it. + var numbered = ExportPaths.NumberedName(root, fitted, 2, keepSuffix: "_t12m05s340"); + StringAssert.EndsWith(numbered, "_t12m05s340 (2).png"); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + numbered.Length); + Assert.AreEqual("marta.demo/x_f001.png", ExportPaths.RelativePathFor(deep, ["marta.demo", "x_f001.png"], keepSuffix: "_f001"), "short paths are not touched"); + } + [TestMethod] public void TheNamingPreviewOfADestinationTakesTheLibrarySchemesWhenNull() { diff --git a/tests/Febe.Tests/Imaging/ImageConversionCheckTests.cs b/tests/Febe.Tests/Imaging/ImageConversionCheckTests.cs new file mode 100644 index 0000000..d0af2db --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageConversionCheckTests.cs @@ -0,0 +1,217 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; +using Febe.Core.Library.Conversion; +using static Febe.Tests.Imaging.TestImages; + +namespace Febe.Tests.Imaging; + +/// +/// What a photo conversion of tappa E3 does with a source, from its bytes only (D5, D6): the same format is a byte copy, +/// HEIF, AVIF and raw files, animations, damaged files, CMYK and deep colour to PNG/WEBP and pictures over the budget +/// of the target are copied as they are, each with its reason. The files are built by the test. +/// +[TestClass] +public sealed class ImageConversionCheckTests +{ + private static readonly ImageFormat[] Targets = [ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.WebP]; + + [TestMethod] + public void SameFormatIsACopy() + { + using var picture = Gradient(24, 16, seed: 1); + foreach (var format in Targets) + { + var file = ImageConverter.Encode(picture, format, null); + var check = ImageConverter.Check(file, format); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyAsIs, format, null), check, $"{format}"); + } + + // A lossy WebP to «WEBP senza perdita» is copied too: re-encoding it would only make it bigger (Q36). + var lossy = ReferenceImages.Get("webp-perdita-alfa-q80").ReadInput(); + Assert.AreEqual(ImageConversionAction.CopyAsIs, ImageConverter.Check(lossy, ImageFormat.WebP).Action); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(lossy, ImageFormat.Png).Action); + } + + [TestMethod] + public void HeifAvifAndRawAreCopiedAsTheyAre() + { + byte[] Ftyp(string brand) => [0, 0, 0, 0x18, .. "ftyp"u8, .. System.Text.Encoding.ASCII.GetBytes(brand), 0, 0, 0, 0, .. "mif1"u8, .. System.Text.Encoding.ASCII.GetBytes(brand), 0, 0, 0, 8, .. "free"u8]; + byte[] tiff = [.. "II*\0"u8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + foreach (var target in Targets) + { + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Heif, ImageConversionLosses.AsIsHeif), ImageConverter.Check(Ftyp("heic"), target)); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Avif, ImageConversionLosses.AsIsAvif), ImageConverter.Check(Ftyp("avif"), target)); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Tiff, ImageConversionLosses.AsIsRaw), ImageConverter.Check(tiff, target)); + } + + // Raw files go by their name in the library (a DNG is a TIFF inside), and the plan predicts them as they are. + Assert.IsTrue(MediaConverter.IsRawExtension(".dng")); + Assert.IsTrue(MediaConverter.IsRawExtension(".CR3")); + Assert.IsFalse(MediaConverter.IsRawExtension(".jpg")); + } + + [TestMethod] + public void AnimatedGifWebpAndPngAreNeverConverted() + { + // GIF with two images. + byte[] palette = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]; + byte[] indices = [0, 1]; + var gif = Gif(2, 1, palette, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2)); + + // PNG with an acTL chunk before its image data (an APNG, by the presence of the chunk). + using var picture = Gradient(8, 8, seed: 2); + var chunks = PngChunks(PngEncoder.Encode(picture)); + var actl = new byte[8]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(actl, 2); + var apng = Png([chunks[0], ("acTL", actl), .. chunks.Skip(1)]); + Assert.IsTrue(ImageDecoder.Identify(apng).IsAnimated); + + // WebP with ANIM and ANMF chunks. + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(picture), "VP8L"); + var webp = WebPTestFiles.Riff( + ("VP8X", WebPTestFiles.Vp8X(0x02 | 0x10, 8, 8)), + ("ANIM", WebPTestFiles.Anim()), + ("ANMF", WebPTestFiles.Anmf(0, 0, 8, 8, 0, ("VP8L", vp8l)))); + + foreach (var (file, source) in new[] { (gif, ImageFormat.Gif), (apng, ImageFormat.Png), (webp, ImageFormat.WebP) }) + { + foreach (var target in Targets.Where(t => t != source)) + { + var check = ImageConverter.Check(file, target); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, source, ImageConversionLosses.AsIsAnimated), check, $"{source} in {target}"); + } + } + + // The same picture without the chunk is converted. + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(PngEncoder.Encode(picture), ImageFormat.WebP).Action); + } + + [TestMethod] + public void CmykAndDeepColorGoToJpgOnly() + { + // An Adobe CMYK JPEG: to PNG and WEBP it is copied as it is; to JPG it is already a JPEG. + 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 = JpegTestEncoder.Write( + 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), + new JpegTestOptions { Jfif = false, AdobeTransform = 0 }); + Assert.AreEqual(ImageConversionLosses.AsIsCmyk, ImageConverter.Check(cmyk, ImageFormat.Png).NoteCode); + Assert.AreEqual(ImageConversionLosses.AsIsCmyk, ImageConverter.Check(cmyk, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.CopyAsIs, ImageConverter.Check(cmyk, ImageFormat.Jpeg).Action); + + // A 16-bit PNG: to WEBP as it is, to JPG converted (JPG loses anyway). + var raw = new byte[2 * (1 + (2 * 6))]; + var deep = Png(("IHDR", Ihdr(2, 2, 16, 2)), ("IDAT", Zlib(raw)), ("IEND", [])); + Assert.AreEqual(ImageConversionLosses.AsIsDeepColor, ImageConverter.Check(deep, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(deep, ImageFormat.Jpeg).Action); + + // A 12-bit JPEG to PNG. + var twelve = JpegTestEncoder.Write(JpegEncoder.TransformPlanes(8, 8, 12, [(1, 1, 1, 0, new int[64])], [fine], 0xC1), new JpegTestOptions()); + Assert.AreEqual(ImageConversionLosses.AsIsDeepColor, ImageConverter.Check(twelve, ImageFormat.Png).NoteCode); + } + + [TestMethod] + public void AnUndecodableImageIsCopiedAsItIs() + { + var unknown = ImageConverter.Check(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, ImageFormat.Png); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, null, ImageConversionLosses.AsIsNotDecodable), unknown); + + // A PNG whose header says 0 × 0: recognised, not decodable. + var broken = Png(("IHDR", Ihdr(0, 0, 8, 2)), ("IEND", [])); + var check = ImageConverter.Check(broken, ImageFormat.Jpeg); + Assert.AreEqual((ImageConversionAction.CopyOriginal, ImageConversionLosses.AsIsNotDecodable), (check.Action, check.NoteCode)); + + // A JPEG cut after its signature. + Assert.AreEqual(ImageConversionLosses.AsIsNotDecodable, ImageConverter.Check(new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0, 16 }, ImageFormat.Png).NoteCode); + } + + [TestMethod] + public async Task AJpegNamedPngIsDetectedByItsBytes() + { + using var picture = Gradient(20, 12, seed: 4); + var jpeg = ImageConverter.Encode(picture, ImageFormat.Jpeg, null); + var sha = Convert.ToHexStringLower(SHA256.HashData(jpeg)); + + using var asJpg = await MediaConverter.PrepareAsync(() => new MemoryStream(jpeg), "post/foto.png", MediaKind.Photo, ExportFormat.Jpg, sha, new ConversionThrottle(), CancellationToken.None); + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original), (asJpg.Variant, asJpg.Format), "a JPEG is already a JPG, whatever its name"); + Assert.IsEmpty(asJpg.Notes); + + using var asPng = await MediaConverter.PrepareAsync(() => new MemoryStream(jpeg), "post/foto.png", MediaKind.Photo, ExportFormat.Png, sha, new ConversionThrottle(), CancellationToken.None); + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png, ".png"), (asPng.Variant, asPng.Format, asPng.Extension), "its name is not a PNG's bytes"); + } + + [TestMethod] + public void PixelBudgetsCopyAsIs() + { + // Only the header is read: the image data is a single empty row, never decoded by the check. + byte[] Header(int w, int h) => Png(("IHDR", Ihdr(w, h, 8, 2)), ("IDAT", Zlib([0])), ("IEND", [])); + + var big = Header(7000, 7000); // 49 MP: over the 40 MP of WEBP, within the 100 MP of PNG and JPG + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(big, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(big, ImageFormat.Jpeg).Action); + + var wide = Header(20_000, 2); // a WebP side is at most 16384 + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(wide, ImageFormat.WebP).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(wide, ImageFormat.Jpeg).Action); + + var huge = Header(11_000, 11_000); // 121 MP: over every budget + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.Jpeg).NoteCode); + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.WebP).NoteCode); + } + + /// A JPEG of only its header (SOI, SOF, SOS, EOI): enough for the check, which never decodes. + private static byte[] JpegHeader(int frameMarker, int width, int height, byte lumaSampling) + { + return + [ + 0xFF, 0xD8, + 0xFF, (byte)frameMarker, 0, 17, 8, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 3, + 1, lumaSampling, 0, 2, 0x11, 1, 3, 0x11, 1, + 0xFF, 0xDA, 0, 12, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 0, 0, + 0xFF, 0xD9, + ]; + } + + [TestMethod] + public async Task AProgressiveJpegTheDecoderWouldRefuseIsTooLargeNotUnreadable() + { + // 8000 × 8000 = 64 MP, within the 100 MP of PNG and JPG. Baseline it needs 3 bytes a pixel besides the picture; + // progressive 4:4:4 keeps its coefficients too, 9 bytes a pixel: 576 MB, over the decoder's 512 MiB. + var baseline = JpegHeader(0xC0, 8000, 8000, 0x11); + var progressive = JpegHeader(0xC2, 8000, 8000, 0x11); + var progressive420 = JpegHeader(0xC2, 8000, 8000, 0x22); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png).Action); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive420, ImageFormat.Png).Action, "4:2:0: 4,5 byte a pixel"); + Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Jpeg, ImageConversionLosses.AsIsTooLarge), + ImageConverter.Check(progressive, ImageFormat.Png)); + Assert.AreEqual(576_000_000L, ImageDecoder.Identify(progressive).DecodeWorkingBytes); + + // The copy and the library conversion say «troppo grande», never «Febe non riesce a leggere l'immagine». + var sha = Convert.ToHexStringLower(SHA256.HashData(progressive)); + using var prepared = await MediaConverter.PrepareAsync(() => new MemoryStream(progressive), "post/grande.jpg", MediaKind.Photo, + ExportFormat.Png, sha, new ConversionThrottle(), CancellationToken.None); + Assert.AreEqual(ExportVariant.Whole, prepared.Variant); + CollectionAssert.AreEqual(new[] { ImageConversionLosses.AsIsTooLarge }, prepared.Notes.ToArray()); + } + + [TestMethod] + public void WhatTheCheckLetsThroughTheDecoderConverts() + { + // A real progressive 4:4:4 JPEG of 64 × 64 under a working budget between the 3 bytes a pixel of a baseline + // decode and the 9 of a progressive one: the check sends it as it is, so the conversion never throws. + using var picture = Gradient(64, 64, seed: 3); + var baseline = ImageConverter.Encode(picture, ImageFormat.Jpeg, null, new ImageConversionOptions { JpegSubsampling = JpegSubsampling.Ratio444 }); + var progressive = JpegTestEncoder.Write(JpegDecoder.DecodeCoefficients(baseline), new JpegTestOptions { Progressive = true }); + var options = new ImageConversionOptions { Limits = new ImageLimits { MaxWorkingBytes = 64 * 64 * 6 } }; + + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png, options).Action); + Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(baseline, ImageFormat.Png, options).Data)); + Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(progressive, ImageFormat.Png, options).NoteCode); + Assert.ThrowsExactly(() => ImageConverter.Convert(progressive, ImageFormat.Png, options)); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive, ImageFormat.Png).Action, "con i limiti di sempre"); + Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(progressive, ImageFormat.Png).Data)); + } +} diff --git a/tests/Febe.Tests/Imaging/ImageConversionTests.cs b/tests/Febe.Tests/Imaging/ImageConversionTests.cs new file mode 100644 index 0000000..c3535ab --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageConversionTests.cs @@ -0,0 +1,137 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; +using static Febe.Tests.Imaging.TestImages; + +namespace Febe.Tests.Imaging; + +/// +/// The photo conversion of tappa E3: what is copied as it is and why (D5, D6), what a conversion reports instead of +/// throwing, and that converting the same picture twice gives the same bytes (D9). +/// +[TestClass] +public sealed class ImageConversionTests +{ + private static readonly byte[] Palette4 = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]; + + [TestMethod] + [DataRow(ImageFormat.Jpeg)] + [DataRow(ImageFormat.Png)] + [DataRow(ImageFormat.WebP)] + public void ConvertingTwiceGivesTheSameBytes(ImageFormat target) + { + using var picture = Gradient(97, 61, seed: 7); + var source = ImageConverter.Encode(picture, target == ImageFormat.Png ? ImageFormat.Jpeg : ImageFormat.Png, null); + + var first = ImageConverter.Convert(source, target); + var second = ImageConverter.Convert(source, target); + + Assert.AreEqual(target, ImageFormatSniffer.Detect(first.Data)); + CollectionAssert.AreEqual(SHA256.HashData(first.Data), SHA256.HashData(second.Data)); + Assert.AreEqual(target == ImageFormat.Jpeg, first.Lossy); + } + + [TestMethod] + public void WebpCostsUseNoFloatingPointLog() + { + // The fixed-point log2 of the VP8L cost estimates is exact on powers of two and monotonic. + var previous = -1L; + for (ulong v = 1; v < 70_000; v += 13) + { + var log = Vp8LEncoder.Log2Fixed(v); + Assert.IsGreaterThanOrEqualTo(previous, log); + previous = log; + } + + Assert.AreEqual(10L << 16, Vp8LEncoder.Log2Fixed(1024)); + Assert.AreEqual(20L << 16, Vp8LEncoder.Log2Fixed(1UL << 20)); + Assert.AreEqual(0L, Vp8LEncoder.Log2Fixed(1)); + } + + [TestMethod] + public void TheSameFormatIsCopiedAsItIs() + { + using var picture = Gradient(16, 16, seed: 3); + var png = ImageConverter.Encode(picture, ImageFormat.Png, null); + + var check = ImageConverter.Check(png, ImageFormat.Png); + + Assert.AreEqual(ImageConversionAction.CopyAsIs, check.Action); + Assert.IsNull(check.NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(png, ImageFormat.Jpeg).Action); + } + + [TestMethod] + public void AnimationsAndDamagedFilesAreCopiedWithTheirReason() + { + byte[] indices = [0, 1]; + var animated = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2)); + var still = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2)); + + Assert.AreEqual(ImageConversionLosses.AsIsAnimated, ImageConverter.Check(animated, ImageFormat.Png).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(still, ImageFormat.Png).Action); + var damaged = ImageConverter.Check(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, ImageFormat.Jpeg); + Assert.AreEqual(ImageConversionAction.CopyOriginal, damaged.Action); + Assert.AreEqual(ImageConversionLosses.AsIsNotDecodable, damaged.NoteCode); + } + + [TestMethod] + public void TransparencyToJpgIsAnnouncedAndTheImageIsLeftAlone() + { + using var picture = Random(8, 8, seed: 11); + var before = picture.ToArray(); + var png = ImageConverter.Encode(picture, ImageFormat.Png, null); + + var result = ImageConverter.Convert(png, ImageFormat.Jpeg); + _ = ImageConverter.Encode(picture, ImageFormat.Jpeg, null); + + CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.TransparencyWhite); + CollectionAssert.AreEqual(before, picture.ToArray(), "Encode lavora su una copia."); + } + + [TestMethod] + [DataRow(true)] + [DataRow(false)] + public void AnExifTooLargeForJpgStillKeepsTheOrientation(bool littleEndian) + { + // 70 000 bytes of TIFF (a big maker note, say) with Orientation 6: more than one APP1 segment holds. The block is + // left behind, but the pixels are never turned (§4.10): without the tag the JPG would show turned. + var exif = new byte[70_000]; + var tiff = exif.AsSpan(); + tiff[0] = tiff[1] = littleEndian ? (byte)'I' : (byte)'M'; + void W16(int at, ushort v) + { + if (littleEndian) + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(exif.AsSpan(at), v); + } + else + { + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian(exif.AsSpan(at), v); + } + } + + W16(2, 42); + W16(littleEndian ? 4 : 6, 8); // first IFD at 8 + W16(8, 1); + W16(10, 0x0112); + W16(12, 3); + W16(littleEndian ? 14 : 16, 1); + W16(18, 6); + using var picture = Gradient(4, 4, seed: 5); + var png = ImageConverter.Encode(picture, ImageFormat.Png, new ImageMetadata { Exif = exif, Orientation = 6 }); + Assert.AreEqual(6, ImageDecoder.Identify(png).Metadata.Orientation); + + var result = ImageConverter.Convert(png, ImageFormat.Jpeg); + + CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.LostExifTooLarge); + var written = ImageDecoder.Identify(result.Data).Metadata; + Assert.AreEqual(6, written.Orientation); + Assert.AreEqual(6, result.Metadata.Orientation); + Assert.AreEqual(26, written.Exif!.Length); + Assert.AreEqual(littleEndian ? (byte)'I' : (byte)'M', written.Exif[0], "l'ordine dei byte della sorgente"); + + // Orientation 1 needs no block at all. + var upright = ImageConverter.Encode(picture, ImageFormat.Png, new ImageMetadata { Exif = exif.AsSpan(0, 8).ToArray().Concat(new byte[70_000]).ToArray(), Orientation = 1 }); + Assert.IsNull(ImageDecoder.Identify(ImageConverter.Convert(upright, ImageFormat.Jpeg).Data).Metadata.Exif); + } +} diff --git a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs index 17ec59b..630cf8b 100644 --- a/tests/Febe.Tests/Imaging/ImageProcessingTests.cs +++ b/tests/Febe.Tests/Imaging/ImageProcessingTests.cs @@ -452,6 +452,128 @@ public sealed class ImageProcessingTests Assert.ThrowsExactly(() => ImageConverter.Convert(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, ImageFormat.Png)); } + // ---- Conversions of tappa E3 ---- + + [TestMethod] + public void PngWithTransparencyToJpgIsWhite() + { + using var clear = Flat(16, 16, 10, 200, 30, 0); + var png = PngEncoder.Encode(clear); + + var result = ImageConverter.Convert(png, ImageFormat.Jpeg); + + CollectionAssert.AreEqual(new[] { ImageConversionLosses.TransparencyWhite }, result.Losses.ToArray()); + using var back = ImageDecoder.Decode(result.Data); + AssertEveryPixel(back, (255, 255, 255, 255), 2, "trasparente diventa bianco"); + } + + [TestMethod] + public void WebpLosslessHasTheSamePixelsAndPngToWebpAndBackIsIdentical() + { + using var picture = TestImages.Random(37, 23, 71); // random alpha: some 0, some 255, the colour under it too + var png = PngEncoder.Encode(picture); + + var webp = ImageConverter.Convert(png, ImageFormat.WebP); + Assert.IsFalse(webp.Lossy); + Assert.IsEmpty(webp.Losses); + using var fromWebp = ImageDecoder.Decode(webp.Data); + CollectionAssert.AreEqual(picture.ToArray(), fromWebp.ToArray(), "ogni pixel identico"); + + var again = ImageConverter.Convert(webp.Data, ImageFormat.Png); + using var fromPng = ImageDecoder.Decode(again.Data); + CollectionAssert.AreEqual(picture.ToArray(), fromPng.ToArray(), "PNG → WEBP → PNG"); + } + + [TestMethod] + public void MetadataIsCarriedIntoTheRightChunksOfEachFormat() + { + using var scene = Scenes.Scene(11, 64, 40); + var exif = Tiff(orientation: 8); + var icc = Profile(500); + const string xmp = ""; + var jpeg = JpegEncoder.Encode(scene, new JpegEncoderOptions { Quality = 90, Exif = exif, IccProfile = icc, Xmp = xmp }); + + // PNG: eXIf, iCCP and an iTXt «XML:com.adobe.xmp», all before the image data. + var png = ImageConverter.Convert(jpeg, ImageFormat.Png).Data; + var chunks = TestImages.PngChunks(png); + var idat = chunks.FindIndex(c => c.Type == "IDAT"); + CollectionAssert.AreEqual(exif, chunks.Single(c => c.Type == "eXIf").Payload); + Assert.IsLessThan(idat, chunks.FindIndex(c => c.Type == "eXIf")); + Assert.IsLessThan(idat, chunks.FindIndex(c => c.Type == "iCCP")); + var itxt = chunks.Single(c => c.Type == "iTXt").Payload; + StringAssert.StartsWith(Encoding.Latin1.GetString(itxt), "XML:com.adobe.xmp\0"); + StringAssert.EndsWith(Encoding.UTF8.GetString(itxt), xmp); + + // WEBP: VP8X first with its flags, ICCP before the image, EXIF and XMP after it. + var webp = ImageConverter.Convert(jpeg, ImageFormat.WebP).Data; + var riff = WebPTestFiles.Chunks(webp); + CollectionAssert.AreEqual(new[] { "VP8X", "ICCP", "VP8L", "EXIF", "XMP " }, riff.Select(c => c.Type).ToArray()); + Assert.AreEqual(0x20 | 0x08 | 0x04, riff[0].Payload[0] & 0x2C, "flag di ICC, EXIF e XMP"); + CollectionAssert.AreEqual(icc, riff[1].Payload); + CollectionAssert.AreEqual(exif, riff[3].Payload); + Assert.AreEqual(xmp, Encoding.UTF8.GetString(riff[4].Payload)); + + // JPG from the PNG: APP1 «Exif», APP2 «ICC_PROFILE» and APP1 of the XMP namespace. + var back = ImageConverter.Convert(png, ImageFormat.Jpeg).Data; + var segments = JpegSegments(back); + var app1 = segments.Where(s => s.Marker == 0xE1).Select(s => s.Payload).ToList(); + Assert.IsTrue(app1.Any(p => p.AsSpan().StartsWith("Exif\0\0"u8) && p.AsSpan(6).SequenceEqual(exif)), "EXIF in APP1"); + Assert.IsTrue(app1.Any(p => p.AsSpan().StartsWith("http://ns.adobe.com/xap/1.0/\0"u8) && Encoding.UTF8.GetString(p.AsSpan(29)) == xmp), "XMP in APP1"); + var app2 = segments.Single(s => s.Marker == 0xE2).Payload; + Assert.IsTrue(app2.AsSpan().StartsWith("ICC_PROFILE\0"u8)); + CollectionAssert.AreEqual(icc, app2[14..]); + } + + [TestMethod] + public void WhatCannotBeCarriedBecomesANote() + { + // A grey JPEG with a grey profile, to every target: the RGB output cannot carry the profile. + using var scene = Scenes.Scene(12, 32, 24); + var grey = JpegEncoder.Encode(scene, new JpegEncoderOptions { Grayscale = true, IccProfile = Profile(300, "GRAY") }); + foreach (var target in new[] { ImageFormat.Png, ImageFormat.WebP, ImageFormat.Jpeg }) + { + CollectionAssert.AreEqual(new[] { ImageConversionLosses.LostIcc }, ImageConverter.Convert(grey, target).Losses.ToArray(), $"grigio in {target}"); + } + + // A CMYK JPEG with its profile, to JPG: converted (it is a JPEG, so only an explicit conversion), profile left behind. + 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 = WithIcc(JpegTestEncoder.Write( + 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), + new JpegTestOptions { Jfif = false, AdobeTransform = 0 }), Profile(400, "CMYK")); + CollectionAssert.AreEqual(new[] { ImageConversionLosses.LostIcc }, ImageConverter.Convert(cmyk, ImageFormat.Jpeg).Losses.ToArray()); + + // A PNG with texts and colour chunks, to WEBP: no texts in WebP, the colour chunks are not written. + using var picture = TestImages.Random(6, 5, 3, opaque: true); + var gamma = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(gamma, 45455); + var parts = TestImages.PngChunks(PngEncoder.Encode(picture, new PngEncoderOptions { Texts = [new ImageText("Title", "Lago")] })); + var png = TestImages.Png([parts[0], ("gAMA", gamma), .. parts.Skip(1)]); + var webp = ImageConverter.Convert(png, ImageFormat.WebP); + CollectionAssert.AreEqual(new[] { ImageConversionLosses.LostTexts, ImageConversionLosses.LostColorChunks }, webp.Losses.ToArray(), "in un ordine fisso"); + Assert.HasCount(2, webp.NotCarried); + } + + [TestMethod] + public void ADamagedExifIsDroppedNotThrown() + { + // A WebP keeps whatever its EXIF chunk holds (PNG and JPEG readers already skip a block that is not TIFF). + using var picture = TestImages.Random(6, 5, 4, opaque: true); + var vp8l = WebPTestFiles.Payload(WebPEncoder.Encode(picture), "VP8L"); + var webp = WebPTestFiles.Riff(("VP8X", WebPTestFiles.Vp8X(0x08, 6, 5)), ("VP8L", vp8l), ("EXIF", [1, 2, 3, 4, 5, 6, 7, 8, 9])); + Assert.IsNotNull(ImageDecoder.Identify(webp).Metadata.Exif); + + foreach (var target in new[] { ImageFormat.Jpeg, ImageFormat.Png }) + { + var result = ImageConverter.Convert(webp, target); + Assert.Contains(ImageConversionLosses.LostExifUnreadable, result.Losses, $"{target}"); + Assert.IsNull(result.Metadata.Exif, $"{target}"); + Assert.IsNull(ImageDecoder.Identify(result.Data).Metadata.Exif, $"{target}: il file scritto non ha l'EXIF"); + } + } + // ---- PNG texts ---- [TestMethod] @@ -674,6 +796,21 @@ public sealed class ImageProcessingTests return bytes; } + /// The marker segments of a JPEG up to its first scan: marker (second byte) and payload. + private static List<(int Marker, byte[] Payload)> JpegSegments(byte[] jpeg) + { + var segments = new List<(int, byte[])>(); + var pos = 2; + while (pos + 4 <= jpeg.Length && jpeg[pos] == 0xFF && jpeg[pos + 1] != 0xDA) + { + var length = BinaryPrimitives.ReadUInt16BigEndian(jpeg.AsSpan(pos + 2)); + segments.Add((jpeg[pos + 1], jpeg.AsSpan(pos + 4, length - 2).ToArray())); + pos += 2 + length; + } + + return segments; + } + /// A JPEG with an APP2 ICC_PROFILE segment (one chunk) right after SOI. private static byte[] WithIcc(byte[] jpeg, byte[] profile) { diff --git a/tests/Febe.Tests/Library/LibraryConversionTests.cs b/tests/Febe.Tests/Library/LibraryConversionTests.cs new file mode 100644 index 0000000..6ff6d18 --- /dev/null +++ b/tests/Febe.Tests/Library/LibraryConversionTests.cs @@ -0,0 +1,882 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Alerts; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Core.Storage; +using Febe.Tests.Alerts.Support; +using Febe.Tests.Export.Support; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +/// +/// The conversion for the library (tappa E3, WP2): the queue, the worker and the hooks that keep the +/// media_conversion rows true. The images are built by the tests. +/// +[TestClass] +public sealed class LibraryConversionTests +{ + private static readonly byte[] JpegSignature = [0xFF, 0xD8, 0xFF]; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheConvertedFileIsAddedAndTheOriginalStays() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 11); + var media = entry.Media[0]; + var original = library.Layout.FullPath(account, media.RelativePath!); + var before = await File.ReadAllBytesAsync(original, ct); + var journalBefore = await File.ReadAllTextAsync(AccountJournal.PathFor(library.Layout.AccountFolder(account)), ct); + + var queued = await library.Db.Conversions.ListPendingAsync(ct: ct); + Assert.HasCount(1, queued, "a new file enters the queue after its journal line"); + var pass = await Worker(library).RunOnceAsync(ct); + Assert.AreEqual(1, pass.Converted); + + var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Converted, ExportFormat.Jpg, media.Sha256), (row.State, row.Format, row.SourceSha256)); + Assert.AreEqual(Path.ChangeExtension(media.RelativePath!, ".jpg"), row.RelativePath); + var converted = await File.ReadAllBytesAsync(library.Layout.FullPath(account, row.RelativePath!), ct); + CollectionAssert.AreEqual(JpegSignature, converted[..3]); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(converted)), row.Sha256); + Assert.AreEqual(converted.Length, row.Bytes); + + // The original, its record and its journal line are untouched. + CollectionAssert.AreEqual(before, await File.ReadAllBytesAsync(original, ct)); + var stored = (await library.Db.Media.GetAsync(media.Id, ct))!; + Assert.AreEqual((media.Sha256, media.RelativePath, media.PerceptualHash, media.HasThumbnail), (stored.Sha256, stored.RelativePath, stored.PerceptualHash, stored.HasThumbnail)); + Assert.AreEqual(journalBefore, await File.ReadAllTextAsync(AccountJournal.PathFor(library.Layout.AccountFolder(account)), ct)); + + var status = await Worker(library).StatusAsync(ct); + Assert.AreEqual((0, 1, 0, 0, false), (status.Pending, status.Converted, status.Failed, status.AsIs, status.Paused)); + } + + [TestMethod] + public async Task OnlyNewFilesByDefaultAndExistingOnesWhenAsked() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await SavePngAsync(library, "1", 12); + var (_, jpg) = await SaveAsync(library, "2", new TestFile(Make.Photo(1), TestFile.PhotoBytes(13, 64, 48), ".jpg")); + await SaveAsync(library, "3", new TestFile(Make.Photo(1), [1, 2, 3, 4], ".heic")); + + var settings = await TurnOnAsync(library, ExportFormat.Jpg); + Assert.IsEmpty(await library.Db.Conversions.ListPendingAsync(ct: ct), "turning it on queues nothing by itself"); + + var queue = new LibraryConversionQueue(library.Db, library.Clock); + var preview = await queue.PreviewExistingAsync(settings, ct); + Assert.AreEqual(1, preview.Files, "only the PNG: a JPG is already in the format, a HEIC is never converted"); + Assert.IsGreaterThan(0L, preview.Bytes); + Assert.AreEqual(1, await queue.EnqueueExistingAsync(settings, ct)); + Assert.AreEqual(0, await queue.EnqueueExistingAsync(settings, ct), "nothing is queued twice"); + Assert.AreEqual(0, (await queue.PreviewExistingAsync(settings, ct)).Files); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(jpg.Media[0].Id, ct)); + } + + [TestMethod] + public async Task ALateFileOfAnOldEntryQueuesItselfOnly() + { + var ct = TestContext.CancellationToken; + 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")); + var added = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(1), Make.Photo(2)], ct); + var (first, second) = (added.Stored.Media[0], added.Stored.Media[1]); + await StorePngAsync(library, account, added.Stored.Entry, first, 31); + await library.Ingest.AppendJournalAsync(added.Stored.Entry.Id, ct); + + // Photos to JPG with «Solo i nuovi»: the PNG already in the library is left alone... + library.Clock.Now += TimeSpan.FromMinutes(5); + var settings = await TurnOnAsync(library, ExportFormat.Jpg); + await new LibraryConversionQueue(library.Db, library.Clock).OnSettingsChangedAsync(ExportSettings.Default, settings, ct); + + // ...also when the second file of its series arrives later: only that one is new. + library.Clock.Now += TimeSpan.FromMinutes(5); + await StorePngAsync(library, account, added.Stored.Entry, second, 32); + await library.Ingest.AppendJournalAsync(added.Stored.Entry.Id, ct); + + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(first.Id, ct), "the old file had its answer"); + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(second.Id, ct)).Single().State); + + // «Anche i N» still counts the old one. + Assert.AreEqual(1, (await new LibraryConversionQueue(library.Db, library.Clock).PreviewExistingAsync(settings, ct)).Files); + } + + [TestMethod] + public async Task TurningOffDropsThePendingRowsAndKeepsTheConvertedOnes() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var on = await TurnOnAsync(library, ExportFormat.Jpg); + var (account, first) = await SavePngAsync(library, "1", 14); + await Worker(library).RunOnceAsync(ct); + await SavePngAsync(library, "2", 15); + Assert.HasCount(1, await library.Db.Conversions.ListPendingAsync(ct: ct)); + + var off = on with { LibraryPhotoFormat = ExportFormat.Original }; + await off.SaveAsync(library.Db.Settings, ct); + await new LibraryConversionQueue(library.Db, library.Clock).OnSettingsChangedAsync(on, off, ct); + + Assert.IsEmpty(await library.Db.Conversions.ListPendingAsync(ct: ct)); + var kept = (await library.Db.Conversions.ListByMediaAsync(first.Media[0].Id, ct)).Single(); + Assert.AreEqual(MediaConversionState.Converted, kept.State); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, kept.RelativePath!)), "the converted file stays"); + } + + [TestMethod] + public async Task AFileAlreadyInTheFormatByItsBytesDropsTheRow() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SaveAsync(library, "1", new TestFile(Make.Photo(1), TestFile.PhotoBytes(16, 64, 48), ".png")); + Assert.HasCount(1, await library.Db.Conversions.ListPendingAsync(ct: ct), "by its name it converts"); + + var pass = await Worker(library).RunOnceAsync(ct); + + Assert.AreEqual((0, 1), (pass.Converted, pass.Done)); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct), "a JPEG named .png is already a JPG: nothing to add"); + Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.*", SearchOption.AllDirectories).Where(f => !f.EndsWith(AccountJournal.FileName, StringComparison.Ordinal))); + } + + [TestMethod] + public async Task AnUndecodableImageIsTerminalAndNotRetried() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (_, entry) = await SaveAsync(library, "1", new TestFile(Make.Photo(1), [.. Enumerable.Range(0, 400).Select(i => (byte)(i * 7))], ".bmp")); + + await Worker(library).RunOnceAsync(ct); + + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Failed, "AsIsNotDecodable"), (row.State, row.LastError)); + Assert.StartsWith("Non si converte", LibraryConversionText.Note(row.LastError)!); + Assert.AreEqual(0, await new LibraryConversionQueue(library.Db, library.Clock).RetryFailedAsync(ct), "«Riprova» skips what never converts"); + var counts = await library.Db.Conversions.CountByStateAsync(ct); + Assert.AreEqual((0, 1), (counts.Failed, counts.AsIs)); + } + + [TestMethod] + public async Task AMissingOriginalSaysSoAndIsRetriedOnRequest() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 17); + var path = library.Layout.FullPath(account, entry.Media[0].RelativePath!); + var bytes = await File.ReadAllBytesAsync(path, ct); + File.Delete(path); + + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Failed, LibraryConversionText.SourceMissing), (row.State, row.LastError)); + Assert.AreEqual("File non presente in libreria", LibraryConversionText.Note(row.LastError)); + + await File.WriteAllBytesAsync(path, bytes, ct); + Assert.AreEqual(1, await new LibraryConversionQueue(library.Db, library.Clock).RetryFailedAsync(ct)); + Assert.AreEqual(1, (await Worker(library).RunOnceAsync(ct)).Converted); + } + + [TestMethod] + public async Task ATakenNameGetsAFreeOneAndAFileFoundAgainIsAdopted() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 18); + var media = entry.Media[0]; + var taken = library.Layout.FullPath(account, Path.ChangeExtension(media.RelativePath!, ".jpg")); + await File.WriteAllBytesAsync(taken, [9, 9, 9], ct); + + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(); + Assert.EndsWith(" (2).jpg", row.RelativePath!, "never overwritten"); + CollectionAssert.AreEqual(new byte[] { 9, 9, 9 }, await File.ReadAllBytesAsync(taken, ct)); + + // The record is lost (a «Tolto» row is history): queued again, the file on disk with its SHA-256 is adopted. + await library.Db.Conversions.MarkRemovedAsync([row.Id], library.Clock.Now, ct); + await library.Db.Conversions.EnqueueAsync([new(media.Id, ExportFormat.Jpg, media.Sha256!)], library.Clock.Now, ct); + await Worker(library).RunOnceAsync(ct); + var again = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(r => r.State == MediaConversionState.Converted); + Assert.AreEqual((row.RelativePath, row.Sha256), (again.RelativePath, again.Sha256)); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, Path.ChangeExtension(media.RelativePath!, null) + " (3).jpg"))); + } + + [TestMethod] + public async Task AnImportPreemptsTheConversion() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 19); + var gate = new LongWorkGate(); + var throttle = new ConversionThrottle(); + + // The photo waits for the throttle (another conversion): meanwhile an import takes the gate. + var busy = new TaskCompletionSource(); + var release = new TaskCompletionSource(); + var other = throttle.RunAsync(_ => + { + busy.SetResult(); + release.Task.Wait(ct); + return 0; + }, ct); + await busy.Task; + var pass = Worker(library, gate, throttle).RunOnceAsync(ct); + while (!gate.BackgroundRunning) + { + await Task.Yield(); + } + + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _), "the import starts at once"); + release.SetResult(); + await other; + var result = await pass; + + Assert.IsTrue(result.Again); + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); + Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories)); + Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), SafeFileWriter.TempPrefix + "*", SearchOption.AllDirectories)); + + Assert.IsTrue((await Worker(library, gate, throttle).RunOnceAsync(ct)).Again, "no conversion while the import runs"); + import.Dispose(); + Assert.AreEqual(1, (await Worker(library, gate, throttle).RunOnceAsync(ct)).Converted, "it resumes after"); + } + + [TestMethod] + public async Task ADeletionDuringTheWriteLeavesNothingUnrecorded() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 20); + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + var worker = new LibraryConversionWorker(Environment(library) with + { + AfterWrite = async (_, _) => await deletion.DeleteAsync(entry.Entry.Id), + }); + + var pass = await worker.RunOnceAsync(ct); + + Assert.AreEqual(0, pass.Converted); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)); + Assert.IsEmpty(Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories), "our own file went"); + } + + [TestMethod] + public async Task NoConversionDuringAnEngineSessionNorWhenPausedOrLowOnSpace() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 21); + var session = new FakeSessionState { InSession = true }; + var space = new FakeFreeSpaceProbe(); + var worker = new LibraryConversionWorker(Environment(library) with { Session = session, FreeSpace = space }); + + Assert.IsTrue((await worker.RunOnceAsync(ct)).Again); + Assert.AreEqual(LibraryConversionText.InSession, (await worker.StatusAsync(ct)).Waiting); + session.InSession = false; + + var queue = new LibraryConversionQueue(library.Db, library.Clock); + await queue.SetPausedAsync(true, ct); + Assert.AreEqual(0, (await worker.RunOnceAsync(ct)).Done); + Assert.IsTrue((await worker.StatusAsync(ct)).Paused); + await queue.SetPausedAsync(false, ct); + + space.Set(library.Layout.AccountFolder(account), 1024, 2 * FakeFreeSpaceProbe.GB); + Assert.AreEqual(0, (await worker.RunOnceAsync(ct)).Done); + Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting); + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); + } + + [TestMethod] + public async Task ALowDiskPausesBeforeTheOriginalIsReadAgain() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 23); + var space = new FakeFreeSpaceProbe(); + space.Set(library.Layout.AccountFolder(account), 1024, 2 * FakeFreeSpaceProbe.GB); + var throttle = new ConversionThrottle(); + var worker = new LibraryConversionWorker(Environment(library, throttle: throttle) with { FreeSpace = space }); + + // Another conversion holds the throttle: a pass that decoded the photo again would wait for it. + using var release = new ManualResetEventSlim(); + var other = throttle.RunAsync(_ => release.Wait(TimeSpan.FromMinutes(1)), ct); + try + { + for (var wakeUp = 0; wakeUp < 3; wakeUp++) + { + var pass = await worker.RunOnceAsync(ct).WaitAsync(TimeSpan.FromSeconds(30), ct); + Assert.AreEqual((0, false), (pass.Done, pass.Again)); + Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting); + } + } + finally + { + release.Set(); + await other; + } + + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); + space.Set(library.Layout.AccountFolder(account), 50 * FakeFreeSpaceProbe.GB, 100 * FakeFreeSpaceProbe.GB); + Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "space again: it converts"); + } + + [TestMethod] + public async Task AFileThatWouldTakeTheDiskBelowTheThresholdIsNotReadAgainAtEveryWakeUp() + { + // Free space above the threshold, but not by the converted file's length: the first pass reads the original and + // pauses; the next ones pause before reading it again, until the disk has room for that file too. + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 25); + var folder = library.Layout.AccountFolder(account); + const long Threshold = 10 * FakeFreeSpaceProbe.GB; + var space = new FakeFreeSpaceProbe(); + space.Set(folder, Threshold + 1, 1000 * FakeFreeSpaceProbe.GB); + var throttle = new ConversionThrottle(); + var worker = new LibraryConversionWorker(Environment(library, throttle: throttle) with + { + FreeSpace = space, + Thresholds = new DiskThresholds(Threshold, 0), + }); + + var first = await worker.RunOnceAsync(ct); + Assert.AreEqual((0, false), (first.Done, first.Again)); + Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting, "the converted file does not fit"); + + // Another conversion holds the throttle: a pass that decoded the photo again would wait for it. + using var release = new ManualResetEventSlim(); + var other = throttle.RunAsync(_ => release.Wait(TimeSpan.FromMinutes(1)), ct); + try + { + for (var wakeUp = 0; wakeUp < 3; wakeUp++) + { + space.Set(folder, Threshold + 1 + wakeUp, 1000 * FakeFreeSpaceProbe.GB); // a little more, never enough + var pass = await worker.RunOnceAsync(ct).WaitAsync(TimeSpan.FromSeconds(30), ct); + Assert.AreEqual((0, false), (pass.Done, pass.Again)); + Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting); + } + } + finally + { + release.Set(); + await other; + } + + Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); + space.Set(folder, Threshold + FakeFreeSpaceProbe.GB, 1000 * FakeFreeSpaceProbe.GB); + Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "room for the file: it converts"); + } + + [TestMethod] + public async Task AFormatTurnedOffOrChangedIsNeitherRetriedNorConverted() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var jpg = await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 24); + var media = entry.Media[0]; + var path = library.Layout.FullPath(account, media.RelativePath!); + var bytes = await File.ReadAllBytesAsync(path, ct); + File.Delete(path); + await Worker(library).RunOnceAsync(ct); + Assert.AreEqual(MediaConversionState.Failed, (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single().State); + await File.WriteAllBytesAsync(path, bytes, ct); + var queue = new LibraryConversionQueue(library.Db, library.Clock); + + // Photos to PNG without the queue told (another way in): «Riprova» puts back only the formats set now. + var png = jpg with { LibraryPhotoFormat = ExportFormat.Png }; + await png.SaveAsync(library.Db.Settings, ct); + Assert.AreEqual(0, await queue.RetryFailedAsync(ct)); + + // Told: the failures of the format changed go with its queue, they are neither counted nor retried. + await queue.OnSettingsChangedAsync(jpg, png, ct); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct)); + Assert.AreEqual(0, (await library.Db.Conversions.CountByStateAsync(ct)).Failed); + + // A row left in the old format (put back by a supersession, say) is dropped by the worker, never written. + await library.Db.Conversions.EnqueueAsync([new Febe.Core.Storage.MediaConversionRequest(media.Id, ExportFormat.Jpg, media.Sha256!)], library.Clock.Now, ct); + var pass = await Worker(library).RunOnceAsync(ct); + Assert.AreEqual(0, pass.Converted); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct)); + Assert.IsFalse(File.Exists(Path.ChangeExtension(path, ".jpg")), "no JPG while the photos are set to PNG"); + + // Turned off altogether: the same. + var off = png with { LibraryPhotoFormat = ExportFormat.Original }; + await off.SaveAsync(library.Db.Settings, ct); + await library.Db.Conversions.EnqueueAsync([new Febe.Core.Storage.MediaConversionRequest(media.Id, ExportFormat.Png, media.Sha256!)], library.Clock.Now, ct); + Assert.AreEqual(0, (await Worker(library).RunOnceAsync(ct)).Converted); + Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct)); + Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.*", SearchOption.AllDirectories).Where(f => !f.EndsWith(AccountJournal.FileName, StringComparison.Ordinal)), "only the original"); + } + + [TestMethod] + public async Task AChangeOfFormatIsStoredWithItsDalKeyAndQueueWholeOrNotAtAll() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var jpg = await TurnOnAsync(library, ExportFormat.Jpg); + var (account, failed) = await SavePngAsync(library, "1", 26); + File.Delete(library.Layout.FullPath(account, failed.Media[0].RelativePath!)); + await Worker(library).RunOnceAsync(ct); + await SavePngAsync(library, "2", 27); + Assert.AreEqual((1, 1), ((await library.Db.Conversions.CountByStateAsync(ct)).Pending, (await library.Db.Conversions.CountByStateAsync(ct)).Failed)); + var png = jpg with { LibraryPhotoFormat = ExportFormat.Png }; + + // A request aborted before its write stores nothing of the change. + using var aborted = new CancellationTokenSource(); + await aborted.CancelAsync(); + await Assert.ThrowsAsync(() => new LibraryConversionQueue(library.Db, library.Clock).SaveSettingsAsync(jpg, png, aborted.Token)); + Assert.AreEqual(ExportFormat.Jpg, (await ExportSettings.LoadAsync(library.Db.Settings, ct)).LibraryPhotoFormat); + Assert.IsNull(await library.Db.Settings.GetAsync(LibraryConversionQueue.PhotoSinceKey, ct)); + Assert.AreEqual((1, 1), ((await library.Db.Conversions.CountByStateAsync(ct)).Pending, (await library.Db.Conversions.CountByStateAsync(ct)).Failed)); + + // A request aborted once the format is written (the tab closed): the change is already whole, never a format + // without its «dal» key or with the old failures left behind. + using var request = new CancellationTokenSource(); + var storage = new AbortAfterSettingsWrite(library.Db, request); + library.Clock.Now += TimeSpan.FromMinutes(1); + await new LibraryConversionQueue(storage, library.Clock).SaveSettingsAsync(jpg, png, request.Token); + + Assert.AreEqual(0, storage.SettingsWrites, "nothing of the change is written on its own"); + Assert.AreEqual(ExportFormat.Png, (await ExportSettings.LoadAsync(library.Db.Settings, ct)).LibraryPhotoFormat); + Assert.AreEqual(library.Clock.Now.ToUnixTimeMilliseconds().ToString(System.Globalization.CultureInfo.InvariantCulture), await library.Db.Settings.GetAsync(LibraryConversionQueue.PhotoSinceKey, ct)); + var counts = await library.Db.Conversions.CountByStateAsync(ct); + Assert.AreEqual((0, 0), (counts.Pending, counts.Failed), "the queue and the failures of JPG went with it"); + Assert.AreEqual(0, await new LibraryConversionQueue(library.Db, library.Clock).RetryFailedAsync(ct)); + } + + [TestMethod] + public async Task AConversionRecordedWhileTheEntryIsDeletedGoesWithIt() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 25); + var media = entry.Media[0]; + var worker = Worker(library); + + // The worker records its conversion while the deletion writes its journal line (the file is still there). + var clock = new HookClock(library.Clock.Now, () => worker.RunOnceAsync(ct)); + var deletion = new LibraryDeletion(library.Db, library.Layout, new AccountJournal(clock), library.Clock); + var result = await deletion.DeleteAsync(entry.Entry.Id, DeletionMode.Remember, ct); + + Assert.AreEqual(1, clock.Pass?.Converted, "converted during the deletion"); + var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(); + Assert.AreEqual(MediaConversionState.Removed, row.State, "the row says the truth"); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, row.RelativePath!)), "the converted file goes with the entry"); + Assert.AreEqual(1, result.ConvertedFiles); + } + + [TestMethod] + public async Task AnUnpluggedAccountFolderIsNotCreated() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 22); + var folder = library.Layout.AccountFolder(account); + Directory.Move(folder, folder + "-staccato"); + + await Worker(library).RunOnceAsync(ct); + + Assert.IsFalse(Directory.Exists(folder)); + Assert.AreEqual(LibraryConversionText.AccountFolderMissing, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().LastError); + } + + [TestMethod] + public async Task DeletionRemembersOrRemovesTheRowsAndTheirFiles() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, kept) = await SavePngAsync(library, "1", 23); + var (_, gone) = await SavePngAsync(library, "2", 24); + await Worker(library).RunOnceAsync(ct); + var keptRow = (await library.Db.Conversions.ListByMediaAsync(kept.Media[0].Id, ct)).Single(); + var goneRow = (await library.Db.Conversions.ListByMediaAsync(gone.Media[0].Id, ct)).Single(); + var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + + var remembered = await deletion.DeleteAsync(kept.Entry.Id, DeletionMode.Remember, ct); + Assert.IsTrue(remembered.Complete); + Assert.AreEqual(1, remembered.ConvertedFiles); + Assert.Contains(keptRow.RelativePath!, remembered.DeletedFiles); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, keptRow.RelativePath!))); + Assert.AreEqual(MediaConversionState.Removed, (await library.Db.Conversions.GetAsync(keptRow.Id, ct))!.State); + + // A strict removal refuses an entry with converted files: their record would be lost. + await Assert.ThrowsExactlyAsync(() => library.Db.Entries.RemoveAsync(gone.Entry.Id, ct)); + var removed = await deletion.DeleteAsync(gone.Entry.Id, DeletionMode.AllowReturn, ct); + Assert.AreEqual(1, removed.ConvertedFiles); + Assert.IsNull(await library.Db.Conversions.GetAsync(goneRow.Id, ct)); + Assert.IsNull(await library.Db.Entries.GetAsync(gone.Entry.Id, ct)); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, goneRow.RelativePath!))); + } + + [TestMethod] + public async Task ADeletionKeepsAReplacedConvertedFile() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 25); + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + var path = library.Layout.FullPath(account, row.RelativePath!); + await File.WriteAllBytesAsync(path, [1, 2, 3], ct); + + var result = await new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock).DeleteAsync(entry.Entry.Id, ct: ct); + + Assert.IsTrue(File.Exists(path)); + Assert.HasCount(1, result.FailedFiles); + Assert.Contains("cambiato dopo la conversione", result.FailedFiles[0]); + } + + [TestMethod] + public async Task AChangedOriginalSupersedesItsConversionAndQueuesTheNewBytes() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 26); + await Worker(library).RunOnceAsync(ct); + var media = entry.Media[0]; + var newSha = new string('a', 64); + await library.Db.Media.UpdateAsync((await library.Db.Media.GetAsync(media.Id, ct))! with { Sha256 = newSha }, ct); + + await ExportSupersession.FileChangedAsync(library.Db, account.Id, media.Sha256, newSha, library.Clock.Now, ct); + + var rows = await library.Db.Conversions.ListByMediaAsync(media.Id, ct); + Assert.AreEqual(MediaConversionState.Superseded, rows[0].State); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, rows[0].RelativePath!)), "the superseded file stays"); + Assert.AreEqual((MediaConversionState.Pending, newSha), (rows[1].State, rows[1].SourceSha256)); + } + + [TestMethod] + public async Task RebuildCountsConvertedFilesWithoutConvertingAndTheWorkerAdoptsThem() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + var (account, entry) = await SavePngAsync(library, "1", 27); + await Worker(library).RunOnceAsync(ct); + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + + await library.LoseDatabaseAsync(); + await TurnOnAsync(library, ExportFormat.Jpg); + var report = await new LibraryRebuilder(library.Db, library.Layout, library.Clock).RebuildAsync(ct: ct); + + Assert.AreEqual((1, 0), (report.ConversionsFound, report.UntrackedFiles), "a converted file is not an unknown file"); + var pending = (await library.Db.Conversions.ListPendingAsync(ct: ct)).Single(); + Assert.AreEqual(ExportFormat.Jpg, pending.Format); + var files = Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories); + Assert.HasCount(1, files, "the rebuild converts nothing"); + + await Worker(library).RunOnceAsync(ct); + var adopted = (await library.Db.Conversions.GetAsync(pending.Id, ct))!; + Assert.AreEqual((MediaConversionState.Converted, row.RelativePath, row.Sha256), (adopted.State, adopted.RelativePath, adopted.Sha256)); + Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task ImportingAConvertedFileSaysItIsInTheLibrary() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await TurnOnAsync(bed.Library, ExportFormat.Png); + var (account, saved) = await bed.AccountWithPhotoAsync("luca.demo", "500", TestFile.PhotoBytes(28, 64, 48)); + await Worker(bed.Library).RunOnceAsync(ct); + var row = (await bed.Library.Db.Conversions.ListByMediaAsync(saved.Media[0].Id, ct)).Single(); + bed.Write("luca.demo/convertita.png", await File.ReadAllBytesAsync(bed.Library.Layout.FullPath(account, row.RelativePath!), ct)); + + var run = await bed.AnalyzeAsync(); + + var file = await bed.FileAsync(run.Id, "luca.demo/convertita.png"); + Assert.AreEqual((ImportOutcome.AlreadyInLibrary, saved.Media[0].Id), (file.Outcome, file.MatchedMediaId)); + Assert.AreEqual("È una copia convertita (o un fotogramma) di un file già in libreria.", file.LastError); + Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original"); + } + + [TestMethod] + public async Task WhatWasNotKeptIsRecordedOnTheConvertedRow() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Jpg); + using var clear = Imaging.TestImages.Gradient(40, 30, seed: 9); // transparent pixels + var (account, entry) = await SaveAsync(library, "1", new TestFile(Make.Photo(1), Core.Codecs.Images.ImageConverter.Encode(clear, Core.Codecs.Images.ImageFormat.Png, null), ".png")); + + Assert.AreEqual(1, (await Worker(library).RunOnceAsync(ct)).Converted); + + var row = (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Converted, ExportText.Notes.TransparencyWhite), (row.State, row.LastError), "the loss codes of a Converted row (D19)"); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, row.RelativePath!))); + Assert.IsFalse(LibraryConversionText.IsAsIs(row.LastError)); + } + + [TestMethod] + public async Task AMovIsRemuxedNextToTheOriginal() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + await (ExportSettings.Default with { LibraryVideoFormat = ExportFormat.Mp4 }).SaveAsync(library.Db.Settings, ct); + var mov = Codecs.Containers.TestVideos.Mov(Codecs.Containers.ElementaryStream.Load("BA1_Sony_D"), new Codecs.Containers.MovOptions(Audio: true, Language: "ita")); + var (account, entry) = await SaveAsync(library, "1", new TestFile(Make.Video(1), mov, ".mov")); + var media = entry.Media[0]; + var original = library.Layout.FullPath(account, media.RelativePath!); + + Assert.AreEqual(1, (await Worker(library).RunOnceAsync(ct)).Converted); + + var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single(); + Assert.AreEqual((MediaConversionState.Converted, ExportFormat.Mp4, media.Sha256), (row.State, row.Format, row.SourceSha256)); + Assert.AreEqual(Path.ChangeExtension(media.RelativePath!, ".mp4"), row.RelativePath); + var mp4 = await File.ReadAllBytesAsync(library.Layout.FullPath(account, row.RelativePath!), ct); + Assert.AreEqual((Convert.ToHexStringLower(SHA256.HashData(mp4)), (long?)mp4.Length), (row.Sha256, row.Bytes)); + using var stream = new MemoryStream(mp4); + var container = Core.Codecs.Containers.ContainerReader.Read(stream, Core.Codecs.Containers.ContainerReader.AnyDate, samples: false)!; + Assert.AreNotEqual("qt ", container.MajorBrand); + Assert.AreEqual("ita", container.Video!.Language); + CollectionAssert.AreEqual(mov, await File.ReadAllBytesAsync(original, ct), "the MOV stays as it is"); + } + + [TestMethod] + public async Task TheDuplicateLoserTakesItsConversions() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("doppioni"); + await using var library = await TestLibrary.CreateAsync(temp); + await TurnOnAsync(library, ExportFormat.Png); + var account = await library.Db.Accounts.AddAsync(Make.Account("doppie.prova"), ct); + var older = await library.SaveAsync(account, Make.Entry(account.Id, "100", Make.T0 - TimeSpan.FromDays(3)), [TestFile.Photo(1, 41, 320, 400)]); + var series = await library.SaveAsync(account, Make.Entry(account.Id, "200", Make.T0 - TimeSpan.FromDays(2)), [TestFile.Photo(1, 41, 240, 300), TestFile.Photo(2, 77, 320, 320)]); + Assert.AreEqual(3, (await Worker(library).RunOnceAsync(ct)).Converted); + var lost = (await library.Db.Conversions.ListByMediaAsync(series.Media[0].Id, ct)).Single(); + var kept = (await library.Db.Conversions.ListByMediaAsync(series.Media[1].Id, ct)).Single(); + + // «Tieni quello in libreria» for the first file of the series: its PNG goes with it, the second file's stays. + var review = new DownloadDuplicateReview(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index); + var pair = (await review.ListAsync(ct: ct)).Single(c => c.Candidate.EntryId == series.Entry.Id); + var result = await review.DecideAsync(pair.Pair.Id, DuplicateDecision.KeepExisting, ct: ct); + + Assert.AreEqual(1, result.FilesRemoved); + Assert.AreEqual(MediaConversionState.Removed, (await library.Db.Conversions.GetAsync(lost.Id, ct))!.State); + Assert.IsFalse(File.Exists(library.Layout.FullPath(account, lost.RelativePath!)), "the converted file of the loser goes"); + Assert.AreEqual(MediaConversionState.Converted, (await library.Db.Conversions.GetAsync(kept.Id, ct))!.State); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, kept.RelativePath!))); + var olderRow = (await library.Db.Conversions.ListByMediaAsync(older.Media[0].Id, ct)).Single(); + Assert.IsTrue(File.Exists(library.Layout.FullPath(account, olderRow.RelativePath!)), "the winner's PNG stays"); + } + + [TestMethod] + public async Task ImportingACopyConvertedForADestinationOrAFrameSaysItIsInTheLibrary() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var (account, saved) = await bed.AccountWithPhotoAsync("luca.demo", "501", TestFile.PhotoBytes(29, 64, 48)); + var media = saved.Media[0]; + + // Two files a destination of Febe got: a PNG copy of the photo and a frame (here any picture: only its SHA counts). + using var picture = TestImages.Scene(29, 64, 48); + var png = TestImages.Png(picture); + using var other = TestImages.Scene(30, 48, 64); + var frame = TestImages.Png(other); + var usb = await bed.Library.Db.Exports.AddDestinationAsync(new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct); + foreach (var (bytes, variant, at, name) in new[] { (png, ExportVariant.Converted, (TimeSpan?)null, "copia.png"), (frame, ExportVariant.Frame, TimeSpan.FromMilliseconds(1250), "fotogramma.png") }) + { + await bed.Library.Db.Exports.AddCopyAsync(new ExportCopy + { + DestinationId = usb.Id, + AccountId = account.Id, + MediaId = media.Id, + SourceSha256 = media.Sha256!, + Variant = variant, + Format = ExportFormat.Png, + FrameAt = at, + State = ExportCopyState.Copied, + RelativePath = "luca.demo/" + name, + Bytes = bytes.Length, + CopySha256 = Convert.ToHexStringLower(SHA256.HashData(bytes)), + CopiedAt = Make.T0, + }, ct); + bed.Write("luca.demo/" + name, bytes); + } + + var run = await bed.AnalyzeAsync(); + + foreach (var name in new[] { "copia.png", "fotogramma.png" }) + { + var file = await bed.FileAsync(run.Id, "luca.demo/" + name); + Assert.AreEqual(ImportOutcome.AlreadyInLibrary, file.Outcome, name); + Assert.AreEqual(Core.Import.ImportText.NoteConvertedCopy, file.LastError, name); + } + + Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original"); + } + + /// A clock that runs work once, the first time it is read (inside the journal append of a deletion). + private sealed class HookClock(DateTimeOffset now, Func> work) : IClock + { + public LibraryConversionPass? Pass { get; private set; } + + public DateTimeOffset Now + { + get + { + if (Pass is null) + { + Pass = Task.Run(work).GetAwaiter().GetResult(); + } + + return now; + } + } + + public TimeZoneInfo LocalZone => TestZones.Rome; + + public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask; + } + + private static LibraryConversionEnvironment Environment(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => new() + { + Storage = library.Db, + Layout = () => library.Layout, + Clock = library.Clock, + Gate = gate, + Throttle = throttle ?? new ConversionThrottle(), + FreeSpace = new FakeFreeSpaceProbe(), + }; + + private static LibraryConversionWorker Worker(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => + new(Environment(library, gate, throttle)); + + /// + /// The storage of a request whose client goes away as soon as a setting is written on its own (outside the + /// transaction of the conversion store): every later write that honours the request's token fails. + /// + private sealed class AbortAfterSettingsWrite(IFebeStorage inner, CancellationTokenSource request) : IFebeStorage, ISettingsStore + { + public int SettingsWrites { get; private set; } + + public IAccountStore Accounts => inner.Accounts; + + public IEntryStore Entries => inner.Entries; + + public IMediaStore Media => inner.Media; + + public IHighlightStore Highlights => inner.Highlights; + + public IDuplicateStore Duplicates => inner.Duplicates; + + public ITaskStore Tasks => inner.Tasks; + + public IActionLogStore ActionLog => inner.ActionLog; + + public ISessionStore Sessions => inner.Sessions; + + public IIncidentStore Incidents => inner.Incidents; + + public IEventStore Events => inner.Events; + + public IFollowingStore Following => inner.Following; + + public IImportStore Imports => inner.Imports; + + public IExportStore Exports => inner.Exports; + + public IVideoAnalysisStore VideoAnalyses => inner.VideoAnalyses; + + public IMediaConversionStore Conversions => inner.Conversions; + + public ISettingsStore Settings => this; + + public IDatabaseMaintenance Maintenance => inner.Maintenance; + + public Task GetAsync(string key, CancellationToken ct = default) => inner.Settings.GetAsync(key, ct); + + public Task> GetAllAsync(CancellationToken ct = default) => inner.Settings.GetAllAsync(ct); + + public async Task SetAsync(string key, string? value, CancellationToken ct = default) + { + await inner.Settings.SetAsync(key, value, ct); + Wrote(); + } + + public async Task SetManyAsync(IReadOnlyDictionary values, CancellationToken ct = default) + { + await inner.Settings.SetManyAsync(values, ct); + Wrote(); + } + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; // the library owns the database + + private void Wrote() + { + SettingsWrites++; + request.Cancel(); + } + } + + private static async Task TurnOnAsync(TestLibrary library, ExportFormat photo) + { + var settings = ExportSettings.Default with { LibraryPhotoFormat = photo }; + await settings.SaveAsync(library.Db.Settings); + return settings; + } + + private static async Task StorePngAsync(TestLibrary library, Account account, Entry entry, Media media, int scene) + { + using var image = TestImages.Scene(scene, 64, 48); + await library.Ingest.SaveMediaAsync(account, entry, media, new MediaContent { Content = new MemoryStream(TestImages.Png(image)), Extension = ".png" }); + } + + private static Task<(Account Account, EntryWithMedia Entry)> SavePngAsync(TestLibrary library, string id, int scene) + { + using var image = TestImages.Scene(scene, 64, 48); + return SaveAsync(library, id, new TestFile(Make.Photo(1), TestImages.Png(image), ".png")); + } + + private static async Task<(Account Account, EntryWithMedia Entry)> SaveAsync(TestLibrary library, string id, TestFile file) + { + var account = await library.Db.Accounts.FindByUsernameAsync("marta.demo") ?? await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var entry = await library.SaveAsync(account, Make.Entry(account.Id, id, Make.T0.AddMinutes(int.Parse(id, System.Globalization.CultureInfo.InvariantCulture))), [file]); + return (account, entry); + } +} diff --git a/tests/Febe.Tests/Library/SafeFileWriterTests.cs b/tests/Febe.Tests/Library/SafeFileWriterTests.cs index 57a5a84..6ff8dcc 100644 --- a/tests/Febe.Tests/Library/SafeFileWriterTests.cs +++ b/tests/Febe.Tests/Library/SafeFileWriterTests.cs @@ -14,6 +14,36 @@ public sealed class SafeFileWriterTests return bytes; } + [TestMethod] + public async Task ProducedContentIsHashedAndATakenNameIsNumberedAfterTheKeptSuffix() + { + using var temp = new TempFolder(); + var content = Content(3000, 7); + Directory.CreateDirectory(Path.Combine(temp.Path, "post")); + File.WriteAllBytes(Path.Combine(temp.Path, "post", "a_f001.png"), [1, 2, 3]); + var tempDirectory = Path.Combine(temp.Path, ".tmp"); + Directory.CreateDirectory(tempDirectory); + FileDigest? seen = null; + + var saved = await new SafeFileWriter().SaveAsync( + (output, token) => output.WriteAsync(content, token).AsTask(), + temp.Path, + tempDirectory, + (digest, _) => + { + seen = digest; + return ValueTask.FromResult("post/a_f001.png"); + }, + new SafeWriteOptions { KeepSuffix = "_f001" }); + + Assert.IsNotNull(saved); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), seen!.Value.Sha256); + Assert.AreEqual(3000L, seen.Value.Bytes); + Assert.AreEqual("post/a_f001 (2).png", saved.RelativePath); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(temp.Path, "post", "a_f001.png")), "Il file che c'era non è toccato."); + CollectionAssert.AreEqual(content, File.ReadAllBytes(saved.FullPath)); + } + [TestMethod] public async Task WritesTheFileWithItsHashAndPublicationTime() { diff --git a/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs b/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs new file mode 100644 index 0000000..e63ae10 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs @@ -0,0 +1,304 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using Febe.Core.Codecs.Containers; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// «MOV → MP4 solo rimuxaggio» (tappa E3, WP1.4): the samples are copied as they are, with their times, sync samples, +/// edit, rotation, languages and dates; what the MP4 cannot take is refused with its reason, and the same source always +/// gives the same bytes of the length planned. The videos are built by the tests from conformance streams. +/// +[TestClass] +public sealed class Mp4RemuxerTests +{ + private static readonly DateTimeOffset Created = new(2025, 7, 14, 18, 30, 5, TimeSpan.Zero); + private static readonly DateTimeOffset Modified = new(2025, 7, 15, 9, 0, 0, TimeSpan.Zero); + + [TestMethod] + public void MovBecomesMp4WithTheSameSamplesDatesRotationAndLanguage() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); // B frames: composition offsets and an edit + var mov = TestVideos.Mov(es, new MovOptions(Audio: true, Language: "ita", Rotation: 90, Created: Created, Modified: Modified)); + using var source = new MemoryStream(mov); + var before = Read(source); + Assert.AreEqual("qt ", before.MajorBrand); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + Assert.IsEmpty(plan!.Losses); + var mp4 = Remux(plan, source); + + Assert.AreEqual(plan.OutputLength, mp4.Length, "the length is known before writing"); + using var output = new MemoryStream(mp4); + var after = Read(output); + Assert.AreNotEqual("qt ", after.MajorBrand); + Assert.AreEqual((Created, Modified), (after.CreatedAt, after.ModifiedAt)); + Assert.AreEqual(2, after.TrackCount); + Assert.AreEqual((90, "ita", "ita"), (after.Video!.Rotation, after.Video.Language, after.Audio!.Language)); + CollectionAssert.AreEqual(before.Video!.AvcConfiguration, after.Video.AvcConfiguration); + CollectionAssert.AreEqual(before.Audio!.AacConfiguration, after.Audio.AacConfiguration); + AssertSameSamples(before.Video, source, after.Video, output, "video"); + AssertSameSamples(before.Audio, source, after.Audio, output, "audio"); + + // The MP4 named .mp4 is what was asked: copied, not remuxed again. + Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(output, "clip.mp4", out _, CancellationToken.None)); + } + + [TestMethod] + public void TheStartAndSyncAreKeptByTheEditList() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var mov = TestVideos.Mov(es, new MovOptions(Audio: true, AudioPriming: 1024, VideoEmptyEdit: TestVideos.Timescale / 2)); + using var source = new MemoryStream(mov); + var before = Read(source); + Assert.AreEqual((1024L, 1), (before.Audio!.EditMediaTime, before.Audio.EditCount), "the priming is hidden by the edit"); + Assert.AreEqual((long)TestVideos.Timescale / 2, before.Video!.EmptyEditDuration, "the video starts half a second later"); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + using var output = new MemoryStream(Remux(plan!, source)); + var after = Read(output); + + Assert.AreEqual((before.Audio.EditMediaTime, before.Video.EmptyEditDuration), (after.Audio!.EditMediaTime, after.Video!.EmptyEditDuration)); + Assert.AreEqual(before.Video.EditMediaTime ?? 0, after.Video.EditMediaTime ?? 0); + AssertSameSamples(before.Video, source, after.Video, output, "video"); + AssertSameSamples(before.Audio, source, after.Audio, output, "audio"); + } + + [TestMethod] + public void ATrimmedEndStaysHiddenInTheMp4() + { + // A passthrough trim: the edits show 0,3 s of video and of audio, the rest of the media is hidden. + var es = ElementaryStream.Load("BA1_Sony_D"); + const int ShownFrames = 9; // 0,3 s: a whole number of milliseconds, as the movie timescale keeps the edit + Assert.IsGreaterThan(ShownFrames + 3, es.Count); + var shownVideo = (long)ShownFrames * TestVideos.FrameTicks; + var mov = TestVideos.Mov(es, new MovOptions(Audio: true, AudioPriming: 1024, VideoTrim: shownVideo, AudioTrim: 13230)); + using var source = new MemoryStream(mov); + var before = Read(source); + Assert.AreEqual(shownVideo, before.Video!.EditSegmentDuration); + Assert.AreEqual(13230L, before.Audio!.EditSegmentDuration); + Assert.AreEqual(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), before.Duration); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + using var output = new MemoryStream(Remux(plan!, source)); + var after = Read(output); + + Assert.AreEqual(shownVideo, after.Video!.EditSegmentDuration, "the edits are carried over"); + Assert.AreEqual(13230L, after.Audio!.EditSegmentDuration); + Assert.AreEqual((before.Audio.EditMediaTime, before.Video.EditMediaTime ?? 0), (after.Audio.EditMediaTime, after.Video.EditMediaTime ?? 0)); + Assert.AreEqual(before.Duration, after.Duration, "the MP4 lasts what the source shows"); + AssertSameSamples(before.Video, source, after.Video, output, "video"); + AssertSameSamples(before.Audio, source, after.Audio, output, "audio"); + + // A frame «oltre la fine» is the last one shown, never one the edit hides. + using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info); + Assert.IsTrue(info.Available); + var last = reader.Locate([TimeSpan.FromHours(1)]).Single(); + Assert.IsLessThan(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), last.Actual); + Assert.AreEqual(ShownFrames - 1, last.Sample); + } + + [TestMethod] + public void TheLastReorderedFramesStayShownInTheMp4() + { + // B frames, as iPhones and High profile encoders write them: the edit starts at the first composition offset + // and shows the whole presentation (N frames). The MP4 must show as much, never 2 frames less. + var es = ElementaryStream.Load("CABA3_SVA_B"); + var n = es.Count; + Assert.IsTrue(Enumerable.Range(0, n).Any(i => es.Rank[i] < i), "the stream has reordered frames"); + var presentation = (long)n * TestVideos.FrameTicks; + var mov = TestVideos.Mov(es, new MovOptions(VideoTrim: presentation)); + using var source = new MemoryStream(mov); + var before = Read(source); + Assert.IsGreaterThan(0L, before.Video!.EditMediaTime ?? 0, "the edit starts at the first composition offset"); + AssertAbout(presentation, before.Video.EditSegmentDuration, "the source shows all N frames"); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + var mp4 = Remux(plan!, source); + using var output = new MemoryStream(mp4); + var after = Read(output); + + Assert.AreEqual(before.Video.EditMediaTime, after.Video!.EditMediaTime); + Assert.AreEqual(before.Video.EditSegmentDuration, after.Video.EditSegmentDuration, "the segment is the source's"); + AssertAbout(presentation, after.Video.EditSegmentDuration, "the MP4 shows all N frames"); + Assert.AreEqual(before.Duration, after.Duration); + var shownMs = (long)Math.Ceiling(n * 1000.0 / 30); + Assert.AreEqual((shownMs, shownMs), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8)), "mvhd and tkhd last N frames"); + Assert.AreEqual((HeaderDuration(mov, "mvhd"u8), HeaderDuration(mov, "tkhd"u8)), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8))); + AssertSameSamples(before.Video, source, after.Video, output, "video"); + + // A frame «oltre la fine» is the one presented last, not one that decodes last. + var lastShown = Enumerable.Range(0, n).MaxBy(i => es.Rank[i]); + using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info); + Assert.IsTrue(info.Available); + Assert.AreEqual(lastShown, reader.Locate([TimeSpan.FromHours(1)]).Single().Sample); + } + + /// A segment read back from the movie timescale (milliseconds, rounded up) is within a millisecond. + private static void AssertAbout(long expected, long? actual, string what) + { + Assert.IsNotNull(actual, what); + Assert.IsLessThanOrEqualTo(TestVideos.Timescale / 1000, Math.Abs(actual.Value - expected), $"{what}: {actual} for {expected}"); + } + + /// The duration of the first mvhd or tkhd of a file (movie units), of either version. + private static long HeaderDuration(byte[] file, ReadOnlySpan type) + { + var at = file.AsSpan().IndexOf(type); + Assert.IsGreaterThan(0, at); + var body = file.AsSpan(at + 4); + var wide = body[0] == 1; + var isTrack = type[0] == (byte)'t'; + // version and flags, the dates, then the timescale (mvhd) or the track id and a reserved word (tkhd). + var offset = 4 + (wide ? 16 : 8) + (isTrack ? 8 : 4); + return wide ? (long)BinaryPrimitives.ReadUInt64BigEndian(body[offset..]) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]); + } + + [TestMethod] + [DataRow(44100, 0x6B)] + [DataRow(32000, 0x6B)] + [DataRow(24000, 0x69)] + [DataRow(22050, 0x69)] + [DataRow(16000, 0x69)] + public void Mp3IsLabelledMpeg1OrMpeg2AudioByItsRate(int rate, int objectType) + { + // ISO/IEC 14496-1 Table 5: 0x6B is ISO/IEC 11172-3 (MPEG-1, 32-48 kHz), 0x69 ISO/IEC 13818-3 (the lower rates). + var mov = TestVideos.Mov(ElementaryStream.Load("BA1_Sony_D"), new MovOptions(Audio: true, Mp3: true, AudioRate: rate)); + using var source = new MemoryStream(mov); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + var mp4 = Remux(plan!, source); + + Assert.AreEqual(objectType, ObjectTypeIndication(mp4)); + using var output = new MemoryStream(mp4); + Assert.AreEqual((AudioCodec.Mp3, rate), (Read(output).Audio!.Codec, Read(output).Audio!.SampleRate)); + } + + /// The objectTypeIndication of the DecoderConfigDescriptor (tag 4) in the esds of a file. + private static int ObjectTypeIndication(byte[] file) + { + var esds = file.AsSpan().IndexOf("esds"u8); + Assert.IsGreaterThan(0, esds); + var config = file.AsSpan(esds).IndexOf((ReadOnlySpan)[0x04, 0x80, 0x80, 0x80]); + Assert.IsGreaterThan(0, config); + return file[esds + config + 5]; + } + + [TestMethod] + public void ExtraTracksAreDroppedAndCountedAndMp3IsKept() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var two = new MemoryStream(TestVideos.Mov(es, new MovOptions(Audio: true, ExtraAudioTracks: 1))); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(two, "clip.mov", out var plan, CancellationToken.None)); + CollectionAssert.AreEqual(new[] { Mp4Remuxer.LostTracks + ":1" }, plan!.Losses.ToArray()); + using (var output = new MemoryStream(Remux(plan, two))) + { + Assert.AreEqual(2, Read(output).TrackCount); + } + + using var mp3 = new MemoryStream(TestVideos.Mov(es, new MovOptions(Audio: true, Mp3: true))); + Assert.AreEqual(AudioCodec.Mp3, Read(mp3).Audio!.Codec); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mp3, "clip.mov", out var mp3Plan, CancellationToken.None)); + using var mp3Output = new MemoryStream(Remux(mp3Plan!, mp3)); + Assert.AreEqual(AudioCodec.Mp3, Read(mp3Output).Audio!.Codec); + } + + [TestMethod] + public void HevcAndMatroskaAreRemuxedWithTheirSamples() + { + var hevc = ElementaryStream.LoadHevc("INITQP_A_Sony_1"); + using var mov = new MemoryStream(TestVideos.Mov(hevc)); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mov, "clip.mov", out var plan, CancellationToken.None)); + using (var output = new MemoryStream(Remux(plan!, mov))) + { + var after = Read(output); + Assert.AreEqual(VideoCodec.Hevc, after.Video!.Codec); + CollectionAssert.AreEqual(hevc.AvcC, after.Video.HevcConfiguration); + AssertSameSamples(Read(mov).Video!, mov, after.Video, output, "HEVC"); + } + + // Matroska block times are presentation times in milliseconds: the MP4 shows each sample at the same millisecond. + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var mkv = new MemoryStream(TestVideos.Matroska(es)); + var before = Read(mkv).Video!; + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mkv, "clip.mkv", out var mkvPlan, CancellationToken.None)); + using var remuxed = new MemoryStream(Remux(mkvPlan!, mkv)); + var after2 = Read(remuxed).Video!; + Assert.HasCount(before.Samples.Count, after2.Samples); + var buffer = new byte[1]; + var other = new byte[1]; + for (var i = 0; i < before.Samples.Count; i++) + { + CollectionAssert.AreEqual(ContainerReader.ReadSample(mkv, before.Samples[i], ref buffer).ToArray(), ContainerReader.ReadSample(remuxed, after2.Samples[i], ref other).ToArray(), $"campione {i}"); + Assert.AreEqual(before.Samples[i].Key, after2.Samples[i].Key, $"sincronia {i}"); + Assert.AreEqual( + Math.Round(before.Seconds(before.Samples[i].PresentationTime) * 1000), + Math.Round(after2.Seconds(after2.Samples[i].PresentationTime + after2.EmptyEditDuration) * 1000), + $"istante {i}"); + } + } + + [TestMethod] + public void WhatNeedsReEncodingIsRefusedWithItsReason() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + RemuxRefusal Check(byte[] data, string name) + { + using var stream = new MemoryStream(data); + var refusal = Mp4Remuxer.Check(stream, name, out var plan, CancellationToken.None); + Assert.AreEqual(refusal == RemuxRefusal.None, plan is not null); + return refusal; + } + + Assert.AreEqual(RemuxRefusal.VideoCodec, Check(TestVideos.Matroska(es, codecId: "V_VP9"), "clip.webm")); + Assert.AreEqual(RemuxRefusal.ContainerNotRemuxable, Check(TestVideos.Avi(es), "clip.avi")); + Assert.AreEqual(RemuxRefusal.AlreadyMp4, Check(TestVideos.Mp4(es), "clip.mp4")); + Assert.AreEqual(RemuxRefusal.None, Check(TestVideos.Mp4(es), "clip.m4v"), "an MP4 with another name is remuxed into a true .mp4"); + Assert.AreNotEqual(RemuxRefusal.None, Check(new byte[4096], "clip.mov")); + + // A truncated MOV: its samples are past the end of the file. + var mov = TestVideos.Mov(es); + Assert.AreEqual(RemuxRefusal.Unreadable, Check(mov[..(mov.Length - 100)], "clip.mov")); + } + + [TestMethod] + public void RemuxingTwiceGivesTheSameBytes() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var mov = TestVideos.Mov(es, new MovOptions(Audio: true, Language: "eng", Created: Created)); + string Once() + { + using var source = new MemoryStream(mov); + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None)); + return Convert.ToHexStringLower(SHA256.HashData(Remux(plan!, source))); + } + + Assert.AreEqual(Once(), Once()); + } + + private static MediaContainer Read(Stream stream) + { + stream.Position = 0; + return ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true)!; + } + + private static byte[] Remux(RemuxPlan plan, Stream source) + { + using var output = new MemoryStream(); + Mp4Remuxer.Write(plan, source, output, CancellationToken.None); + return output.ToArray(); + } + + private static void AssertSameSamples(MediaTrack before, Stream source, MediaTrack after, Stream output, string what) + { + Assert.HasCount(before.Samples.Count, after.Samples, what); + Assert.AreEqual(before.Timescale, after.Timescale, what); + var a = new byte[1]; + var b = new byte[1]; + for (var i = 0; i < before.Samples.Count; i++) + { + var (x, y) = (before.Samples[i], after.Samples[i]); + Assert.AreEqual((x.Size, x.DecodeTime, x.PresentationTime, x.Key), (y.Size, y.DecodeTime, y.PresentationTime, y.Key), $"{what} {i}"); + CollectionAssert.AreEqual(ContainerReader.ReadSample(source, x, ref a).ToArray(), ContainerReader.ReadSample(output, y, ref b).ToArray(), $"{what} {i}"); + } + } +} diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs index a150de8..72d9d29 100644 --- a/tests/Febe.Tests/Media/Containers/TestVideos.cs +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -308,6 +308,69 @@ internal static class TestVideos return output.ToArray(); } + /// + /// A QuickTime file (major brand qt , as phones write MOV) of the stream and, with , + /// an AAC track (or MP3) of fixed frames; with the options of a camera: track languages, rotation, both dates, the + /// AAC priming hidden by an edit, a delayed start (an empty edit) and a second audio track that the MP4 drops. + /// + public static byte[] Mov(ElementaryStream es, MovOptions? options = null) + { + var o = options ?? new MovOptions(); + var samples = new List(); + var data = new List(); + for (var i = 0; i < es.Count; i++) + { + var bytes = es.LengthPrefixed(i); + data.Add(bytes); + samples.Add(new Mp4OutputSample(bytes.Length, (long)i * FrameTicks, (long)es.Rank[i] * FrameTicks, es.Key[i])); + } + + var tracks = new List + { + new() + { + IsVideo = true, + Timescale = Timescale, + Samples = samples, + WriteSample = (i, s) => s.Write(data[i]), + Width = es.Width, + Height = es.Height, + Rotation = o.Rotation, + AvcConfiguration = es.Hevc ? null : es.AvcC, + HevcConfiguration = es.Hevc ? es.AvcC : null, + Language = o.Language, + EmptyEditDuration = o.VideoEmptyEdit, + EditMediaTime = o.VideoTrim > 0 ? 0 : null, + EditSegmentDuration = o.VideoTrim > 0 ? o.VideoTrim : null, + }, + }; + for (var track = 0; track < (o.Audio ? 1 : 0) + o.ExtraAudioTracks; track++) + { + var frames = (int)Math.Ceiling(es.Count / 30.0 * o.AudioRate / 1024) + (o.AudioPriming > 0 ? 1 : 0); + var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C, (byte)track }; + tracks.Add(new Mp4OutputTrack + { + IsVideo = false, + Timescale = o.AudioRate, + Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))], + WriteSample = (_, s) => s.Write(payload), + AacConfiguration = o.Mp3 ? null : [0x12, 0x10], // AAC LC, 44.1 kHz, stereo + IsMp3 = o.Mp3, + SampleRate = o.AudioRate, + Channels = 2, + Language = o.Language, + EditMediaTime = o.AudioPriming > 0 ? o.AudioPriming : null, + EditSegmentDuration = o.AudioTrim > 0 ? o.AudioTrim : null, + }); + } + + using var output = new MemoryStream(); + Mp4Writer.Prepare(tracks, new Mp4MovieInfo(o.Created, o.Modified)).WriteTo(output); + var file = output.ToArray(); + "qt "u8.CopyTo(file.AsSpan(8)); // the major brand of ftyp + return file; + } + /// /// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of frames). /// With the sample durations come from trex, each fragment has two runs that @@ -400,7 +463,7 @@ internal static class TestVideos /// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of /// nanoseconds (milliseconds by default). /// - public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000) + public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000, string? codecId = null) { var shift = 0; for (var i = 0; i < es.Count; i++) @@ -422,7 +485,7 @@ internal static class TestVideos var video = Element(0xE0, Element(0xB0, U16((ushort)es.Width)), Element(0xBA, U16((ushort)es.Height))); var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]), - Element(0x86, es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video); + Element(0x86, codecId is not null ? Encoding.ASCII.GetBytes(codecId) : es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video); var blocks = new List { Element(0xE7, [0]) }; for (var i = 0; i < es.Count; i++) { @@ -558,3 +621,25 @@ internal static class TestVideos return b; } } + +/// What puts in a QuickTime file. +/// One audio track (AAC unless ). +/// Further audio tracks (an MP4 of Febe keeps one). +/// Samples of AAC priming hidden by the audio edit (media time of the edit); 0: no edit. +/// Ticks (of 30000 a second) before the video starts: an empty edit. +/// Ticks (of 30000 a second) of video shown by its edit, the rest hidden (a trim); 0: all. +/// The sample rate (and timescale) of the audio; the AAC configuration always says 44,1 kHz. +/// Samples (of 44100 a second) of audio shown by its edit after the priming; 0: all. +internal sealed record MovOptions( + bool Audio = false, + bool Mp3 = false, + int ExtraAudioTracks = 0, + string? Language = null, + int Rotation = 0, + DateTimeOffset? Created = null, + DateTimeOffset? Modified = null, + long AudioPriming = 0, + long VideoEmptyEdit = 0, + long VideoTrim = 0, + long AudioTrim = 0, + int AudioRate = 44100); diff --git a/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs b/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs new file mode 100644 index 0000000..10d95c4 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs @@ -0,0 +1,250 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; +using Febe.Core.Export; +using Febe.Core.Library; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// Frames at chosen instants (tappa E3, D12): the sample shown at an instant, exact decoding at full size, rotation, +/// and the remux into MP4 (D9: the same bytes every time). +/// +[TestClass] +public sealed class VideoFramesTests +{ + [TestMethod] + [DataRow("mp4")] + [DataRow("mkv")] + public void TheFrameAtAnInstantIsTheOneShown(string kind) + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var data = kind == "mkv" ? TestVideos.Matroska(es) : TestVideos.Mp4(es); + using var stream = new MemoryStream(data); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + Assert.AreEqual((es.Width, es.Height), (info.Width, info.Height)); + + // 30 frames per second: 0.51 s shows frame 15 (shown at 0.5 s), 0.499 s still frame 14. The Matroska file starts + // showing later by the reordering delay of its B frames (its block times are presentation times as written). + var shift = kind == "mkv" ? Enumerable.Range(0, es.Count).Max(i => i - es.Rank[i]) : 0; + var targets = reader.Locate([TimeSpan.FromMilliseconds(510), TimeSpan.FromMilliseconds(499)]); + Assert.AreEqual(TimeSpan.FromMilliseconds(500), targets[0].Actual); + Assert.AreEqual(500L, ExportFrames.ActualMs(targets[0].Actual)); + Assert.IsLessThan(TimeSpan.FromMilliseconds(500), targets[1].Actual); + + var frames = reader.Decode(targets, CancellationToken.None).ToList(); + try + { + Assert.HasCount(2, frames); + foreach (var (frame, rank) in new[] { (frames.Single(f => f.Index == 0), 15 - shift), (frames.Single(f => f.Index == 1), 14 - shift) }) + { + var expected = VideoFrameDecoder.ToImage(ShownFrame(es, rank), 0, 0); + Assert.AreEqual((expected.Width, expected.Height), (frame.Image.Width, frame.Image.Height)); + var pixels = frame.Image.ToArray(); + for (var i = 0; i < expected.Width * expected.Height; i++) + { + Assert.AreEqual(expected.Rgb[i * 3], pixels[i * 4]); + Assert.AreEqual(expected.Rgb[(i * 3) + 1], pixels[(i * 4) + 1]); + Assert.AreEqual(expected.Rgb[(i * 3) + 2], pixels[(i * 4) + 2]); + Assert.AreEqual((byte)255, pixels[(i * 4) + 3]); + } + } + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [TestMethod] + public void BeforeTheStartAndPastTheEndGiveTheFirstAndLastFrames() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var stream = new MemoryStream(TestVideos.Mp4(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + + var targets = reader.Locate([TimeSpan.Zero, TimeSpan.FromHours(1), info.Duration]); + + Assert.AreEqual(Array.IndexOf(es.Rank, 0), targets[0].Sample); + Assert.AreEqual(Array.IndexOf(es.Rank, es.Count - 1), targets[1].Sample); + Assert.AreEqual(targets[1].Sample, targets[2].Sample); + } + + [TestMethod] + public void ReRequestingTheActualMsGivesTheSameFrame() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var stream = new MemoryStream(TestVideos.Matroska(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + var instants = ExportFrames.Spread(info.Duration, 7); + + var first = reader.Locate(instants); + var again = reader.Locate([.. first.Select(t => TimeSpan.FromMilliseconds(ExportFrames.ActualMs(t.Actual)))]); + + CollectionAssert.AreEqual(first.Select(t => t.Sample).ToArray(), again.Select(t => t.Sample).ToArray()); + } + + [TestMethod] + public void RotationIsApplied() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Mp4(es, rotation: 90)); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.AreEqual((es.Height, es.Width), (info.Width, info.Height)); + + using var frame = reader.Decode(reader.Locate([TimeSpan.Zero]), CancellationToken.None).Single(); + + Assert.AreEqual((es.Height, es.Width), (frame.Image.Width, frame.Image.Height)); + } + + [TestMethod] + public void AnUnreadableVideoSaysNotAvailable() + { + using var stream = new MemoryStream(new byte[4096]); + using var reader = VideoFrameReader.Open(stream, out var info); + + Assert.IsFalse(info.Available); + Assert.AreEqual(VideoFrameReader.NotAvailableMessage, info.Unavailable); + Assert.IsEmpty(reader.Locate([TimeSpan.Zero])); + } + + [TestMethod] + public void RemuxingTwiceGivesTheSameBytesOfThePlannedLength() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var mkv = TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)); + using var source = new MemoryStream(mkv); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "video.mkv", out var plan, CancellationToken.None)); + using var first = new MemoryStream(); + using var second = new MemoryStream(); + Mp4Remuxer.Write(plan!, source, first, CancellationToken.None); + Mp4Remuxer.Write(plan!, source, second, CancellationToken.None); + + Assert.AreEqual(plan!.OutputLength, first.Length); + CollectionAssert.AreEqual(SHA256.HashData(first.ToArray()), SHA256.HashData(second.ToArray())); + + // The MP4 shows the same frames at the same instants as the Matroska file. + first.Position = 0; + using var remuxed = VideoFrameReader.Open(first, out var info); + Assert.IsTrue(info.Available); + using var original = VideoFrameReader.Open(source, out _); + var instants = ExportFrames.Every(info.Duration, TimeSpan.FromMilliseconds(250)); + CollectionAssert.AreEqual( + original.Locate(instants).Select(t => t.Actual).ToArray(), + remuxed.Locate(instants).Select(t => t.Actual).ToArray()); + + // An MP4 named .mp4 is already what was asked. + using var mp4 = new MemoryStream(TestVideos.Mp4(es)); + Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(mp4, "video.mp4", out _, CancellationToken.None)); + } + + [TestMethod] + public void HevcFramesWork() + { + var es = ElementaryStream.LoadHevc("INITQP_A_Sony_1"); + using var stream = new MemoryStream(TestVideos.Mp4(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + + var target = reader.Locate([TimeSpan.FromMilliseconds(1010)]).Single(); + Assert.AreEqual(TimeSpan.FromSeconds(1), target.Actual); + using var frame = reader.Decode([target], CancellationToken.None).Single(); + + var shown = new List(); + var decoder = new Febe.Core.Codecs.H265.H265Decoder(); + decoder.FrameOutput += shown.Add; + decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(es.Name).BitstreamPath)); + var expected = VideoFrameDecoder.ToImage(shown[30], 0, 0); + var pixels = frame.Image.ToArray(); + for (var i = 0; i < expected.Width * expected.Height; i++) + { + Assert.AreEqual((expected.Rgb[i * 3], expected.Rgb[(i * 3) + 1], expected.Rgb[(i * 3) + 2]), (pixels[i * 4], pixels[(i * 4) + 1], pixels[(i * 4) + 2]), $"pixel {i}"); + } + } + + [TestMethod] + public void TheInstantFollowsTheEditList() + { + // The video starts half a second into the presentation (an empty edit): the browser shows nothing of it before. + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Mov(es, new MovOptions(VideoEmptyEdit: TestVideos.Timescale / 2))); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + + var targets = reader.Locate([TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(510), TimeSpan.FromMilliseconds(1010)]); + + Assert.AreEqual((Array.IndexOf(es.Rank, 0), TimeSpan.FromMilliseconds(500)), (targets[0].Sample, targets[0].Actual), "before the start: the first frame"); + Assert.AreEqual(TimeSpan.FromMilliseconds(500), targets[1].Actual); + Assert.AreEqual((Array.IndexOf(es.Rank, 15), TimeSpan.FromSeconds(1)), (targets[2].Sample, targets[2].Actual), "frame 15 is shown at 0.5 + 0.5 s"); + } + + [TestMethod] + public void EveryKSecondsAndNInAllFindTheFramesShown() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Mp4(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + + var every = reader.Locate(ExportFrames.Every(info.Duration, TimeSpan.FromMilliseconds(250))); + Assert.AreEqual(TimeSpan.Zero, every[0].Actual); + foreach (var t in every) + { + Assert.IsLessThanOrEqualTo(t.Requested, t.Actual, "the frame shown at an instant started at or before it"); + Assert.IsLessThan(TimeSpan.FromMilliseconds(34), t.Requested - t.Actual, "and less than a frame before"); + } + + var spread = reader.Locate(ExportFrames.Spread(info.Duration, 4)); + Assert.HasCount(4, spread.Select(t => t.Sample).Distinct().ToList(), "four different frames"); + var frames = reader.Decode(spread, CancellationToken.None).ToList(); + try + { + CollectionAssert.AreEquivalent(new[] { 0, 1, 2, 3 }, frames.Select(f => f.Index).ToArray(), "one picture per target"); + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [TestMethod] + public void AnUnsupportedCodecSaysNotAvailable() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Matroska(es, webm: true, codecId: "V_VP9")); + using var reader = VideoFrameReader.Open(stream, out var info); + + Assert.IsFalse(info.Available); + Assert.AreEqual(VideoFrameReader.NotAvailableMessage, info.Unavailable); + Assert.IsEmpty(reader.Locate([TimeSpan.Zero])); + } + + [TestMethod] + public void ADamagedStreamGivesNoPicture() + { + // The container is fine, the pictures are noise: no frame comes out, nothing throws. + var es = ElementaryStream.Load("BA1_Sony_D"); + var mp4 = TestVideos.Mp4(es); + var mdat = mp4.AsSpan().IndexOf("mdat"u8) + 4; + new Random(5).NextBytes(mp4.AsSpan(mdat + 64)); + using var stream = new MemoryStream(mp4); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available, "the tables are readable"); + + var frames = reader.Decode(reader.Locate([TimeSpan.FromMilliseconds(900)]), CancellationToken.None).ToList(); + frames.ForEach(f => f.Dispose()); + Assert.IsEmpty(frames); + } + + /// The frame shown at position , decoded straight from the stream. + private static H264Frame ShownFrame(ElementaryStream es, int rank) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name)); + var index = Array.IndexOf(es.Rank, rank); + return frames.Single(f => f.DecodeIndex == index); + } +} diff --git a/tests/Febe.Tests/Media/H264/H264PcmWriterTests.cs b/tests/Febe.Tests/Media/H264/H264PcmWriterTests.cs new file mode 100644 index 0000000..1cba046 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264PcmWriterTests.cs @@ -0,0 +1,78 @@ +using Febe.Core.Codecs.H264; +using Febe.Core.Library; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The small H.264 video the demo shows (tappa E3): PCM macroblocks only, so its frames decode to the samples written, +/// through the same reader «Fotogramma» uses. +/// +[TestClass] +public sealed class H264PcmWriterTests +{ + [TestMethod] + public void TheDemoVideoIsTheSameEveryTime() => + CollectionAssert.AreEqual(H264PcmWriter.DemoVideo(), H264PcmWriter.DemoVideo()); + + [TestMethod] + public void TheDemoVideoGivesItsFramesAtTheirInstants() + { + using var stream = new MemoryStream(H264PcmWriter.DemoVideo()); + using var reader = VideoFrameReader.Open(stream, out var info); + + Assert.IsTrue(info.Available, info.Unavailable); + Assert.AreEqual((H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight), (info.Width, info.Height)); + Assert.AreEqual(H264PcmWriter.DemoPictures, info.SampleCount); + Assert.AreEqual(TimeSpan.FromSeconds(2), info.Duration); + Assert.IsFalse(info.HasAudio); + + // 8 pictures per second: 1.234 s shows picture 9 (shown from 1.125 s). + var targets = reader.Locate([TimeSpan.FromMilliseconds(1234), TimeSpan.Zero]); + Assert.AreEqual(TimeSpan.FromMilliseconds(1125), targets[0].Actual); + Assert.AreEqual(9, targets[0].Sample); + + var frames = reader.Decode(targets, CancellationToken.None).ToList(); + try + { + Assert.HasCount(2, frames); + foreach (var frame in frames) + { + var expected = H264PcmWriter.DemoPicture(frame.Index == 0 ? 9 : 0); + var pixels = frame.Image.ToArray(); + var width = H264PcmWriter.DemoWidth; + foreach (var (x, y) in new[] { (0, 0), (17, 33), (width - 1, H264PcmWriter.DemoHeight - 1), (120, 200) }) + { + var (r, g, b) = Bt601(expected.Y[(y * width) + x], expected.Cb[((y / 2) * (width / 2)) + (x / 2)], expected.Cr[((y / 2) * (width / 2)) + (x / 2)]); + var at = ((y * width) + x) * 4; + Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at] - r), $"R at {x},{y}"); + Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at + 1] - g), $"G at {x},{y}"); + Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at + 2] - b), $"B at {x},{y}"); + Assert.AreEqual((byte)255, pixels[at + 3]); + } + } + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [TestMethod] + public void TheSamplesNeverContainAStartCode() + { + var nal = H264PcmWriter.Idr(H264PcmWriter.DemoPicture(3), 1); + for (var i = 0; i + 2 < nal.Length; i++) + { + Assert.IsFalse(nal[i] == 0 && nal[i + 1] == 0 && nal[i + 2] <= 3 && nal[i + 2] != 3, $"Start code at {i}"); + } + } + + private static (int R, int G, int B) Bt601(byte y, byte cb, byte cr) + { + var c = 1.164 * (y - 16); + var d = cb - 128; + var e = cr - 128; + static int Clamp(double v) => (int)Math.Clamp(Math.Round(v), 0, 255); + return (Clamp(c + (1.596 * e)), Clamp(c - (0.392 * d) - (0.813 * e)), Clamp(c + (2.017 * d))); + } +} diff --git a/tests/Febe.Tests/Media/H264/H264RecoveryPointTests.cs b/tests/Febe.Tests/Media/H264/H264RecoveryPointTests.cs new file mode 100644 index 0000000..2fb792e --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264RecoveryPointTests.cs @@ -0,0 +1,39 @@ +using Febe.Core.Codecs.H264; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The recovery point SEI (H.264 §D.1.8, §D.2.8) that lets an exact frame start at an I picture (D12 of tappa E3): only +/// with recovery_frame_cnt 0 and exact_match_flag 1. The access units are written by the test. +/// +[TestClass] +public sealed class H264RecoveryPointTests +{ + [TestMethod] + public void OnlyAnExactMatchIsAnExactStart() + { + // payload: ue(recovery_frame_cnt) = 0 «1», exact_match_flag, broken_link_flag 0, changing_slice_group_idc 00, + // then the stop bit of the payload: 1 1 0 00 1 00 (exact) and 1 0 0 00 1 00 (not exact). + Assert.IsTrue(H264Decoder.HasExactRecoveryPoint(AccessUnit(0xC4), 4), "exact_match_flag 1"); + Assert.IsFalse(H264Decoder.HasExactRecoveryPoint(AccessUnit(0x84), 4), "exact_match_flag 0: pictures may differ from the IDR's"); + + // recovery_frame_cnt 1 («010»), exact: the pictures are exact only one frame later. + Assert.IsFalse(H264Decoder.HasExactRecoveryPoint(AccessUnit(0x51), 4)); + + // Annex B carries the same. + Assert.IsTrue(H264Decoder.HasExactRecoveryPoint([0, 0, 0, 1, .. Sei(0xC4), 0, 0, 0, 1, .. Slice], 0)); + Assert.IsFalse(H264Decoder.HasExactRecoveryPoint([0, 0, 0, 1, .. Sei(0x84), 0, 0, 0, 1, .. Slice], 0)); + } + + /// A non-IDR slice NAL header and a byte of data: where the SEIs of an access unit end. + private static readonly byte[] Slice = [0x41, 0x9A]; + + /// An SEI NAL unit with one recovery point message of one byte, and its RBSP trailing bits. + private static byte[] Sei(byte payload) => [0x06, 0x06, 0x01, payload, 0x80]; + + private static byte[] AccessUnit(byte payload) + { + var sei = Sei(payload); + return [0, 0, 0, (byte)sei.Length, .. sei, 0, 0, 0, (byte)Slice.Length, .. Slice]; + } +} diff --git a/tests/Febe.Tests/Web/DemoExportTests.cs b/tests/Febe.Tests/Web/DemoExportTests.cs index 7c60263..bde03e3 100644 --- a/tests/Febe.Tests/Web/DemoExportTests.cs +++ b/tests/Febe.Tests/Web/DemoExportTests.cs @@ -1,6 +1,9 @@ +using System.IO.Compression; using System.Net; using System.Security.Cryptography; +using System.Text; using System.Text.Json; +using System.Text.RegularExpressions; using Febe.Core.Domain; using Febe.Core.Library; using Febe.Tests.Support; @@ -12,7 +15,8 @@ namespace Febe.Tests.Web; /// /// The copies of the demo (spec §10.6, tappa E2) tell one story everywhere: the block «Copie esterne» of each account /// counts what the «Copie» filter finds and what the tiles mark; every job has its files; a copy «Copiato» is a real -/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there. +/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there. Tappa E3: +/// a copy converted to PNG, a frame of a video and two conversions of the library, which the demo never runs. /// [TestClass] public sealed class DemoExportTests @@ -61,12 +65,18 @@ public sealed class DemoExportTests var destinations = await demo.Storage.Exports.ListDestinationsAsync(includeRetired: true, ct); Assert.IsGreaterThanOrEqualTo(2, destinations.Count); var states = new HashSet(); + var forms = new List(); foreach (var destination in destinations) { Assert.IsTrue(Directory.Exists(destination.RootPath), destination.RootPath); foreach (var copy in await demo.Storage.Exports.ListCopiesAsync(destination.Id, null, 0, 100_000, ct)) { states.Add(copy.State); + if (copy.State == ExportCopyState.Copied && copy.Variant != ExportVariant.Whole) + { + forms.Add(copy); + } + var path = copy.RelativePath is { } relative ? Path.Combine(destination.RootPath, LibraryLayout.ToPlatform(relative)) : null; switch (copy.State) { @@ -149,5 +159,132 @@ public sealed class DemoExportTests } Assert.IsGreaterThanOrEqualTo(2, checkedAccounts, "the demo has accounts with files to copy"); + + // Tappa E3: the converted copy (by the real engine) and the frame are real files with their SHA-256 (checked above). + var convertedCopy = forms.SingleOrDefault(c => c.Variant == ExportVariant.Converted); + Assert.IsNotNull(convertedCopy, "a copy converted to PNG"); + Assert.AreEqual(ExportFormat.Png, convertedCopy.Format); + StringAssert.EndsWith(convertedCopy.RelativePath, ".png"); + var frameCopy = forms.Single(c => c.Variant == ExportVariant.Frame); + Assert.AreEqual(TimeSpan.FromMilliseconds(1125), frameCopy.FrameAt, "1.234 s shows the picture shown from 1.125 s"); + StringAssert.EndsWith(frameCopy.RelativePath, "_t0m01s125.png"); + + // The demo video gives frames: the preview of that instant is the frame copied. + var videoId = frameCopy.MediaId!.Value; + var info = await GetAsync($"/api/media/{videoId}/frames/info"); + Assert.IsTrue(info.Bool("available"), info.ToString()); + Assert.AreEqual(2000L, info.Long("durationMs")); + using (var frame = await client.GetAsync($"/api/media/{videoId}/frame?at=1234&format=png&download=1", ct)) + { + Assert.AreEqual(HttpStatusCode.OK, frame.StatusCode); + Assert.AreEqual("image/png", frame.Content.Headers.ContentType?.MediaType); + Assert.AreEqual(frameCopy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await frame.Content.ReadAsByteArrayAsync(ct)))); + } + + var video = await demo.Storage.Media.GetAsync(videoId, ct); + var viewer = (await GetAsync($"/api/entries/{video!.EntryId}")).Items("media").Single(m => m.Long("id") == videoId); + Assert.IsTrue(viewer.Bool("framesAvailable")); + var frameRow = viewer.Items("copies").Single(c => c.Str("variant") == "frame"); + Assert.AreEqual(1125L, frameRow.Long("frameAtMs")); + Assert.AreEqual("0:01,125", frameRow.Str("frameLabel")); + + // Two conversions of the library, which the demo never runs: nothing waits and nothing changes. + var conversion = await GetAsync("/api/export/library-conversion"); + Assert.AreEqual(0, conversion.Int("pending")); + Assert.AreEqual(1, conversion.Int("converted")); + Assert.AreEqual(1, conversion.Int("asIs")); + Assert.AreEqual(0, conversion.Int("failed")); + var (rowId, file) = demo.World.ConversionFiles.Single(); + var row = await demo.Storage.Conversions.GetAsync(rowId, ct); + Assert.AreEqual(MediaConversionState.Converted, row!.State); + using (var converted = await client.GetAsync($"/api/conversions/{rowId}/file", ct)) + { + Assert.AreEqual(HttpStatusCode.OK, converted.StatusCode); + Assert.AreEqual("image/png", converted.Content.Headers.ContentType?.MediaType); + Assert.AreEqual(row.Sha256, Convert.ToHexStringLower(SHA256.HashData(await converted.Content.ReadAsByteArrayAsync(ct)))); + } + + var photo = await demo.Storage.Media.GetAsync(row.MediaId, ct); + var shown = (await GetAsync($"/api/entries/{photo!.EntryId}")).Items("media").Single(m => m.Long("id") == row.MediaId); + var shownRow = shown.Items("conversions").Single(); + Assert.AreEqual("converted", shownRow.Str("state")); + Assert.AreEqual("png", shownRow.Str("format")); + Assert.IsTrue(shownRow.Bool("available")); + await Task.Delay(TimeSpan.FromSeconds(1), ct); + Assert.AreEqual(MediaConversionState.Converted, (await demo.Storage.Conversions.GetAsync(rowId, ct))!.State, "the demo never converts"); + Assert.IsTrue(File.Exists(file)); + } + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task TheDemoGivesFramesAndPlansTheFormats() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("demo-export-formati"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct); + using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) }; + var origin = demo.Address.GetLeftPart(UriPartial.Authority); + + async Task SendAsync(HttpMethod method, string path, string? json = null) + { + using var request = new HttpRequestMessage(method, path); + request.Headers.TryAddWithoutValidation("Origin", origin); + if (json is not null) + { + request.Content = new StringContent(json, Encoding.UTF8, "application/json"); + } + + using var response = await client.SendAsync(request, ct); + var text = await response.Content.ReadAsStringAsync(ct); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}"); + return JsonDocument.Parse(text).RootElement.Clone(); + } + + // Entries of @marta.demo with a video cover and with a photo cover (the demo places them by the hour: asked). + var marta = (await SendAsync(HttpMethod.Get, "/api/accounts")).Items("accounts").Single(a => a.Str("username") == "marta.demo").Long("id"); + var tiles = (await SendAsync(HttpMethod.Get, $"/api/library?accounts={marta}&limit=1000")).Items("tiles").ToList(); + var videos = tiles.Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "video").Take(2).Select(t => t.Long("id")).ToList(); + var photos = tiles.Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "photo").Take(3).Select(t => t.Long("id")).ToList(); + Assert.HasCount(2, videos, "the demo has videos of marta.demo"); + Assert.IsNotEmpty(photos, "the demo has photos of marta.demo"); + + // «Fotogrammi…» of a selection: two in all of each video, the photos skipped, a zip named as the copies. + var selection = $"{{ \"entryIds\": [{string.Join(", ", videos.Concat(photos))}], \"frames\": {{ \"mode\": \"numero\", \"count\": 2, \"format\": \"png\" }} }}"; + var plan = await SendAsync(HttpMethod.Post, "/api/frames/plan", selection); + Assert.IsGreaterThanOrEqualTo(2, plan.Int("videos"), plan.ToString()); + Assert.IsGreaterThan(0, plan.Int("photosSkipped"), plan.ToString()); + Assert.AreEqual(0, plan.Int("notAvailable"), "every video of the demo gives frames"); + Assert.AreEqual(2 * plan.Int("videos"), plan.Int("frames")); + StringAssert.Contains(plan.Str("summary"), " si salt", plan.Str("summary")); + var token = await SendAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(plan.Int("frames"), token.Int("frames")); + using (var zip = await client.GetAsync(token.Str("url"), ct)) + { + Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode); + using var archive = new ZipArchive(new MemoryStream(await zip.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read); + Assert.HasCount(plan.Int("frames"), archive.Entries); + foreach (var entry in archive.Entries) + { + StringAssert.StartsWith(entry.FullName, "marta.demo/", entry.FullName); + Assert.IsTrue(Regex.IsMatch(entry.FullName, @"_f00[12]\.png$"), entry.FullName); + using var read = entry.Open(); + var head = new byte[8]; + read.ReadExactly(head); + CollectionAssert.AreEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, head, entry.FullName); + } + } + + // «Copia in…» of photos not copied yet (a new format is for those): PNG converts the JPG photos of the demo, + // without loss; JPG copies them byte for byte. + var notCopied = (await SendAsync(HttpMethod.Get, $"/api/library?accounts={marta}&copies=notCopied&limit=1000")).Items("tiles") + .Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "photo").Take(3).Select(t => t.Long("id")).ToList(); + Assert.IsNotEmpty(notCopied, "the demo has photos of marta.demo not copied yet"); + var photoIds = string.Join(", ", notCopied); + var png = await SendAsync(HttpMethod.Post, "/api/export/plan", $"{{ \"entryIds\": [{photoIds}], \"copyAgain\": false, \"photoFormat\": \"png\" }}"); + Assert.IsGreaterThan(0, png.Int("converted"), png.ToString()); + Assert.IsFalse(png.Bool("lossy"), png.ToString()); + var jpg = await SendAsync(HttpMethod.Post, "/api/export/plan", $"{{ \"entryIds\": [{photoIds}], \"copyAgain\": false, \"photoFormat\": \"jpg\" }}"); + Assert.AreEqual(0, jpg.Int("converted"), jpg.ToString()); + Assert.IsFalse(jpg.Bool("lossy"), "a JPG already JPG is copied as it is, never encoded again"); } } diff --git a/tests/Febe.Tests/Web/DemoTests.cs b/tests/Febe.Tests/Web/DemoTests.cs index 15e75ac..905bff3 100644 --- a/tests/Febe.Tests/Web/DemoTests.cs +++ b/tests/Febe.Tests/Web/DemoTests.cs @@ -219,8 +219,11 @@ public sealed class DemoTests } else { - // Videos have only their cover in the demo. - Assert.AreEqual(HttpStatusCode.NotFound, file.StatusCode); + // Every video of the demo plays its one short H.264 video (tappa E3: «Fotogramma» works in the demo). + Assert.AreEqual(HttpStatusCode.OK, file.StatusCode); + Assert.AreEqual("video/mp4", file.Content.Headers.ContentType?.MediaType); + var bytes = await file.Content.ReadAsByteArrayAsync(); + Assert.AreEqual("ftyp", System.Text.Encoding.ASCII.GetString(bytes, 4, 4), "a real MP4"); checkedVideos++; } } diff --git a/tests/Febe.Tests/Web/ExportApiDemoTests.cs b/tests/Febe.Tests/Web/ExportApiDemoTests.cs index 6248097..6d7979c 100644 --- a/tests/Febe.Tests/Web/ExportApiDemoTests.cs +++ b/tests/Febe.Tests/Web/ExportApiDemoTests.cs @@ -139,7 +139,8 @@ public sealed class ExportApiDemoTests Assert.IsTrue(copied.All(t => t.Str("copies") == "copied"), "every file the filter finds copied carries the mark"); var notCopied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=notCopied&limit=600")).Items("tiles").ToList(); Assert.IsNotEmpty(notCopied); - Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "a file not copied has no mark"); + // Tappa E3: a video with only a frame copied is still to copy, and says so («frameOnly»), never «copiato». + Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null || t.Str("copies") == "frameOnly"), "a file not copied has no mark of a copy"); Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/library?copies=tutti")).Status); var grouped = (await GetAsync($"/api/library?accounts={marta}&limit=600")).Items("tiles").ToList(); diff --git a/tests/Febe.Tests/Web/ExportFormatsApiTests.cs b/tests/Febe.Tests/Web/ExportFormatsApiTests.cs new file mode 100644 index 0000000..13c3e5b --- /dev/null +++ b/tests/Febe.Tests/Web/ExportFormatsApiTests.cs @@ -0,0 +1,465 @@ +using System.IO.Compression; +using System.Net; +using System.Text.Json; +using Febe.Core.Abstractions; +using Febe.Core.Codecs.H264; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Core.Storage; +using Febe.Tests.Alerts.Support; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web; +using Febe.Web.Library; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Web; + +/// +/// Formats and frames over the API of a real web host (tappa E3): the formats of the settings and of a folder of the +/// copies (wire names of D21), the conversion of the library (status, question, pause), and frames of a video built by +/// the test (information, one frame, the instants of a mode, «Scarica» of one frame and of a zip). +/// +[TestClass] +public sealed class ExportFormatsApiTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheFormatsOfTheSettingsAreSavedByTheirWireNames() + { + await using var server = await StartAsync(); + var overview = await server.GetJsonAsync("/api/export"); + foreach (var name in new[] { "photoFormat", "videoFormat", "libraryPhotoFormat", "libraryVideoFormat" }) + { + Assert.AreEqual("original", overview.Str(name), name); + } + + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "webplossless", videoFormat = "mp4" }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + Assert.IsNotEmpty(saved.Str("message")); + Assert.AreEqual("webplossless", saved.GetProperty("overview").Str("photoFormat")); + overview = await server.GetJsonAsync("/api/export"); + Assert.AreEqual("webplossless", overview.Str("photoFormat")); + Assert.AreEqual("mp4", overview.Str("videoFormat")); + Assert.AreEqual("original", overview.Str("libraryPhotoFormat"), "a partial request keeps the rest"); + + foreach (var wrong in new object[] { new { }, new { photoFormat = "mp4" }, new { videoFormat = "png" }, new { libraryPhotoFormat = "tiff" } }) + { + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", wrong)).Status, JsonSerializer.Serialize(wrong)); + } + + Assert.AreEqual("webplossless", (await server.GetJsonAsync("/api/export")).Str("photoFormat"), "a refused request changes nothing"); + + // A command from another page is refused, like every other one. + using var foreign = server.Request(HttpMethod.Put, "/api/export/settings", new { photoFormat = "png" }, "http://altro.example"); + using var refused = await server.Client.SendAsync(foreign, TestContext.CancellationToken); + Assert.AreEqual(HttpStatusCode.Forbidden, refused.StatusCode); + } + + [TestMethod] + public async Task AFolderOfTheCopiesKeepsItsFormats() + { + await using var server = await StartAsync(); + var root = server.Temp.Combine("usb"); + Directory.CreateDirectory(root); + var (status, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root, photoFormat: "png", videoFormat: "original")); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + var destination = saved.GetProperty("destination"); + Assert.AreEqual("png", destination.Str("photoFormat")); + Assert.AreEqual("original", destination.Str("videoFormat")); + var stored = await server.Db.Exports.GetDestinationAsync(destination.Long("id")); + Assert.AreEqual(ExportFormat.Png, stored!.PhotoFormat); + + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(server.Temp.Combine("nas"), photoFormat: "mp4"))).Status); + } + + [TestMethod] + public async Task TheConversionOfTheLibrarySaysWhatItWouldDo() + { + await using var server = await StartAsync(); + var status = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.AreEqual(0, status.Int("pending")); + Assert.IsFalse(status.Bool("on")); + var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?photo=png"); + Assert.AreEqual(0, preview.Int("files")); + foreach (var action in new[] { "pause", "resume", "retry" }) + { + var (code, answer) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/library-conversion/{action}", new { }); + Assert.AreEqual(HttpStatusCode.OK, code, $"{action}: {answer}"); + Assert.IsNotEmpty(answer.Str("message")); + } + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task FramesOfAVideoArePreviewedAndDownloaded() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var video = await AddVideoAsync(server); + + var info = await server.GetJsonAsync($"/api/media/{video.Id}/frames/info"); + Assert.IsTrue(info.Bool("available"), info.ToString()); + Assert.AreEqual(2000L, info.Long("durationMs")); + Assert.AreEqual(H264PcmWriter.DemoWidth, info.Int("width")); + + // A preview fits the size asked; a download is full size, PNG by default, named by its actual instant. + using (var preview = await server.Client.GetAsync($"/api/media/{video.Id}/frame?at=1234&max=120", ct)) + { + Assert.AreEqual(HttpStatusCode.OK, preview.StatusCode); + Assert.AreEqual("image/jpeg", preview.Content.Headers.ContentType?.MediaType); + } + + using (var full = await server.Client.GetAsync($"/api/media/{video.Id}/frame?at=1234&download=1", ct)) + { + Assert.AreEqual(HttpStatusCode.OK, full.StatusCode); + Assert.AreEqual("image/png", full.Content.Headers.ContentType?.MediaType); + StringAssert.EndsWith(full.Content.Headers.ContentDisposition?.FileNameStar ?? full.Content.Headers.ContentDisposition?.FileName?.Trim('"'), "_t0m01s125.png"); + } + + var instants = await server.GetJsonAsync($"/api/media/{video.Id}/frames/instants?mode=numero&count=4"); + Assert.AreEqual(4, instants.Int("total")); + var labels = instants.Items("instants").Select(i => i.Str("suffix")).ToList(); + CollectionAssert.AreEqual(new[] { "_f001", "_f002", "_f003", "_f004" }, labels); + var over = await server.GetJsonAsync($"/api/media/{video.Id}/frames/instants?mode=ogni&every=100"); + Assert.IsFalse(over.Bool("overCap")); + Assert.AreEqual(20, over.Int("total")); + + // «Scarica» of 3 frames: a zip with one entry per frame under the account folder, each a PNG. + var selection = new { mediaIds = new[] { video.Id }, frames = new { mode = "numero", count = 3, format = "png" } }; + var (planStatus, plan) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection); + Assert.AreEqual(HttpStatusCode.OK, planStatus, plan.ToString()); + Assert.AreEqual(1, plan.Int("videos")); + Assert.AreEqual(3, plan.Int("frames")); + Assert.IsFalse(plan.Bool("needsQuiet")); + var (tokenStatus, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.OK, tokenStatus, token.ToString()); + using (var zip = await server.Client.GetAsync(token.Str("url"), ct)) + { + Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode); + Assert.AreEqual("application/zip", zip.Content.Headers.ContentType?.MediaType); + using var archive = new ZipArchive(new MemoryStream(await zip.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read); + Assert.HasCount(3, archive.Entries); + foreach (var entry in archive.Entries) + { + StringAssert.StartsWith(entry.FullName, "marta.demo/"); + StringAssert.EndsWith(entry.FullName, ".png"); + using var data = entry.Open(); + var header = new byte[8]; + data.ReadExactly(header); + CollectionAssert.AreEqual(new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A }, header); + } + } + + // A token is used once. + using (var again = await server.Client.GetAsync(token.Str("url"), ct)) + { + Assert.AreEqual(HttpStatusCode.NotFound, again.StatusCode); + } + + // A photo has no frames. + var (photoStatus, _) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video.PhotoId}/frames/info"); + Assert.AreEqual(HttpStatusCode.BadRequest, photoStatus); + } + + [TestMethod] + public async Task AFormatLeftToTheSettingsIsStoredAsNone() + { + await using var server = await StartAsync(); + var root = server.Temp.Combine("usb"); + Directory.CreateDirectory(root); + var (_, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root, photoFormat: "jpg", videoFormat: "mp4")); + var id = saved.GetProperty("destination").Long("id"); + Assert.AreEqual((ExportFormat?)ExportFormat.Mp4, (await server.Db.Exports.GetDestinationAsync(id))!.VideoFormat); + + // «Come le impostazioni generali» is no format of its own: it follows the settings when they change. + var (status, changed) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(root, photoFormat: "general", videoFormat: "general")); + Assert.AreEqual(HttpStatusCode.OK, status, changed.ToString()); + Assert.AreEqual(id, changed.GetProperty("destination").Long("id"), "the same folder: the same destination"); + var stored = await server.Db.Exports.GetDestinationAsync(id); + Assert.AreEqual(((ExportFormat?)null, (ExportFormat?)null), (stored!.PhotoFormat, stored.VideoFormat)); + Assert.AreEqual(JsonValueKind.Null, changed.GetProperty("destination").GetProperty("photoFormat").ValueKind); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task CopyInConvertsAsTheRequestAsksAndSaysWhatStaysAsItIs() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var jpg = await WebLibrary.AddPostAsync(server, marta, "foto-1", Make.T0.AddDays(-1), WebLibrary.Photo(1)); + await WebLibrary.AddPostAsync(server, marta, "foto-2", Make.T0.AddDays(-2), WebLibrary.Photo(2)); + var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-3), WebLibrary.Image(PngBytes(3), ".png")); + var heic = await WebLibrary.AddPostAsync(server, marta, "heic", Make.T0.AddDays(-4), WebLibrary.Image(Heic, ".heic")); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + var (created, destination) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb)); + Assert.AreEqual(HttpStatusCode.OK, created, destination.ToString()); + var destinationId = destination.GetProperty("destination").Long("id"); + + // The plan of each choice: JPG converts the PNG with loss and leaves the HEIC as it is; PNG converts the two JPGs + // without loss; «Originale» (the settings) copies everything as it is and says nothing about it. + async Task PlanAsync(string? photoFormat) => + (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Id, photoFormat })).Body; + var toJpg = await PlanAsync("jpg"); + Assert.AreEqual((4, 1, true), (toJpg.Int("files"), toJpg.Int("converted"), toJpg.Bool("lossy")), toJpg.ToString()); + Assert.AreEqual(("HEIC", 1), toJpg.Items("asIs").Select(a => (a.Str("label"), a.Int("files"))).Single()); + StringAssert.StartsWith(toJpg.Str("summary"), "4 file · circa 1 HEIC copiato com'è · circa "); + StringAssert.EndsWith(toJpg.Str("summary"), " · con perdita"); + var toPng = await PlanAsync("png"); + Assert.AreEqual((4, 2, false), (toPng.Int("files"), toPng.Int("converted"), toPng.Bool("lossy")), toPng.ToString()); + Assert.IsFalse(toPng.Str("summary").Contains("con perdita", StringComparison.Ordinal)); + var asTheyAre = await PlanAsync(null); + Assert.AreEqual((4, 0, false), (asTheyAre.Int("files"), asTheyAre.Int("converted"), asTheyAre.Bool("lossy")), asTheyAre.ToString()); + Assert.IsEmpty(asTheyAre.Items("asIs").ToList()); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Id, photoFormat = "mp4" })).Status); + + // Copied as PNG: the JPGs converted, the PNG and the HEIC byte for byte, the library untouched. + var library = Fingerprint.Of(server.Library.Layout.AccountFolder(marta)); + var (started, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Id, photoFormat = "png" }); + Assert.AreEqual(HttpStatusCode.OK, started, job.ToString()); + await WebLibrary.WaitIdleAsync(server); + Fingerprint.AreEqual(library, Fingerprint.Of(server.Library.Layout.AccountFolder(marta)), "the library is never touched"); + var written = Directory.GetFiles(usb, "*", SearchOption.AllDirectories).Select(f => Path.GetExtension(f)).Order(StringComparer.Ordinal).ToArray(); + CollectionAssert.AreEqual(new[] { ".heic", ".png", ".png", ".png" }, written); + CollectionAssert.AreEqual(PngBytes(3), await File.ReadAllBytesAsync(CopyPath(usb, png.Media[0], ".png"), ct), "PNG to PNG is a byte copy"); + CollectionAssert.AreEqual(Heic, await File.ReadAllBytesAsync(CopyPath(usb, heic.Media[0], ".heic"), ct), "HEIC is copied as it is"); + var converted = await File.ReadAllBytesAsync(CopyPath(usb, jpg.Media[0], ".png"), ct); + CollectionAssert.AreEqual(new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G' }, converted[..4]); + + // The report says what was copied as it is; the viewer says the form of each copy. + var report = await server.GetJsonAsync($"/api/export/runs/{job.Items("runIds").Single().GetInt64()}/report"); + Assert.AreEqual(1, report.Items("accounts").Single().GetProperty("asIs").Int("HEIC"), report.ToString()); + Assert.IsTrue(report.Items("notes").Any(n => n.Str("path")?.EndsWith(".heic", StringComparison.Ordinal) == true && n.Str("text").Length > 0), report.ToString()); + async Task FormAsync(EntryWithMedia post) => + (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single().Items("copies").Select(c => $"{c.Str("state")} {c.Str("variant")} {c.GetProperty("format")}").Single(); + Assert.AreEqual("copied converted png", await FormAsync(jpg)); + Assert.AreEqual("copied whole ", await FormAsync(png)); + Assert.AreEqual("copied whole ", await FormAsync(heic)); + + // Already copied in another form: a new format applies to the files not yet copied (D3, §16 domanda 28). + var again = await PlanAsync("jpg"); + Assert.AreEqual((0, 4, false), (again.Int("files"), again.Int("alreadyCopied"), again.Bool("lossy")), again.ToString()); + + // A converted copy removed from the folder: «Copia di nuovo» writes that same form, whatever the settings say. + File.Delete(CopyPath(usb, jpg.Media[0], ".png")); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{destinationId}/check")).Status); + await WebLibrary.WaitAsync(async () => (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Count == 1, "the copy «Tolto»"); + await WebLibrary.WaitIdleAsync(server); + var removed = (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Single(); + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png), (removed.Variant, removed.Format)); + var (copiedAgain, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id }); + Assert.AreEqual(HttpStatusCode.OK, copiedAgain); + await WebLibrary.WaitIdleAsync(server); + CollectionAssert.AreEqual(converted, await File.ReadAllBytesAsync(CopyPath(usb, jpg.Media[0], ".png"), ct), "the same conversion at its place"); + Assert.IsFalse(File.Exists(CopyPath(usb, jpg.Media[0], ".jpg")), "not the whole file"); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task TheConversionOfTheLibraryAsksConvertsAndGoesWithTheFiles() + { + var ct = TestContext.CancellationToken; + await using var server = await WebTestServer.StartAsync( + new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, + s => + { + s.AddSingleton(new FakeExportDisk(500_000_000_000)); + // The worker of the composition, with a disk far above the threshold; the test runs its passes. + s.AddSingleton(sp => new LibraryConversionWorker(new LibraryConversionEnvironment + { + Storage = sp.GetRequiredService(), + Layout = () => sp.GetRequiredService().Layout, + Clock = sp.GetRequiredService(), + Gate = sp.GetRequiredService(), + Session = sp.GetRequiredService(), + FreeSpace = new FakeFreeSpaceProbe(), + })); + }); + var worker = server.App.Services.GetRequiredService(); + var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-1), WebLibrary.Image(PngBytes(5), ".png")); + var jpg = await WebLibrary.AddPostAsync(server, marta, "jpg", Make.T0.AddDays(-2), WebLibrary.Photo(6)); + + // The question: only the PNG would convert to JPG (a JPG is already one). + var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?photo=jpg"); + Assert.AreEqual((1, (long)PngBytes(5).Length), (preview.Int("files"), preview.Long("bytes")), preview.ToString()); + Assert.IsNotEmpty(preview.Str("text")); + + // «Solo i nuovi»: nothing already in the library is queued; a new file is, after its line of the journal. + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg" }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + Assert.AreEqual(0, saved.Int("queued")); + var conversion = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.AreEqual((true, 0), (conversion.Bool("on"), conversion.Int("pending"))); + var later = await WebLibrary.AddPostAsync(server, marta, "nuova", Make.T0, WebLibrary.Image(PngBytes(7), ".png")); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/export/library-conversion")).Int("pending"), "the new file waits for its conversion"); + + // Off: the queue empties; on with «Anche i N già in libreria»: both PNGs. + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "original" })).Status); + conversion = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.AreEqual((false, 0), (conversion.Bool("on"), conversion.Int("pending"))); + (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = true }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + Assert.AreEqual(2, saved.Int("queued")); + Assert.AreEqual(2, saved.GetProperty("overview").GetProperty("libraryConversion").Int("pending")); + + // «Interrompi» holds the queue; «Riprendi» lets it go. + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/library-conversion/pause", new { })).Status); + Assert.IsTrue((await server.GetJsonAsync("/api/export/library-conversion")).Bool("paused")); + Assert.AreEqual(0, (await worker.RunOnceAsync(ct)).Converted, "paused: nothing converts"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/library-conversion/resume", new { })).Status); + Assert.IsFalse((await server.GetJsonAsync("/api/export/library-conversion")).Bool("paused")); + var library = Fingerprint.Of(server.Library.Layout.AccountFolder(marta)); + Assert.AreEqual(2, (await worker.RunOnceAsync(ct)).Converted); + conversion = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.AreEqual((0, 2, 0), (conversion.Int("pending"), conversion.Int("converted"), conversion.Int("failed")), conversion.ToString()); + Assert.AreEqual("Convertiti 2", conversion.Str("text")); + + // The converted file is added next to its original, which stays as it was (rule 11). + var original = WebLibrary.PathOf(server, marta, png.Media[0]); + var added = Path.ChangeExtension(original, ".jpg"); + Assert.IsTrue(File.Exists(added)); + var after = Fingerprint.Of(server.Library.Layout.AccountFolder(marta)); + Assert.AreEqual(library.Count + 2, after.Count, "two files added, none changed or taken away"); + foreach (var (path, sha) in library) + { + Assert.AreEqual(sha, after[path], path); + } + + // The viewer row, the file over the API, and «Mostra nella cartella» where there is no desktop. + var row = (await server.GetJsonAsync($"/api/entries/{png.Entry.Id}")).Items("media").Single().Items("conversions").Single(); + Assert.AreEqual(("jpg", "converted", true, Path.GetFileName(added)), (row.Str("format"), row.Str("state"), row.Bool("available"), row.Str("fileName"))); + Assert.AreEqual(new FileInfo(added).Length, row.Long("bytes")); + Assert.IsEmpty((await server.GetJsonAsync($"/api/entries/{jpg.Entry.Id}")).Items("media").Single().Items("conversions").ToList(), "a JPG has nothing to convert"); + using (var file = await server.Client.GetAsync($"/api/conversions/{row.Long("id")}/file?download=1", ct)) + { + Assert.AreEqual(HttpStatusCode.OK, file.StatusCode); + Assert.AreEqual("image/jpeg", file.Content.Headers.ContentType?.MediaType); + Assert.AreEqual(Path.GetFileName(added), file.Content.Headers.ContentDisposition?.FileNameStar ?? file.Content.Headers.ContentDisposition?.FileName?.Trim('"')); + CollectionAssert.AreEqual(await File.ReadAllBytesAsync(added, ct), await file.Content.ReadAsByteArrayAsync(ct)); + } + + Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/conversions/999999/file")).Status); + var (shown, shownBody) = await server.SendJsonAsync(HttpMethod.Post, "/api/conversions/show-in-folder", new { conversionId = row.Long("id") }); + Assert.AreEqual(HttpStatusCode.BadRequest, shown); + StringAssert.Contains(shownBody.Str("message"), "Scarica"); + + // «Elimina dalla libreria» counts the converted files that go with the entries. + var (previewStatus, deletion) = await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete-preview", new { ids = new[] { png.Entry.Id, jpg.Entry.Id } }); + Assert.AreEqual(HttpStatusCode.OK, previewStatus, deletion.ToString()); + Assert.AreEqual((2, 2, 1), (deletion.Int("entries"), deletion.Int("files"), deletion.Int("convertedFiles"))); + + // «Rimuovi» with the files: the converted files go too, and the message says how many. + var (removed, removal) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/remove", new { deleteFiles = true }); + Assert.AreEqual(HttpStatusCode.OK, removed, removal.ToString()); + Assert.AreEqual(2, removal.Int("convertedFiles")); + StringAssert.Contains(removal.Str("message"), "e 2 file convertiti"); + Assert.IsFalse(File.Exists(added)); + Assert.IsFalse(File.Exists(Path.ChangeExtension(WebLibrary.PathOf(server, marta, later.Media[0]), ".jpg"))); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheQuestionOfOneKindNeitherCountsNorQueuesTheOther() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-1), WebLibrary.Image(PngBytes(8), ".png")); + var video = WebLibrary.DemoVideo(3); + var mov = await WebLibrary.AddPostAsync(server, marta, "mov", Make.T0.AddDays(-2), video with { Extension = ".mov" }); + + // Photos to JPG, «Solo i nuovi»: the PNG already in the library is left alone. + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = false }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + Assert.AreEqual(0, saved.Int("queued")); + + // Then videos to MP4: the question counts the MOV only, and «Anche i N» queues it only. + var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?video=mp4"); + Assert.AreEqual((1, (long)video.Bytes.Length), (preview.Int("files"), preview.Long("bytes")), preview.ToString()); + (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryVideoFormat = "mp4", convertExisting = true }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + Assert.AreEqual(1, saved.Int("queued")); + Assert.IsEmpty(await server.Db.Conversions.ListByMediaAsync(png.Media[0].Id, ct), "the photo refused with «Solo i nuovi» stays so"); + Assert.AreEqual(ExportFormat.Mp4, (await server.Db.Conversions.ListByMediaAsync(mov.Media[0].Id, ct)).Single().Format); + + // Asked about both (no kind named), the preview counts what both formats would add. + Assert.AreEqual(1, (await server.GetJsonAsync("/api/export/library-conversion/preview")).Int("files"), "the PNG"); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TwoQuickChangesOfTheSettingsAreBothKept() + { + await using var server = await StartAsync(); + for (var round = 0; round < 10; round++) + { + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "jpg", videoFormat = "mp4" }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + + // Two clicks one after the other: two requests at once, each changing one format. + var photo = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "original" }); + var video = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { videoFormat = "original" }); + foreach (var (code, body) in await Task.WhenAll(photo, video)) + { + Assert.AreEqual(HttpStatusCode.OK, code, body.ToString()); + } + + var overview = await server.GetJsonAsync("/api/export"); + Assert.AreEqual(("original", "original"), (overview.Str("photoFormat"), overview.Str("videoFormat")), $"round {round}"); + } + } + + // ------------------------------------------------------------------------------------------------- support + + /// A HEIC as far as its name and brand go: Febe copies it as it is, it never decodes it. + private static readonly byte[] Heic = [0, 0, 0, 0x18, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, 0, 0, 0, 8, .. "free"u8, .. new byte[64]]; + + private static byte[] PngBytes(int scene) + { + using var image = TestImages.Scene(scene, 64, 48); + return TestImages.Png(image); + } + + /// Where the general folder «usb» has the copy of a file of marta.demo, with the extension of its form. + private static string CopyPath(string usb, Media media, string extension) => + Path.Combine(usb, "marta.demo", LibraryLayout.ToPlatform(Path.ChangeExtension(media.RelativePath!, extension))); + + private static Task StartAsync() => + WebTestServer.StartAsync( + new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, + s => s.AddSingleton(new FakeExportDisk(500_000_000_000))); + + private static object Destination(string path, string? photoFormat = null, string? videoFormat = null) => new + { + scope = "general", + accountId = (long?)null, + path, + label = (string?)null, + types = new[] { "postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo" }, + namingScheme = (string?)null, + highlightNamingScheme = (string?)null, + profileNamingScheme = (string?)null, + photoFormat, + videoFormat, + }; + + /// A post of @marta.demo with the demo's 2 s video and a photo, saved as the collection does. + private static async Task<(long Id, long PhotoId)> AddVideoAsync(WebTestServer server) + { + var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex()); + var added = await server.Db.Entries.AddAsync(Make.Entry(account.Id, "video-1", Make.T0.AddDays(-1)), [Make.Video(1), Make.Photo(2)]); + var media = added.Stored.Media; + await ingest.SaveMediaAsync(account, added.Stored.Entry, media[0], new MediaContent { Content = new MemoryStream(H264PcmWriter.DemoVideo()), Extension = ".mp4" }); + await ingest.SaveMediaAsync(account, added.Stored.Entry, media[1], new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(3, 96, 120)), Extension = ".jpg" }); + await ingest.AppendJournalAsync(added.Stored.Entry.Id); + return (media[0].Id, media[1].Id); + } +} diff --git a/tests/Febe.Tests/Web/ExportFramesApiTests.cs b/tests/Febe.Tests/Web/ExportFramesApiTests.cs new file mode 100644 index 0000000..4e76c57 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportFramesApiTests.cs @@ -0,0 +1,521 @@ +using System.IO.Compression; +using System.Net; +using System.Text.Json; +using Febe.Core.Abstractions; +using Febe.Core.Codecs.H264; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web; +using Febe.Web.Export; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Web; + +/// +/// Frames over the API of a real web host (spec §4.10 «Fotogrammi», tappa E3, D12-D14), with videos built by the test: +/// the instants of each mode are the pictures shown, a video without frames says so everywhere, a preview past its +/// budget answers 503, «Scarica» gives one image or a zip (names, account folders, dates per the setting), the limits of +/// «Scarica» (20 at any time, 21-500 only outside engine sessions and other long work, more than 500 never), the lease of +/// a large zip held until it ends or the page goes away, and frames to the folder of the copies with their viewer rows, +/// mark and «Copia di nuovo». +/// +[TestClass] +public sealed class ExportFramesApiTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheInstantsOfEachModeAreThePicturesShown() + { + await using var server = await StartAsync(); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo())); + var video = post.Media[0].Id; + + // The demo video shows a picture every 125 ms: «Questo istante» gives the one shown, past the end the last one. + var at = (await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=istante&at=1234")).Items("instants").Single(); + Assert.AreEqual((1234L, 1125L, "0:01,125", "_t0m01s125"), (at.Long("requestedMs"), at.Long("actualMs"), at.Str("label"), at.Str("suffix"))); + var past = (await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=istante&at=60000")).Items("instants").Single(); + Assert.AreEqual(1875L, past.Long("actualMs"), "past the end: the last picture"); + + // «Uno ogni k secondi» from 0:00; «N in tutto» centred in N equal parts (§16 domanda 33). + var every = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=ogni&every=500"); + Assert.AreEqual(4, every.Int("total")); + CollectionAssert.AreEqual(new long[] { 0, 500, 1000, 1500 }, every.Items("instants").Select(i => i.Long("actualMs")).ToArray()); + CollectionAssert.AreEqual(new[] { "_t0m00s000", "_t0m00s500", "_t0m01s000", "_t0m01s500" }, every.Items("instants").Select(i => i.Str("suffix")).ToArray()); + var count = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=numero&count=4"); + CollectionAssert.AreEqual(new long[] { 250, 750, 1250, 1750 }, count.Items("instants").Select(i => i.Long("requestedMs")).ToArray()); + CollectionAssert.AreEqual(new long[] { 250, 750, 1250, 1750 }, count.Items("instants").Select(i => i.Long("actualMs")).ToArray()); + CollectionAssert.AreEqual(new[] { "0:00,25", "0:00,75", "0:01,25", "0:01,75" }, count.Items("instants").Select(i => i.Str("label")).ToArray()); + + // A re-request at the actual instant gives the same picture (D12: ceil ms). + using (var first = await server.Client.GetAsync($"/api/media/{video}/frame?at=1234&format=png", TestContext.CancellationToken)) + using (var again = await server.Client.GetAsync($"/api/media/{video}/frame?at=1125&format=png", TestContext.CancellationToken)) + { + CollectionAssert.AreEqual(await first.Content.ReadAsByteArrayAsync(TestContext.CancellationToken), await again.Content.ReadAsByteArrayAsync(TestContext.CancellationToken)); + } + + // The limits (§16 domanda 38) and the words of the modes. + foreach (var wrong in new[] { "mode=ogni&every=50", "mode=numero&count=0", "mode=numero&count=1001", "mode=sempre", "mode=numero&count=3&format=gif" }) + { + var path = $"/api/media/{video}/frames/instants?{wrong}"; + if (wrong.Contains("format", StringComparison.Ordinal)) + { + path = $"/api/media/{video}/frame?at=0&format=gif"; + } + + var (status, body) = await server.SendJsonAsync(HttpMethod.Get, path); + Assert.AreEqual(HttpStatusCode.BadRequest, status, wrong); + Assert.IsNotEmpty(body.Str("message"), wrong); + } + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task AVideoWithoutFramesSaysSoEverywhere() + { + await using var server = await StartAsync(); + var noise = new byte[40_000]; + new Random(5).NextBytes(noise); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "rumore", Make.T0.AddDays(-1), WebLibrary.Video(noise)); + var video = post.Media[0].Id; + + var info = await server.GetJsonAsync($"/api/media/{video}/frames/info"); + Assert.IsFalse(info.Bool("available")); + Assert.IsNotEmpty(info.Str("unavailable")); + + var (frameStatus, frame) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video}/frame?at=0&max=160"); + Assert.AreEqual(HttpStatusCode.NotFound, frameStatus); + Assert.IsNotEmpty(frame.Str("message")); + var instants = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=numero&count=3"); + Assert.AreEqual(0, instants.Int("total")); + Assert.IsNotEmpty(instants.Str("problem")); + + // The viewer says «Fotogramma non disponibile» (WP4) from this flag. + var shown = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single(); + Assert.IsFalse(shown.Bool("framesAvailable")); + + var selection = new { mediaIds = new[] { video }, frames = new { mode = "istante", atMs = 0, format = "png" } }; + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection)).Body; + Assert.AreEqual((1, 1, 0), (plan.Int("videos"), plan.Int("notAvailable"), plan.Int("frames")), plan.ToString()); + Assert.AreEqual(FrameService.NothingText, plan.Str("problem")); + StringAssert.Contains(plan.Str("summary"), "1 video senza fotogrammi"); + var (tokenStatus, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.BadRequest, tokenStatus); + Assert.AreEqual(FrameService.NothingText, token.Str("message")); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task APreviewPastItsBudgetSaysToUseTheFolderOfTheCopies() + { + await using var server = await WebTestServer.StartAsync( + new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, + s => s.AddSingleton(sp => new FrameService(sp.GetRequiredService()) { Budget = TimeSpan.Zero })); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo())); + + var (status, body) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{post.Media[0].Id}/frame?at=0&max=160"); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, status); + Assert.AreEqual(FrameService.TimeoutText, body.Str("message")); + + // What the video allows is known without decoding a frame. + Assert.IsTrue((await server.GetJsonAsync($"/api/media/{post.Media[0].Id}/frames/info")).Bool("available")); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task ScaricaGivesOneImageOrAZipNamedAndDatedAsTheCopies() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var first = await WebLibrary.AddPostAsync(server, marta, "primo", Make.T0.AddDays(-3), WebLibrary.DemoVideo(2)); + var second = await WebLibrary.AddPostAsync(server, marta, "secondo", Make.T0.AddDays(-5), WebLibrary.DemoVideo(3), WebLibrary.Photo(4)); + + // One frame: the image itself, named by its actual instant, in the format chosen. + var one = new { mediaIds = new[] { first.Media[0].Id }, frames = new { mode = "istante", atMs = 1234, format = "jpg" } }; + var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", one); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + Assert.AreEqual(1, token.Int("frames")); + using (var image = await server.Client.GetAsync(token.Str("url"), ct)) + { + Assert.AreEqual(HttpStatusCode.OK, image.StatusCode); + Assert.AreEqual("image/jpeg", image.Content.Headers.ContentType?.MediaType); + Assert.AreEqual(Stem(first.Media[0]) + "_t0m01s125.jpg", FileName(image)); + var bytes = await image.Content.ReadAsByteArrayAsync(ct); + Assert.AreEqual((0xFF, 0xD8), (bytes[0], bytes[1])); + } + + // Two entries, grouped: their videos (the photo is skipped and said), three frames each, in one zip. + var both = new { entryIds = new[] { first.Entry.Id, second.Entry.Id }, frames = new { mode = "numero", count = 3, format = "png" } }; + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", both)).Body; + Assert.AreEqual((2, 1, 0, 6), (plan.Int("videos"), plan.Int("photosSkipped"), plan.Int("notAvailable"), plan.Int("frames")), plan.ToString()); + Assert.AreEqual("6 fotogrammi da 2 video · la foto si salta", plan.Str("summary")); + Assert.IsFalse(plan.Bool("needsQuiet")); + Assert.AreEqual(JsonValueKind.Null, plan.GetProperty("problem").ValueKind); + + var published = await ZipAsync(server, both); + Assert.AreEqual($"febe-fotogrammi-{LocalCalendar.Today(server.Clock.Now, server.Clock.LocalZone):yyyy-MM-dd}.zip", published.Name); + var expected = new[] { first, second } + .SelectMany(p => new[] { "_f001", "_f002", "_f003" }.Select(s => $"marta.demo/{Stem(p.Media[0])}{s}.png")) + .ToArray(); + CollectionAssert.AreEquivalent(expected, published.Entries.Keys.ToArray()); + // The time of publication of each entry, where Febe runs (D18; the zip keeps 2 s steps). + AssertNear(first.Entry.PublishedAt, published.Entries[expected[0]], server.Clock.LocalZone); + AssertNear(second.Entry.PublishedAt, published.Entries[expected[3]], server.Clock.LocalZone); + + // «Data del file = pubblicazione» off: the time of the download. + await server.Db.Settings.SetAsync(SettingKeys.SetFileTimeToPublication, "false", ct); + var now = await ZipAsync(server, both); + Assert.IsTrue(now.Entries.Values.All(time => Math.Abs((time - TimeZoneInfo.ConvertTime(server.Clock.Now, server.Clock.LocalZone).DateTime).TotalSeconds) <= 2), string.Join(", ", now.Entries.Values)); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task TheLimitsOfScaricaAreKept() + { + var session = new FakeSessionState(); + await using var server = await StartAsync(session); + var gate = server.App.Services.GetRequiredService(); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo())); + object Selection(int n) => new { mediaIds = new[] { post.Media[0].Id }, frames = new { mode = "numero", count = n, format = "png" } }; + + // More than 500: never «Scarica» (the folder of the copies takes them); more than 1.000 a video: refused. + var many = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(501))).Body; + Assert.IsTrue(many.Bool("tooManyToDownload")); + Assert.AreEqual(FrameService.TooManyText, many.Str("problem")); + Assert.AreEqual((HttpStatusCode.BadRequest, FrameService.TooManyText), await TokenAsync(server, Selection(501))); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(1001))).Status); + + // From 21: only when it is quiet; up to 20 at any time. + var quiet = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body; + Assert.IsTrue(quiet.Bool("needsQuiet")); + Assert.AreEqual(JsonValueKind.Null, quiet.GetProperty("problem").ValueKind); + + session.InSession = true; + Assert.AreEqual(FrameService.SessionText, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.Str("problem")); + Assert.AreEqual(((HttpStatusCode)409, FrameService.SessionText), await TokenAsync(server, Selection(21))); + Assert.HasCount(16, (await ZipAsync(server, Selection(20))).Entries, "20 frames during a session: a zip of the 16 pictures of the video"); + + // A download asked outside a session and opened during one waits for it to end. + session.InSession = false; + var (_, ready) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", Selection(21)); + session.InSession = true; + var (late, lateBody) = await server.SendJsonAsync(HttpMethod.Get, ready.Str("url")); + Assert.AreEqual((HttpStatusCode)409, late); + Assert.AreEqual(FrameService.SessionText, lateBody.Str("message")); + session.InSession = false; + + // Another long work: 21 and more wait for it with its message, 20 do not. + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var export, out _)); + using (export) + { + var busy = LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Export); + Assert.AreEqual(busy, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.Str("problem")); + Assert.AreEqual(((HttpStatusCode)409, busy), await TokenAsync(server, Selection(21))); + Assert.HasCount(16, (await ZipAsync(server, Selection(20))).Entries); + } + + Assert.IsNull(gate.Busy, "no lease is left behind"); + } + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task AZipOfMoreThanTwentyHoldsItsLeaseUntilItEndsOrThePageGoes() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var gate = server.App.Services.GetRequiredService(); + // Big pictures of noise, so the zip (about 60 MB of PNG) cannot sit whole in the buffers of the connection: the + // server is still writing while the test looks. + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "rumore", Make.T0.AddDays(-1), WebLibrary.Video(NoiseVideo(1280, 720, 24))); + var selection = new { mediaIds = new[] { post.Media[0].Id }, frames = new { mode = "numero", count = 22, format = "png" } }; + + // Read to the end: the lease is held while it is written, then let go. + var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + using (var response = await server.Client.GetAsync(token.Str("url"), HttpCompletionOption.ResponseHeadersRead, ct)) + { + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, gate.Busy); + Assert.IsFalse(gate.TryEnter(LongWorkKind.Import, out _, out var busyWith)); + Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, busyWith); + Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.FrameDownload), (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection)).Body.Str("problem")); + using var archive = new ZipArchive(new MemoryStream(await response.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read); + Assert.HasCount(22, archive.Entries); + } + + await WaitFreeAsync(gate, "after the whole zip"); + + // The page goes away halfway: the lease goes with it. + (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + var abandoned = await server.Client.GetAsync(token.Str("url"), HttpCompletionOption.ResponseHeadersRead, ct); + Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, gate.Busy); + var part = new byte[64 * 1024]; + await (await abandoned.Content.ReadAsStreamAsync(ct)).ReadAtLeastAsync(part, part.Length, throwOnEndOfStream: false, ct); + abandoned.Dispose(); + await WaitFreeAsync(gate, "after the page went away"); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _), "another long work can start"); + lease.Dispose(); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task FramesGoToTheFolderOfTheCopiesAndAreCopiedAgainOnRequest() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var post = await WebLibrary.AddPostAsync(server, marta, "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo()), WebLibrary.Photo(4)); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + var (created, destination) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", WebLibrary.Destination(usb)); + Assert.AreEqual(HttpStatusCode.OK, created, destination.ToString()); + var destinationId = destination.GetProperty("destination").Long("id"); + + // Formats and frames are two different requests. + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { entryIds = new[] { post.Entry.Id }, photoFormat = "png", frames = new { mode = "istante", atMs = 1234 } })).Status); + + var request = new { entryIds = new[] { post.Entry.Id }, frames = new { mode = "istante", atMs = 1234, format = "png" } }; + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", request)).Body; + Assert.AreEqual((1, 1, 1), (plan.Int("videos"), plan.Int("photosSkipped"), plan.Int("frames")), plan.ToString()); + Assert.AreEqual("1 fotogramma da 1 video · la foto si salta", plan.Str("summary")); + Assert.IsFalse(plan.Bool("lossy")); + Assert.IsTrue((await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { entryIds = new[] { post.Entry.Id }, frames = new { mode = "istante", atMs = 1234, format = "jpg" } })).Body.Bool("lossy"), "a JPG frame is «con perdita»"); + + await WebLibrary.StartAndWaitAsync(server, request); + var frame = Path.Combine(usb, "marta.demo", LibraryLayout.ToPlatform(Path.ChangeExtension(post.Media[0].RelativePath!, null) + "_t0m01s125.png")); + Assert.IsTrue(File.Exists(frame), string.Join(", ", Directory.GetFiles(usb, "*", SearchOption.AllDirectories))); + Assert.HasCount(1, Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "only the frame: the video and the photo are not copied"); + + // The viewer row of the frame, and the mark of the entry: a frame does not make the file «Copiato». + var shown = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").ToDictionary(m => m.Long("id")); + var row = shown[post.Media[0].Id].Items("copies").Single(); + Assert.AreEqual(("copied", "frame", "png", 1125L, "0:01,125"), (row.Str("state"), row.Str("variant"), row.Str("format"), row.Long("frameAtMs"), row.Str("frameLabel"))); + Assert.IsFalse(row.Bool("canCopyAgain")); + var tile = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").Single(t => t.Long("id") == post.Entry.Id); + Assert.AreEqual("frameOnly", tile.Str("copies"), tile.ToString()); + Assert.HasCount(1, (await server.GetJsonAsync("/api/library?copies=notCopied")).Items("tiles").ToList(), "still «Non ancora copiati»"); + + // Removed from the folder: «Controlla le copie» says «Tolto», «Copia di nuovo» writes the same frame again. + File.Delete(frame); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{destinationId}/check")).Status); + await WebLibrary.WaitAsync(async () => (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Count == 1, "the frame «Tolto»"); + await WebLibrary.WaitIdleAsync(server); + row = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single(m => m.Long("id") == post.Media[0].Id).Items("copies").Single(); + Assert.AreEqual("removed", row.Str("state")); + Assert.IsTrue(row.Bool("canCopyAgain")); + var (again, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = row.Long("copyId") }); + Assert.AreEqual(HttpStatusCode.OK, again, job.ToString()); + await WebLibrary.WaitIdleAsync(server); + Assert.IsTrue(File.Exists(frame), "the frame written again at its place"); + var copies = await server.Db.Exports.ListCopiesAsync(destinationId, null, 0, 10, ct); + Assert.AreEqual( + (ExportVariant.Frame, ExportFormat.Png, TimeSpan.FromMilliseconds(1125)), + copies.Where(c => c.State == ExportCopyState.Copied).Select(c => (c.Variant, c.Format, c.FrameAt!.Value)).Single(), + "the same form, not the whole video"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = row.Long("copyId") })).Status, "already copied again"); + } + + [TestMethod] + public async Task CommandsOfFramesAndConversionsComeOnlyFromFebesPages() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var frames = new { mediaIds = new[] { 1L }, frames = new { mode = "istante", atMs = 0 } }; + foreach (var (method, path, body) in new (HttpMethod, string, object)[] + { + (HttpMethod.Post, "/api/frames/plan", frames), + (HttpMethod.Post, "/api/frames/download-token", frames), + (HttpMethod.Post, "/api/conversions/show-in-folder", new { conversionId = 1 }), + (HttpMethod.Post, "/api/entries/delete-preview", new { ids = new[] { 1L } }), + (HttpMethod.Post, "/api/export/library-conversion/pause", new { }), + (HttpMethod.Post, "/api/export/library-conversion/resume", new { }), + (HttpMethod.Post, "/api/export/library-conversion/retry", new { }), + (HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = true }), + }) + { + using var request = server.Request(method, path, body, "http://altro.example"); + using var response = await server.Client.SendAsync(request, ct); + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, path); + } + + var status = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.IsFalse(status.Bool("paused"), "nothing was done"); + Assert.IsFalse(status.Bool("on")); + } + + // ------------------------------------------------------------------------------------------------- support + + private static Task StartAsync(IEngineSessionState? session = null) => + WebTestServer.StartAsync( + new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, + s => + { + s.AddSingleton(new FakeExportDisk(500_000_000_000)); + if (session is not null) + { + s.AddSingleton(session); + } + }); + + private static Task AccountAsync(WebTestServer server) => server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + + private static string Stem(Media media) => Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(media.RelativePath!)); + + private static string? FileName(HttpResponseMessage response) => + response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName?.Trim('"'); + + private static void AssertNear(DateTimeOffset expected, DateTime actual, TimeZoneInfo zone) + { + var local = TimeZoneInfo.ConvertTime(expected, zone).DateTime; + Assert.IsLessThanOrEqualTo(2.0, Math.Abs((actual - local).TotalSeconds), $"{actual} vs {local}"); + } + + private static async Task<(HttpStatusCode Status, string Message)> TokenAsync(WebTestServer server, object selection) + { + var (status, body) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + return (status, body.ValueKind == JsonValueKind.Object && body.TryGetProperty("message", out var message) ? message.GetString() ?? string.Empty : string.Empty); + } + + /// «Scarica» of a selection that gives a zip: its name and its entries with their times. + private async Task<(string? Name, Dictionary Entries)> ZipAsync(WebTestServer server, object selection) + { + var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + using var response = await server.Client.GetAsync(token.Str("url"), TestContext.CancellationToken); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual("application/zip", response.Content.Headers.ContentType?.MediaType); + using var archive = new ZipArchive(new MemoryStream(await response.Content.ReadAsByteArrayAsync(TestContext.CancellationToken)), ZipArchiveMode.Read); + foreach (var entry in archive.Entries) + { + Assert.AreEqual(entry.Length, entry.CompressedLength, $"{entry.FullName}: stored, not compressed"); + } + + return (FileName(response), archive.Entries.ToDictionary(e => e.FullName, e => e.LastWriteTime.DateTime, StringComparer.Ordinal)); + } + + private static async Task WaitFreeAsync(LongWorkGate gate, string what) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + while (gate.Busy is not null) + { + if (watch.Elapsed > TimeSpan.FromSeconds(90)) + { + Assert.Fail($"the lease of the zip is still held {what}"); + } + + await Task.Delay(50); + } + } + + /// An I_PCM video of noise (it does not compress), 8 pictures per second. + private static byte[] NoiseVideo(int width, int height, int pictures) + { + var random = new Random(11); + using var output = new MemoryStream(); + H264PcmWriter.WriteMp4(output, width, height, pictures, 8, _ => + { + var p = new H264PcmPicture(width, height); + foreach (var plane in new[] { p.Y, p.Cb, p.Cr }) + { + random.NextBytes(plane); + for (var i = 0; i < plane.Length; i++) + { + plane[i] = (byte)(16 + (plane[i] % 220)); // no zero byte, as in the demo video + } + } + + return p; + }); + return output.ToArray(); + } +} + +/// Library files and folders of the copies for the web tests of tappa E3, saved as the collection does. +internal static class WebLibrary +{ + public sealed record Item(byte[] Bytes, string Extension, MediaKind Kind); + + public static Item Video(byte[] bytes) => new(bytes, ".mp4", MediaKind.Video); + + /// + /// The demo's video with its own creation date, so two of them are two files (the same bytes would be one file of the + /// library in two entries). + /// + public static Item DemoVideo(int day) + { + using var output = new MemoryStream(); + H264PcmWriter.WriteMp4(output, H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight, H264PcmWriter.DemoPictures, H264PcmWriter.DemoFps, H264PcmWriter.DemoPicture, new DateTimeOffset(2026, 1, day, 12, 0, 0, TimeSpan.Zero)); + return Video(output.ToArray()); + } + + public static Item Photo(int scene) => new(TestFile.PhotoBytes(scene, 96, 120), ".jpg", MediaKind.Photo); + + public static Item Image(byte[] bytes, string extension) => new(bytes, extension, MediaKind.Photo); + + /// A post of with its files on disk and its journal line. + public static async Task AddPostAsync(WebTestServer server, Account account, string code, DateTimeOffset published, params Item[] files) + { + var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex()); + var added = await server.Db.Entries.AddAsync( + Make.Entry(account.Id, code, published), + [.. files.Select((f, i) => f.Kind == MediaKind.Video ? Make.Video(i + 1) : Make.Photo(i + 1))]); + foreach (var (media, file) in added.Stored.Media.Zip(files)) + { + await ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension }); + } + + await ingest.AppendJournalAsync(added.Stored.Entry.Id); + return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + } + + /// The library file of a media of . + public static string PathOf(WebTestServer server, Account account, Media media) => + Path.Combine(server.Library.Layout.AccountFolder(account), LibraryLayout.ToPlatform(media.RelativePath!)); + + public static object Destination(string path, string scope = "general", long? accountId = null, string? photoFormat = null, string? videoFormat = null) => new + { + scope, + accountId, + path, + label = (string?)null, + types = new[] { "postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo" }, + namingScheme = (string?)null, + highlightNamingScheme = (string?)null, + profileNamingScheme = (string?)null, + photoFormat, + videoFormat, + }; + + public static async Task StartAndWaitAsync(WebTestServer server, object request) + { + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", request); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + Assert.IsNotEmpty(job.Items("runIds").ToList(), job.ToString()); + await WaitIdleAsync(server); + } + + public static Task WaitIdleAsync(WebTestServer server) => + WaitAsync(async () => !(await server.GetJsonAsync("/api/export/progress")).Bool("running"), "the copy ends"); + + public static async Task WaitAsync(Func> condition, string what) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + while (!await condition()) + { + if (watch.Elapsed > TimeSpan.FromSeconds(60)) + { + Assert.Fail($"not reached: {what}"); + } + + await Task.Delay(50); + } + } +} diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.Formats.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.Formats.cs new file mode 100644 index 0000000..a2f95d7 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.Formats.cs @@ -0,0 +1,433 @@ +using System.Globalization; +using Febe.Core.Domain; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// Tappa E3 in a real browser, on the demo (spec §4.10, §10.3): the formats of Impostazioni → Esportazione and of the +/// dialog of a folder («con perdita» under JPG), the question of the conversion of the library with «Solo i nuovi» first, +/// «Copia in…» with «Formato: come la destinazione · Cambia», «Fotogrammi…» from the viewer (opened at the player's +/// time, with its previews) and from a selection (the photos are skipped and the dialog says so), the copy rows of the +/// viewer with their form, the converted file of the library and the deletion that counts it. What the pages should say +/// is asked of the API, never assumed from how the demo is built (it places its entries by the hour, #72). +/// +public sealed partial class ExportInterfaceTests +{ + /// A GET of the API from the page, as JSON. + private static string Get(string path) => $"fetch({Js(path)}, {{ headers: {{ Accept: 'application/json' }} }}).then((r) => r.json())"; + + /// A POST of the API from the page (a command of Febe's own page), as JSON. + private static string Post(string path, string json) => + $"fetch({Js(path)}, {{ method: 'POST', headers: {{ 'Content-Type': 'application/json', Accept: 'application/json' }}, body: {Js(json)} }}).then((r) => r.json())"; + + /// The choice of one format (photo or video) inside a scope. + private static string FormatChoice(string scope, string kind) => $"document.querySelector({Js(scope + " .scelta-formato[data-tipo=" + kind + "]")})"; + + /// The value checked in a choice of format. + private static string Checked(string choice) => $"{choice}.querySelector('[role=radio][aria-checked=true]').dataset.value"; + + [TestMethod] + public async Task FormatsAreChosenInTheSettingsAndJpgSaysItLoses() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-formati-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await RecordNoticesAsync(ui); + + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + var photo = FormatChoice(".sezione-formati", "photo"); + var video = FormatChoice(".sezione-formati", "video"); + await ui.WaitAsync($"{photo} !== null && {video} !== null", "i formati delle copie " + ui.Report()); + CollectionAssert.AreEqual(new[] { "Originale", "JPG", "PNG", "WEBP senza perdita" }, await ui.EvalAsync($"[...{photo}.querySelectorAll('[role=radio]')].map((b) => b.textContent.trim())")); + CollectionAssert.AreEqual(new[] { "Originale", "MP4" }, await ui.EvalAsync($"[...{video}.querySelectorAll('[role=radio]')].map((b) => b.textContent.trim())")); + Assert.AreEqual("original", (await ui.EvalAsync(Checked(photo))).GetString()); + Assert.IsTrue((await ui.EvalAsync($"{photo}.querySelector('.nota-formato').hidden")).GetBoolean(), "«Originale» needs no note"); + + // JPG: saved at once, with the note of the loss; MP4 says it only remuxes. + await ui.EvalAsync($"{photo}.querySelector('[data-value=jpg]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.photoFormat === 'jpg')", "JPG sul server"); + Assert.IsFalse((await ui.EvalAsync($"{photo}.querySelector('.nota-formato').hidden")).GetBoolean()); + Assert.AreEqual("con perdita: qualità 92", (await ui.EvalAsync($"{photo}.querySelector('.nota-formato').textContent")).GetString()); + await ui.EvalAsync($"{video}.querySelector('[data-value=mp4]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.videoFormat === 'mp4')", "MP4 sul server"); + Assert.AreEqual("solo rimuxaggio, mai ricodifica", (await ui.EvalAsync($"{video}.querySelector('.nota-formato').textContent")).GetString()); + await ui.WaitAsync("window.__notices.length >= 2", "gli avvisi brevi del salvataggio"); + Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), (await ui.EvalAsync("JSON.stringify(window.__notices)")).GetString()); + + // The page drawn again shows what is saved; «Originale» again takes the note away. + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + await ui.WaitAsync($"{photo} !== null && {Checked(photo)} === 'jpg' && {Checked(video)} === 'mp4'", "i formati salvati dopo il ricaricamento"); + await ui.EvalAsync($"{photo}.querySelector('[data-value=original]').click()"); + await ui.EvalAsync($"{video}.querySelector('[data-value=original]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.photoFormat === 'original' && j.videoFormat === 'original')", "di nuovo «Originale»"); + Assert.IsTrue((await ui.EvalAsync($"{photo}.querySelector('.nota-formato').hidden && {video}.querySelector('.nota-formato').hidden")).GetBoolean()); + } + + [TestMethod] + public async Task TurningOnTheLibraryConversionAsksAboutTheFilesAlreadyThere() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-conversione-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await RecordNoticesAsync(ui); + + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + var photo = FormatChoice(".sezione-conversione", "photo"); + await ui.WaitAsync($"{photo} !== null && document.querySelector('.stato-conversione .riga-conteggi') !== null", "la conversione della libreria " + ui.Report()); + var before = await ui.EvalAsync(Get("/api/export/library-conversion")); + Assert.IsFalse(before.GetProperty("on").GetBoolean()); + // The demo has its two rows («Convertito», «Non si converte») and never converts: the line says so. + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.stato-conversione').textContent")).GetString(), before.GetProperty("text").GetString()); + + // PNG: the question, with the count and the space of the files already there, «Solo i nuovi» first and focused. + var preview = await ui.EvalAsync(Get("/api/export/library-conversion/preview?photo=png")); + var files = preview.GetProperty("files").GetInt32(); + Assert.IsGreaterThan(1, files, "the demo has photos that would convert to PNG"); + const string Question = "[...document.querySelectorAll('.dialogo.piccolo')].find((d) => d.querySelector('.spazio-conversione'))"; + await ui.EvalAsync($"{photo}.querySelector('[data-value=png]').click()"); + await ui.WaitAsync($"({Question}) !== undefined", "la domanda"); + Assert.AreEqual( + $"Convertire anche i {files.ToString("N0", CultureInfo.GetCultureInfo("it-IT"))} file già in libreria?", + (await ui.EvalAsync($"({Question}).querySelector('h2').textContent")).GetString()); + StringAssert.StartsWith((await ui.EvalAsync($"({Question}).querySelector('.spazio-conversione').textContent")).GetString(), "Gli originali occupano circa"); + CollectionAssert.AreEqual( + new[] { $"Anche i {files.ToString("N0", CultureInfo.GetCultureInfo("it-IT"))} già in libreria", "Solo i nuovi" }, + await ui.EvalAsync($"[...({Question}).querySelectorAll('footer button')].map((b) => b.textContent.trim())")); + Assert.IsTrue((await ui.EvalAsync($"({Question}).querySelector('footer .btn.primo').textContent === 'Solo i nuovi'")).GetBoolean(), "«Solo i nuovi» is the primary answer"); + + // Closed without an answer: nothing changes, and the control goes back. + await ui.EvalAsync($"({Question}).querySelector('header button').click()"); + await ui.WaitAsync($"({Question}) === undefined && {Checked(photo)} === 'original'", "la domanda chiusa, il controllo com'era"); + Assert.AreEqual("original", (await ui.EvalAsync(Get("/api/export"))).GetProperty("libraryPhotoFormat").GetString()); + + // «Solo i nuovi»: on, and nothing already in the library is queued. + await ui.EvalAsync($"{photo}.querySelector('[data-value=png]').click()"); + await ui.WaitAsync($"({Question}) !== undefined", "la domanda di nuovo"); + await ui.EvalAsync($"({Question}).querySelector('footer .btn.primo').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.libraryPhotoFormat === 'png' && j.libraryConversion.on)", "PNG sul server"); + var on = await ui.EvalAsync(Get("/api/export/library-conversion")); + Assert.AreEqual(before.GetProperty("pending").GetInt32(), on.GetProperty("pending").GetInt32(), "«Solo i nuovi» queues none of the files already there"); + await ui.WaitAsync($"document.querySelector('.stato-conversione').textContent.includes({Js(on.GetProperty("text").GetString()!)})", "la riga dello stato"); + + // «Interrompi» and «Riprendi». + Assert.IsTrue((await ui.EvalAsync(ClickText(".stato-conversione", "button", "Interrompi"))).GetBoolean(), "«Interrompi» while it is on"); + await ui.WaitAsync($"{Get("/api/export/library-conversion")}.then((j) => j.paused)", "interrotta sul server"); + await ui.WaitAsync("[...document.querySelectorAll('.stato-conversione button')].some((b) => b.textContent.includes('Riprendi'))", "«Riprendi»"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".stato-conversione", "button", "Riprendi"))).GetBoolean()); + await ui.WaitAsync($"{Get("/api/export/library-conversion")}.then((j) => !j.paused)", "ripresa sul server"); + + // Back to «Originale»: no question. + await ui.EvalAsync($"{photo}.querySelector('[data-value=original]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.libraryPhotoFormat === 'original' && !j.libraryConversion.on)", "spenta sul server"); + Assert.IsTrue((await ui.EvalAsync($"({Question}) === undefined")).GetBoolean(), "turning it off asks nothing"); + Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), (await ui.EvalAsync("JSON.stringify(window.__notices)")).GetString()); + } + + [TestMethod] + public async Task TheDestinationDialogHasItsFormats() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-dialogo-formati-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=docker")); + await ui.WaitAsync($"({General}) !== ''", "la cartella generale"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".cartella-impostazioni", "button", "Modifica"))).GetBoolean()); + const string Dialog = "document.querySelector('.dialogo.destinazione')"; + var photo = FormatChoice(".dialogo.destinazione .parte-formati", "photo"); + var video = FormatChoice(".dialogo.destinazione .parte-formati", "video"); + await ui.WaitAsync($"{photo} !== null && /liberi/.test({Dialog}.querySelector('.controllo-cartella').textContent)", "il dialogo con i formati"); + Assert.AreEqual("Formati", (await ui.EvalAsync($"{Dialog}.querySelector('.parte-formati h3').textContent")).GetString()); + CollectionAssert.AreEqual( + new[] { "Come le impostazioni generali", "Originale", "JPG", "PNG", "WEBP senza perdita" }, + await ui.EvalAsync($"[...{photo}.querySelectorAll('[role=radio]')].map((b) => b.textContent.trim())")); + Assert.AreEqual("general", (await ui.EvalAsync(Checked(photo))).GetString(), "a folder without formats of its own follows the settings"); + Assert.AreEqual("general", (await ui.EvalAsync(Checked(video))).GetString()); + + // JPG for the photos of this folder: the note, then «Salva» stores it. + await ui.EvalAsync($"{photo}.querySelector('[data-value=jpg]').click()"); + Assert.AreEqual("con perdita: qualità 92", (await ui.EvalAsync($"{photo}.querySelector('.nota-formato').textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync(ClickText(".dialogo.destinazione", "footer button", "Salva"))).GetBoolean()); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude " + ui.Report()); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.general.photoFormat === 'jpg' && j.general.videoFormat === null)", "il formato della cartella sul server"); + + // Open again: JPG is chosen; back to «Come le impostazioni generali». + Assert.IsTrue((await ui.EvalAsync(ClickText(".cartella-impostazioni", "button", "Modifica"))).GetBoolean()); + await ui.WaitAsync($"{photo} !== null && {Checked(photo)} === 'jpg' && /liberi/.test({Dialog}.querySelector('.controllo-cartella').textContent)", "JPG scelto alla riapertura"); + await ui.EvalAsync($"{photo}.querySelector('[data-value=general]').click()"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".dialogo.destinazione", "footer button", "Salva"))).GetBoolean()); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.general.photoFormat === null)", "di nuovo come le impostazioni generali"); + } + + [TestMethod] + public async Task CopyInChangesTheFormatAndTheSummaryFollowsThePlan() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-copia-formati-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico"); + var marta = (await ui.EvalAsync($"{Get("/api/accounts")}.then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64(); + await ui.OpenAsync(new Uri(demo.Address, $"/libreria?copie=non-copiati&account={marta}")); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 1 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico dei non ancora copiati"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean()); + var ids = (await ui.EvalAsync("(() => { const tiles = [...document.querySelectorAll('.mosaico .tess')].slice(0, 4); tiles.forEach((t) => t.click()); return JSON.stringify(tiles.map((t) => Number(t.dataset.id))); })()")).GetString()!; + const string CopyIn = "[...document.querySelectorAll('.salva button')].find((b) => b.textContent.includes('Copia in'))"; + await ui.WaitAsync($"({CopyIn}) && !({CopyIn}).disabled", "«Copia in…»"); + await ui.EvalAsync($"({CopyIn}).click()"); + + const string Dialog = "document.querySelector('.dialogo.copia-in')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-copia') != null", "il riepilogo"); + Assert.AreEqual("Formato: come la destinazione", (await ui.EvalAsync($"{Dialog}.querySelector('.riga-formato .testo-formato').textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.riga-formato .formati-copie').hidden")).GetBoolean(), "the controls open with «Cambia»"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".dialogo.copia-in .riga-formato", "button", "Cambia"))).GetBoolean()); + await ui.WaitAsync($"!{Dialog}.querySelector('.riga-formato .formati-copie').hidden", "i formati di questa copia"); + var photo = FormatChoice(".dialogo.copia-in .riga-formato", "photo"); + Assert.AreEqual("Come la destinazione", (await ui.EvalAsync($"{photo}.querySelector('[role=radio]').textContent.trim()")).GetString()); + Assert.AreEqual("destination", (await ui.EvalAsync(Checked(photo))).GetString()); + + // Each format asks the plan again: the summary and the button say what the plan of that format says. + foreach (var format in new[] { "png", "jpg" }) + { + await ui.EvalAsync($"{photo}.querySelector('[data-value={format}]').click()"); + var label = format == "png" ? "PNG" : "JPG"; + Assert.AreEqual($"Formato: foto {label} · video come la destinazione", (await ui.EvalAsync($"{Dialog}.querySelector('.riga-formato .testo-formato').textContent")).GetString()); + var plan = await ui.EvalAsync(Post("/api/export/plan", $"{{ \"entryIds\": {ids}, \"copyAgain\": false, \"photoFormat\": \"{format}\" }}")); + var files = plan.GetProperty("files").GetInt32(); + var lossy = plan.GetProperty("lossy").GetBoolean(); + await ui.WaitAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim() === {Js($"Copia {files} file")} && !{Dialog}.querySelector('footer .btn.primo').disabled", $"il pulsante del piano in {label}"); + var summary = (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()!; + StringAssert.StartsWith(summary, $"{files} file", summary); + Assert.AreEqual(lossy, summary.Contains("con perdita", StringComparison.Ordinal), $"{label}: {summary}"); + foreach (var asIs in plan.GetProperty("asIs").EnumerateArray().Where(a => a.GetProperty("files").GetInt32() > 0)) + { + StringAssert.Contains(summary, asIs.GetProperty("label").GetString(), summary); + } + } + + // JPG has its note of the loss here too; «Annulla» leaves nothing behind. + Assert.AreEqual("con perdita: qualità 92", (await ui.EvalAsync($"{photo}.querySelector('.nota-formato').textContent")).GetString()); + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + } + + [TestMethod] + public async Task TheFrameDialogOfTheViewerOpensAtThePlayerTimeAndPreviews() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-fotogramma-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + var video = (await DemoCopyAsync(demo, ExportVariant.Frame)).MediaId!.Value; + await OpenInViewerAsync(ui, demo, video, "docker"); + await ui.WaitAsync("document.querySelector('.vis .azione-fotogramma') !== null && document.querySelector('.vis video') !== null", "«Fotogramma» nel visualizzatore " + ui.Report()); + + // The player is at 1,3 s: the dialog opens there, the video waits. + await ui.EvalAsync("Object.defineProperty(document.querySelector('.vis video'), 'currentTime', { configurable: true, get: () => 1.3, set: () => {} })"); + await ui.EvalAsync("document.querySelector('.vis .azione-fotogramma').click()"); + const string Dialog = "document.querySelector('.dialogo.fotogrammi')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.dati-video') != null", "il dialogo «Fotogrammi»"); + Assert.AreEqual("Fotogrammi", (await ui.EvalAsync($"{Dialog}.querySelector('h2').textContent")).GetString()); + var info = await ui.EvalAsync(Get($"/api/media/{video}/frames/info")); + var data = (await ui.EvalAsync($"{Dialog}.querySelector('.dati-video').textContent")).GetString()!; + StringAssert.StartsWith(data, "Video di 0:0", data); + StringAssert.EndsWith(data, $", {info.GetProperty("width").GetInt32()} × {info.GetProperty("height").GetInt32()} pixel.", data); + Assert.AreEqual("0:01,3", (await ui.EvalAsync($"{Dialog}.querySelector('.campo-tempo input').value")).GetString()); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis video').paused")).GetBoolean(), "the video waits while the dialog is open"); + + // The preview of that instant, and the instant really shown (asked of the API). + var shown = (await ui.EvalAsync(Get($"/api/media/{video}/frames/instants?mode=istante&at=1300"))).GetProperty("instants")[0].GetProperty("label").GetString(); + await ui.WaitAsync($"{Dialog}.querySelector('.istante-mostrato').textContent === {Js($"Fotogramma a {shown}")}", "l'istante mostrato"); + await ui.WaitAsync($"(() => {{ const i = {Dialog}.querySelector('.anteprima-fotogramma img'); return i && i.complete && i.naturalWidth > 0; }})()", "l'anteprima " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync($"Math.max({Dialog}.querySelector('.anteprima-fotogramma img').naturalWidth, {Dialog}.querySelector('.anteprima-fotogramma img').naturalHeight) <= 480")).GetBoolean(), "a preview is at most 480 pixels"); + Assert.AreEqual("Il fotogramma non ha l'audio.", (await ui.EvalAsync($"{Dialog}.querySelector('.nota-audio').textContent.trim()")).GetString()); + + // Above the viewer (its own layer): the middle of the dialog is the dialog. + Assert.IsTrue((await ui.EvalAsync($"(() => {{ const r = {Dialog}.getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return e !== null && e.closest('.dialogo.fotogrammi') !== null; }})()")).GetBoolean(), "the dialog is above the viewer"); + + // «N in tutto» with 8: the strip shows the first 6 at the instants of the API, and «e altri 2». + await ui.EvalAsync($"{Dialog}.querySelector('.modo-fotogrammi').previousElementSibling.querySelector('[data-value=numero]').click()"); + await ui.EvalAsync($"(() => {{ const i = {Dialog}.querySelector('input[type=number]'); i.value = '8'; i.dispatchEvent(new Event('input', {{ bubbles: true }})); }})()"); + var labels = (await ui.EvalAsync(Get($"/api/media/{video}/frames/instants?mode=numero&count=8"))).GetProperty("instants").EnumerateArray().Take(6).Select(i => i.GetProperty("label").GetString()!).ToArray(); + await ui.WaitAsync($"{Dialog}.querySelector('.altri-fotogrammi')?.textContent === 'e altri 2'", "la striscia con «e altri 2»"); + CollectionAssert.AreEqual(labels, await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.striscia-fotogrammi figcaption')].map((c) => c.textContent)")); + + // JPG says it loses; the summary of «Scarica» is the one of the API. + Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').hidden")).GetBoolean(), "PNG is the default, without loss"); + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('[role=radio][data-value=jpg]')].pop().click()"); + Assert.IsFalse((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').hidden")).GetBoolean()); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').textContent")).GetString(), "con perdita: qualità 92"); + var plan = await ui.EvalAsync(Post("/api/frames/plan", $"{{ \"mediaIds\": [{video}], \"frames\": {{ \"mode\": \"numero\", \"count\": 8, \"format\": \"jpg\" }} }}")); + var frames = plan.GetProperty("frames").GetInt32(); + await ui.WaitAsync($"{Dialog}.querySelector('.riepilogo-fotogrammi .riepilogo-copia')?.textContent === {Js(plan.GetProperty("summary").GetString()!)}", "il riepilogo di «Scarica»"); + await ui.WaitAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim() === {Js($"Scarica {frames} fotogrammi")} && !{Dialog}.querySelector('footer .btn.primo').disabled", "il pulsante «Scarica»"); + + // «Nella cartella delle copie»: the plan of the copies, and the button says «Copia». + await ui.EvalAsync($"{Dialog}.querySelector('input[type=radio][value=cartella]').click()"); + var copies = await ui.EvalAsync(Post("/api/export/plan", $"{{ \"mediaIds\": [{video}], \"frames\": {{ \"mode\": \"numero\", \"count\": 8, \"format\": \"jpg\" }} }}")); + await ui.WaitAsync($"{Dialog}.querySelector('.riepilogo-fotogrammi .riepilogo-copia')?.textContent.startsWith({Js(copies.GetProperty("summary").GetString()!)})", "il riepilogo della cartella delle copie"); + await ui.WaitAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim() === {Js($"Copia {copies.GetProperty("frames").GetInt32()} fotogrammi")}", "il pulsante «Copia»"); + + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null && document.querySelector('.vis') !== null", "il dialogo si chiude, il visualizzatore resta"); + } + + [TestMethod] + public async Task TheFrameDialogOfASelectionSkipsThePhotos() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-fotogrammi-scelta-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico"); + var marta = (await ui.EvalAsync($"{Get("/api/accounts")}.then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64(); + await ui.OpenAsync(new Uri(demo.Address, $"/libreria?account={marta}")); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 4 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico di marta.demo"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean()); + + // Two entries with a video and two with photos only, among the tiles on screen (their kinds asked of the API). + var ids = (await ui.EvalAsync( + $"(async () => {{ const j = await ({Get($"/api/library?accounts={marta}&limit=1000")}); const kinds = new Map(j.tiles.map((t) => [t.id, t.cover && t.cover.kind])); " + + "const tiles = [...document.querySelectorAll('.mosaico .tess')]; const videos = tiles.filter((t) => kinds.get(Number(t.dataset.id)) === 'video').slice(0, 2); " + + "const photos = tiles.filter((t) => kinds.get(Number(t.dataset.id)) === 'photo').slice(0, 2); const chosen = [...videos, ...photos]; " + + "chosen.forEach((t) => t.click()); return JSON.stringify(chosen.map((t) => Number(t.dataset.id))); })()")).GetString()!; + var plan = await ui.EvalAsync(Post("/api/frames/plan", $"{{ \"entryIds\": {ids}, \"frames\": {{ \"mode\": \"istante\", \"atMs\": 0, \"format\": \"png\" }} }}")); + Assert.IsGreaterThan(0, plan.GetProperty("photosSkipped").GetInt32(), $"{ids}: {plan}"); + Assert.IsGreaterThan(0, plan.GetProperty("videos").GetInt32(), $"{ids}: {plan}"); + + const string Frames = "document.querySelector('.salva .fotogrammi-selezione')"; + await ui.WaitAsync($"{Frames} && !{Frames}.disabled", "«Fotogrammi…» nella barra della scelta"); + Assert.AreEqual("Fotogrammi…", (await ui.EvalAsync($"{Frames}.textContent.trim()")).GetString()); + await ui.EvalAsync($"{Frames}.click()"); + const string Dialog = "document.querySelector('.dialogo.fotogrammi')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-fotogrammi .riepilogo-copia') != null", "il dialogo della scelta " + ui.Report()); + Assert.AreEqual("Fotogrammi dei video scelti", (await ui.EvalAsync($"{Dialog}.querySelector('h2').textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.anteprima-fotogramma') === null")).GetBoolean(), "no preview: there is no single video"); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.modo-fotogrammi').textContent")).GetString(), "Lo stesso istante in ogni video"); + await ui.WaitAsync($"{Dialog}.querySelector('.riepilogo-fotogrammi .riepilogo-copia').textContent === {Js(plan.GetProperty("summary").GetString()!)}", "il riepilogo dell'API"); + StringAssert.Contains(plan.GetProperty("summary").GetString(), "si salt", "the summary says the photos are skipped"); + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + + // The account tab has «Fotogrammi…» in its selection bar too. + await ui.OpenAsync(new Uri(demo.Address, $"/account/{marta}")); + await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null && [...document.querySelectorAll('.btn')].some((b) => b.textContent.includes('Seleziona'))", "i contenuti dell'account"); + await ui.EvalAsync("[...document.querySelectorAll('.btn')].find((b) => b.textContent.includes('Seleziona')).click()"); + await ui.EvalAsync("document.querySelector('.mosaico .tess').click()"); + await ui.WaitAsync($"{Frames} && !{Frames}.disabled", "«Fotogrammi…» nella scheda dell'account"); + } + + [TestMethod] + public async Task TheViewerSaysTheFormOfEachCopyAndShowsTheConvertedFile() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-righe-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // The frame of a video: «· fotogramma a 0:01,125 · PNG». + var frame = await DemoCopyAsync(demo, ExportVariant.Frame); + await OpenInViewerAsync(ui, demo, frame.MediaId!.Value, "docker"); + await ui.WaitAsync("[...document.querySelectorAll('.vis .riga-copia')].some((r) => r.textContent.includes('fotogramma'))", "la riga del fotogramma " + ui.Report()); + var rows = await ui.EvalAsync("[...document.querySelectorAll('.vis .riga-copia')].map((r) => r.querySelector('span').textContent)"); + Assert.IsTrue(rows.Any(r => r.StartsWith("Copiato in Disco USB il ", StringComparison.Ordinal) && r.EndsWith(" · fotogramma a 0:01,125 · PNG", StringComparison.Ordinal)), string.Join(" | ", rows)); + await CloseViewerAsync(ui); + + // A copy converted to PNG: «· PNG»; a whole one: «· intero». + var converted = await DemoCopyAsync(demo, ExportVariant.Converted); + await OpenInViewerAsync(ui, demo, converted.MediaId!.Value, "docker"); + await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "la riga della copia convertita"); + rows = await ui.EvalAsync("[...document.querySelectorAll('.vis .riga-copia')].map((r) => r.querySelector('span').textContent)"); + Assert.IsTrue(rows.Any(r => r.StartsWith("Copiato in Disco USB il ", StringComparison.Ordinal) && r.EndsWith(" · PNG", StringComparison.Ordinal)), string.Join(" | ", rows)); + await CloseViewerAsync(ui); + var whole = await DemoCopyAsync(demo, ExportVariant.Whole); + await OpenInViewerAsync(ui, demo, whole.MediaId!.Value, "docker"); + await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "la riga della copia intera"); + rows = await ui.EvalAsync("[...document.querySelectorAll('.vis .riga-copia')].map((r) => r.querySelector('span').textContent)"); + Assert.IsTrue(rows.Any(r => r.StartsWith("Copiato in Disco USB il ", StringComparison.Ordinal) && r.EndsWith(" · intero", StringComparison.Ordinal)), string.Join(" | ", rows)); + await CloseViewerAsync(ui); + + // The converted file of the library next to its original, with «Scarica» in Docker; the deletion counts it. + var conversionId = demo.World.ConversionFiles.Single().Key; + var conversion = await demo.Storage.Conversions.GetAsync(conversionId); + await OpenInViewerAsync(ui, demo, conversion!.MediaId, "docker"); + await ui.WaitAsync("document.querySelector('.vis .riga-conversione') !== null", "la riga del file convertito " + ui.Report()); + StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.vis .riga-conversione span').textContent")).GetString(), "Convertito in PNG · "); + Assert.AreEqual($"/api/conversions/{conversionId}/file", (await ui.EvalAsync("new URL(document.querySelector('.vis .riga-conversione a').href).pathname")).GetString()); + Assert.AreEqual("Scarica", (await ui.EvalAsync("document.querySelector('.vis .riga-conversione a').textContent.trim()")).GetString()); + Assert.AreEqual("Convertito", (await ui.EvalAsync("document.querySelector('.vis .riga-conversione').previousElementSibling.textContent")).GetString()); + + Assert.IsTrue((await ui.EvalAsync("(() => { const b = [...document.querySelectorAll('.vis button')].find((x) => x.textContent.includes('Elimina dalla libreria')); if (!b) return false; b.click(); return true; })()")).GetBoolean()); + const string Confirm = "[...document.querySelectorAll('.dialogo.piccolo')].pop()"; + // One file of an entry of several says the whole entry goes, converted file included; otherwise its own line. + await ui.WaitAsync($"({Confirm})?.querySelector('.contenuto').textContent.includes('1 file convertito')", "la conferma conta il file convertito " + ui.Report()); + if ((await ui.EvalAsync($"({Confirm}).querySelector('.conta-convertiti') !== null")).GetBoolean()) + { + Assert.AreEqual( + "Si cancella anche 1 file convertito della libreria, fatto da questi file.", + (await ui.EvalAsync($"({Confirm}).querySelector('.conta-convertiti').textContent")).GetString()); + } + else + { + StringAssert.Contains((await ui.EvalAsync($"({Confirm}).querySelector('.contenuto').textContent")).GetString(), "e 1 file convertito."); + } + await ui.EvalAsync($"[...({Confirm}).querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.piccolo') === null && document.querySelector('.vis') !== null", "annullato: nulla si cancella"); + Assert.AreEqual(MediaConversionState.Converted, (await demo.Storage.Conversions.GetAsync(conversionId))!.State); + } + + // ------------------------------------------------------------------------------------------------- support + + /// A copy «Copiato» of the demo of a form (of @marta.demo, in its general folder). + private static async Task DemoCopyAsync(DemoHost demo, ExportVariant variant) + { + foreach (var destination in await demo.Storage.Exports.ListDestinationsAsync(includeRetired: false)) + { + var found = (await demo.Storage.Exports.ListCopiesAsync(destination.Id, ExportCopyState.Copied, 0, 100_000)) + .Where(c => c.Variant == variant && c.MediaId is not null) + .OrderBy(c => c.Id) + .ToList(); + foreach (var copy in found) + { + // A file on disk, whose kind is the one of the form (the demo shares a picture's bytes with a video). + var media = await demo.Storage.Media.GetAsync(copy.MediaId!.Value); + if (media is { RelativePath: not null } && EntryStateRules.IsPresent(media.State) && (variant != ExportVariant.Whole || media.Kind == MediaKind.Photo)) + { + return copy; + } + } + } + + Assert.Fail($"the demo has no copy {variant}"); + return null!; + } + + /// + /// Opens the viewer on one file: the Libreria of its account on its day, «Tutte le foto», its tile (the mosaic shows a + /// window of tiles, so a file far down would not be on screen in the whole library). + /// + private static async Task OpenInViewerAsync(UiBrowser ui, DemoHost demo, long mediaId, string look) + { + var media = await demo.Storage.Media.GetAsync(mediaId); + var entry = await demo.Storage.Entries.GetAsync(media!.EntryId); + var day = LocalCalendar.Today(entry!.PublishedAt, demo.World.Zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + await ui.OpenAsync(new Uri(demo.Address, $"/libreria?account={entry.AccountId}&dal={day}&al={day}&veste={look}")); + await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]') !== null && document.querySelector('.mosaico .tess') !== null", "la Libreria del giorno " + ui.Report()); + await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()"); + var tile = $"document.querySelector('.mosaico .tess[data-id=\"{mediaId}\"]')"; + await ui.WaitAsync($"document.querySelector('.strumenti .modo-mosaico [aria-checked=true]').dataset.value === 'files' && {tile} !== null", "la tessera del file " + ui.Report()); + await ui.EvalAsync($"{tile}.click()"); + await ui.WaitAsync("document.querySelector('.vis .scheda') !== null", "il visualizzatore"); + } + + private static async Task CloseViewerAsync(UiBrowser ui) + { + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))"); + await ui.WaitAsync("document.querySelector('.vis') === null", "Esc chiude il visualizzatore"); + } +} diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.cs index cd8aa56..fdf942c 100644 --- a/tests/Febe.Tests/Web/ExportInterfaceTests.cs +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.cs @@ -10,10 +10,11 @@ namespace Febe.Tests.Web; /// types, the preview of the names), the block «Copie esterne» of an account whose switch acts at once, «Copia in…» from /// the selection with its summary and the toast that leads to the Dashboard, the «Copie» filter in the address with the /// marks of the tiles and the menu of the CSV icon, the rows «Copia» of the viewer with «Copia di nuovo», and the -/// Dashboard tab «Esportazione». Chromium only (CI); the selectors follow the pages of WP3, checked on the demo. +/// Dashboard tab «Esportazione». Chromium only (CI); the selectors follow the pages of WP3, checked on the demo. Tappa +/// E3 (formats, frames, the conversion of the library) is in ExportInterfaceTests.Formats.cs. /// [TestClass] -public sealed class ExportInterfaceTests +public sealed partial class ExportInterfaceTests { /// The demo copies its general folder to «Disco USB», under /esporta in the Docker look. private const string General = "document.querySelector('.cartella-impostazioni .val')?.textContent || ''"; @@ -80,7 +81,7 @@ public sealed class ExportInterfaceTests StringAssert.Contains(notes, "sottocartelle di /esporta", "la nota di Docker"); StringAssert.Contains(notes, "da riprendere", "il lavoro interrotto della demo"); CollectionAssert.AreEqual( - new[] { "Esportazione", "Cartella generale", "Lo stesso post in due account", "Cartelle degli account" }, + new[] { "Esportazione", "Cartella generale", "Formati delle copie", "Lo stesso post in due account", "Cartelle degli account", "Conversione della libreria" }, (await ui.EvalAsync("[...document.querySelectorAll('.sezione h2')].map((x) => x.textContent)"))); StringAssert.Contains((await ui.EvalAsync("document.querySelector('.stato-copie')?.textContent || ''")).GetString(), "copiati", "i conteggi della cartella"); Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.stato-copie button')].some((b) => b.textContent.includes('Controlla le copie'))")).GetBoolean(), "«Controlla le copie»"); @@ -304,8 +305,11 @@ public sealed class ExportInterfaceTests await ui.WaitAsync($"{tile} !== null", "la tessera del file"); await ui.EvalAsync($"{tile}.click()"); - await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "le righe «Copia» del visualizzatore " + ui.Report()); - var row = (await ui.EvalAsync("document.querySelector('.vis .riga-copia').textContent")).GetString()!; + // The file may also have copies of other forms (a frame of the demo, «Copiato»), so the rows are many and their + // order depends on the demo: the one «Tolto» or «Superato» is looked for among them. + const string Gone = "[...document.querySelectorAll('.vis .riga-copia')].find((r) => r.textContent.startsWith('Tolto da Disco USB') || r.textContent.startsWith('Superato in Disco USB'))"; + await ui.WaitAsync($"document.querySelector('.vis .riga-copia') !== null && ({Gone}) !== undefined", "la riga «Tolto» o «Superato» del visualizzatore " + ui.Report()); + var row = (await ui.EvalAsync($"({Gone}).textContent")).GetString()!; Assert.IsTrue(row.StartsWith("Tolto da Disco USB", StringComparison.Ordinal) || row.StartsWith("Superato in Disco USB", StringComparison.Ordinal), row); Assert.AreEqual("Copia", (await ui.EvalAsync("document.querySelector('.vis .riga-copia').previousElementSibling.textContent")).GetString()); Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.vis button')].some((b) => b.textContent.trim() === 'Copia in…')")).GetBoolean(), "«Copia in…» in fondo al pannello"); @@ -314,7 +318,7 @@ public sealed class ExportInterfaceTests const string Replaced = "fetch('/api/library?mode=files&copies=removedOrSuperseded&limit=1000').then((r) => r.json()).then((j) => j.tiles.length)"; var before = (await ui.EvalAsync(Replaced)).GetInt32(); Assert.IsGreaterThan(0, before); - await ui.EvalAsync("document.querySelector('.vis .riga-copia .copia-di-nuovo').click()"); + await ui.EvalAsync($"({Gone}).querySelector('.copia-di-nuovo').click()"); // The notice lasts 8 s: it is looked for among those shown. await ui.WaitAsync("window.__notices.some((n) => n.href !== null && !n.kind.includes('errore'))", "l'avviso breve del lavoro"); StringAssert.Contains((await ui.EvalAsync("window.__notices.findLast((n) => n.href !== null).text")).GetString(), "Copia avviata"); @@ -340,7 +344,7 @@ public sealed class ExportInterfaceTests await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .riga-riprendi') !== null", "la linguetta «Esportazione»"); Assert.AreEqual("Esportazione", (await ui.EvalAsync("document.querySelector('.linguette-dashboard a.qui').textContent")).GetString()); - CollectionAssert.AreEqual(new[] { "In corso", "Da riprendere", "Ultimi lavori" }, await ui.EvalAsync("[...document.querySelectorAll('.esportazione-dashboard h2')].map((x) => x.textContent)")); + CollectionAssert.AreEqual(new[] { "In corso", "Da riprendere", "Conversione della libreria", "Ultimi lavori" }, await ui.EvalAsync("[...document.querySelectorAll('.esportazione-dashboard h2')].map((x) => x.textContent)")); StringAssert.Contains((await ui.EvalAsync("document.querySelector('.copia-in-corso').textContent")).GetString(), "Nessuna copia al lavoro"); StringAssert.Contains((await ui.EvalAsync("document.querySelector('.riga-riprendi').textContent")).GetString(), "interrotta"); diff --git a/tests/Febe.Tests/Web/FrameServiceTests.cs b/tests/Febe.Tests/Web/FrameServiceTests.cs new file mode 100644 index 0000000..b2cae0f --- /dev/null +++ b/tests/Febe.Tests/Web/FrameServiceTests.cs @@ -0,0 +1,290 @@ +using System.IO.Compression; +using Febe.Core.Codecs.H264; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Tests.Support; +using Febe.Web.Export; + +namespace Febe.Tests.Web; + +/// +/// The zip of «Scarica» of frames (tappa E3, D14): written while it is sent, through asynchronous writes only (a +/// response body refuses synchronous ones), one entry per frame under the account folder, names made unique. +/// +[TestClass] +public sealed class FrameServiceTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheZipIsWrittenThroughAsynchronousWritesOnly() + { + using var temp = new TempFolder("fotogrammi-zip"); + var path = temp.Combine("video.mp4"); + await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), TestContext.CancellationToken); + var clock = new ManualClock(Make.T0); + var service = new FrameService(clock); + var instants = new[] { TimeSpan.Zero, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1.5) }; + var plan = new FrameDownloadPlan(FrameMode.Count, ExportFormat.Png, [ + new FrameDownloadVideo("marta.demo", path, "post", instants, Make.T0.AddDays(-3)), + new FrameDownloadVideo("marta.demo", path, "post", instants[..1], Make.T0.AddDays(-3)), + ]); + using var sent = new MemoryStream(); + + await service.WriteZipAsync(new AsyncOnlyStream(sent), plan, publicationTime: true, TestContext.CancellationToken); + + using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read); + CollectionAssert.AreEqual( + new[] { "marta.demo/post_f001.png", "marta.demo/post_f002.png", "marta.demo/post_f003.png", "marta.demo/post_f001 (2).png" }, + archive.Entries.Select(e => e.FullName).ToArray()); + var published = TimeZoneInfo.ConvertTime(Make.T0.AddDays(-3), clock.LocalZone).DateTime; + foreach (var entry in archive.Entries) + { + Assert.AreEqual(entry.Length, entry.CompressedLength, "frames are stored, not compressed"); + // The zip keeps local date and time fields at 2 s steps: the time of publication where Febe runs (D18). + Assert.IsLessThanOrEqualTo(2.0, Math.Abs((entry.LastWriteTime.DateTime - published).TotalSeconds), $"{entry.LastWriteTime} vs {published}"); + } + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task ASlowReaderThatKeepsReadingGetsTheWholeZip() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("fotogrammi-lento"); + var path = temp.Combine("rumore.mp4"); + await File.WriteAllBytesAsync(path, NoiseVideo(), ct); + + // The time of the stalls moves only as the link sends, never with the load of the machine. + var time = new LinkTime(); + var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(400), StallTime = time }; + var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [ + new FrameDownloadVideo("marta.demo", path, "rumore", [TimeSpan.Zero], Make.T0), + ]); + + // 64 KB every 150 ms: a frame of a few hundred KB takes longer than the 400 ms of a stall, but every piece goes. + using var sent = new MemoryStream(); + var link = new SlowStream(sent, TimeSpan.FromMilliseconds(150), time); + await service.WriteZipAsync(link, plan, publicationTime: false, ct); + + using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read); + var entry = archive.Entries.Single(); + Assert.IsGreaterThan(64L * 1024 * 3, entry.Length, "a frame that takes more than a stall to send"); + Assert.IsGreaterThan(TimeSpan.FromMilliseconds(400), link.Busy, "the link was slower than a stall for the frame"); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task AReaderThatStopsReadingAbortsTheZip() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("fotogrammi-fermo"); + var path = temp.Combine("video.mp4"); + await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), ct); + var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(300) }; + var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [ + new FrameDownloadVideo("marta.demo", path, "post", [TimeSpan.Zero], Make.T0), + ]); + + await Assert.ThrowsAsync(() => service.WriteZipAsync(new SlowStream(Stream.Null, Timeout.InfiniteTimeSpan), plan, false, ct)); + Assert.IsFalse(ct.IsCancellationRequested); + } + + /// A video of one picture of noise (320 × 320): its PNG frame is several hundred KB. + private static byte[] NoiseVideo() + { + var random = new Random(28); + using var output = new MemoryStream(); + H264PcmWriter.WriteMp4(output, 320, 320, 1, 8, _ => + { + var p = new H264PcmPicture(320, 320); + for (var i = 0; i < p.Y.Length; i++) + { + p.Y[i] = (byte)random.Next(16, 236); + } + + for (var i = 0; i < p.Cb.Length; i++) + { + p.Cb[i] = (byte)random.Next(16, 241); + p.Cr[i] = (byte)random.Next(16, 241); + } + + return p; + }); + return output.ToArray(); + } + + /// + /// A response body on a slow link: asynchronous writes only, each taking perPiece for every 64 KB it holds + /// (a write completes once its bytes are sent); an infinite time is a reader that stopped. With a + /// a write moves that time instead of waiting for the real one. + /// + private sealed class SlowStream(Stream inner, TimeSpan perPiece, LinkTime? time = null) : Stream + { + public TimeSpan Busy { get; private set; } + + 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 Flush() => throw new InvalidOperationException("synchronous flush"); + + public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + 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(); + + public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("synchronous write"); + + public override void Write(ReadOnlySpan buffer) => throw new InvalidOperationException("synchronous write"); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + var wait = perPiece == Timeout.InfiniteTimeSpan ? Timeout.InfiniteTimeSpan : perPiece * ((buffer.Length + 65535) / 65536); + if (time is not null && wait != Timeout.InfiniteTimeSpan) + { + time.Advance(wait); // the stall timers due before this write is sent fire now + cancellationToken.ThrowIfCancellationRequested(); + } + else + { + await Task.Delay(wait, cancellationToken); + } + + if (wait != Timeout.InfiniteTimeSpan) + { + Busy += wait; + } + + await inner.WriteAsync(buffer, cancellationToken); + } + } + + /// + /// A time that moves only when is called: its timers fire then, in order, on the caller's + /// thread. Only one-shot timers (those of a ) are supported. + /// + private sealed class LinkTime : TimeProvider + { + private readonly Lock _gate = new(); + private readonly List _timers = []; + private DateTimeOffset _now = Make.T0; + + public override DateTimeOffset GetUtcNow() + { + lock (_gate) + { + return _now; + } + } + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + Assert.AreEqual(Timeout.InfiniteTimeSpan, period, "one-shot timers only"); + var timer = new LinkTimer(this, callback, state); + timer.Change(dueTime, period); + return timer; + } + + public void Advance(TimeSpan by) + { + List due; + lock (_gate) + { + _now += by; + due = [.. _timers.Where(t => t.Due <= _now).OrderBy(t => t.Due)]; + foreach (var t in due) + { + _timers.Remove(t); + } + } + + foreach (var t in due) + { + t.Fire(); + } + } + + private sealed class LinkTimer(LinkTime owner, TimerCallback callback, object? state) : ITimer + { + public DateTimeOffset Due { get; private set; } + + public bool Change(TimeSpan dueTime, TimeSpan period) + { + lock (owner._gate) + { + owner._timers.Remove(this); + if (dueTime != Timeout.InfiniteTimeSpan) + { + Due = owner._now + dueTime; + owner._timers.Add(this); + } + } + + return true; + } + + public void Fire() => callback(state); + + public void Dispose() + { + lock (owner._gate) + { + owner._timers.Remove(this); + } + } + + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } + } + } + + /// A response body: asynchronous writes only. + private sealed class AsyncOnlyStream(Stream inner) : Stream + { + 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 Flush() => throw new InvalidOperationException("synchronous flush"); + + public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + 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(); + + public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("synchronous write"); + + public override void Write(ReadOnlySpan buffer) => throw new InvalidOperationException("synchronous write"); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + inner.WriteAsync(buffer, offset, count, cancellationToken); + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + inner.WriteAsync(buffer, cancellationToken); + } +} diff --git a/tools/Febe.Schermate/Shots.cs b/tools/Febe.Schermate/Shots.cs index 9d71242..772fb25 100644 --- a/tools/Febe.Schermate/Shots.cs +++ b/tools/Febe.Schermate/Shots.cs @@ -53,7 +53,7 @@ internal static class Shots // Part 3: copie esterne (tappa E2, spec §4.10 and §10.3, composed from mockups 08, 07, 05, 13, 09, 01, 02, 06). // No step starts a copy: the demo's copies stay as they were seeded. - new("/impostazioni/esportazione?tema=chiaro", "15-impostazioni-esportazione.png"), + new("/impostazioni/esportazione?tema=chiaro", "15-impostazioni-esportazione.png", 1440, 1470), new("/impostazioni/esportazione?tema=chiaro&veste=docker", "15-impostazioni-esportazione-docker.png"), new("/impostazioni/esportazione?tema=chiaro", "16-destinazione.png", 1440, 1000, Step: "destinazione.js"), new("/account/3/impostazioni?tema=chiaro", "17-account-copie-esterne.png", 1440, 1000, Step: "account-copie.js"), @@ -61,6 +61,15 @@ internal static class Shots new("/libreria?copie=copiati&tema=chiaro", "19-libreria-copie.png", Step: "menu-csv.js"), new("/libreria?copie=tolti&tema=chiaro", "20-visualizzatore-copie.png", Step: "visualizzatore-copie.js"), new("/dashboard/esportazione?tema=chiaro", "21-dashboard-esportazione.png"), + + // Part 4: formati e fotogrammi (tappa E3, spec §4.10 and §10.3, composed from mockups 13, 09, 08, 07, 02 and 01). + // 15–21 above show the formats too. No step converts, downloads or copies: the question and the dialogs stay open. + new("/libreria?tema=chiaro", "22-fotogrammi-visualizzatore.png", 1440, 1000, Step: "fotogrammi-visualizzatore.js"), + new("/libreria?tema=chiaro", "22-fotogrammi-striscia.png", 1440, 1000, Step: "fotogrammi-striscia.js"), + new("/libreria?account=2&tema=chiaro", "23-fotogrammi-selezione.png", 1440, 1000, Step: "fotogrammi-selezione.js"), + new("/libreria?tema=chiaro", "24-visualizzatore-fotogramma.png", Step: "visualizzatore-fotogramma.js"), + new("/libreria?tema=chiaro", "25-copia-in-formati.png", 1440, 1000, Step: "copia-in-formati.js"), + new("/impostazioni/esportazione?tema=chiaro", "26-conversione-libreria.png", Step: "conversione-libreria.js"), ]; /// diff --git a/tools/Febe.Schermate/passi/conversione-libreria.js b/tools/Febe.Schermate/passi/conversione-libreria.js new file mode 100644 index 0000000..d65c079 --- /dev/null +++ b/tools/Febe.Schermate/passi/conversione-libreria.js @@ -0,0 +1,16 @@ +// «Conversione della libreria» in Impostazioni → Esportazione (spec §4.10, tappa E3; composed from mockups 08 and 07 and +// the dialogs of mockup 13): PNG chosen for the photos opens «Convertire anche i N file già in libreria?» with «Solo i +// nuovi» first. Nothing is answered: closed, the setting stays «Originale». +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (test, tries = 100) => { for (let i = 0; i < tries && !test(); i++) await sleep(100); return test(); }; +const photo = () => document.querySelector('.sezione-conversione .scelta-formato[data-tipo=photo]'); +await until(() => photo() && document.querySelector('.stato-conversione')?.textContent); +const body = document.querySelector('.corpo'); +const section = document.querySelector('.sezione-conversione'); +body.scrollTop = section.getBoundingClientRect().top - body.getBoundingClientRect().top + body.scrollTop - 24; +photo().querySelector('[data-value=png]').click(); +const question = () => [...document.querySelectorAll('.dialogo')].find((d) => d.querySelector('.spazio-conversione')); +await until(question); +await sleep(500); +document.activeElement?.blur(); +return [question().querySelector('h2')?.textContent, question().querySelector('.spazio-conversione')?.textContent]; diff --git a/tools/Febe.Schermate/passi/copia-in-formati.js b/tools/Febe.Schermate/passi/copia-in-formati.js new file mode 100644 index 0000000..c105b62 --- /dev/null +++ b/tools/Febe.Schermate/passi/copia-in-formati.js @@ -0,0 +1,21 @@ +// «Copia in…» on the whole Libreria with «Cambia» open (spec §4.10, tappa E3; composed from the dialogs of mockup 13, +// the segmented controls of mockup 07 and mockup 09): PNG chosen for the photos of this copy only, the summary and the +// rows asked again with that format. Nothing is started. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (test, tries = 100) => { for (let i = 0; i < tries && !test(); i++) await sleep(100); return test(); }; +const button = () => [...document.querySelectorAll('.strumenti button')].find((b) => (b.getAttribute('aria-label') || '').startsWith('Esporta')); +await until(() => button() && document.querySelector('.tess[data-id]')); +button().click(); +await sleep(400); +[...document.querySelectorAll('.menu button, .menu [role=menuitem]')].find((x) => x.textContent.includes('Copia'))?.click(); +const dialog = () => document.querySelector('.dialogo.copia-in'); +await until(() => dialog()?.querySelector('.riepilogo-copia'), 150); +dialog().querySelector('.riga-formato-testa .btn').click(); +await sleep(200); +dialog().querySelector('.riga-formato .scelta-formato[data-tipo=photo] [data-value=png]').click(); +// The choice asks the plan again: the button is off until the new plan is drawn. +await until(() => dialog().querySelector('.riepilogo-copia') + && !dialog().querySelector('footer .btn.primo').disabled, 200); +await sleep(400); +document.activeElement?.blur(); +return [dialog().querySelector('.testo-formato')?.textContent, dialog().querySelector('.riepilogo-copia')?.textContent]; diff --git a/tools/Febe.Schermate/passi/fotogrammi-selezione.js b/tools/Febe.Schermate/passi/fotogrammi-selezione.js new file mode 100644 index 0000000..72f3c23 --- /dev/null +++ b/tools/Febe.Schermate/passi/fotogrammi-selezione.js @@ -0,0 +1,23 @@ +// «Fotogrammi…» from the selection bar of the Libreria (spec §4.10, tappa E3; composed from the dialogs of mockup 13 and +// the choices of mockup 09): @marta.demo, «Seleziona», four tiles of videos and four of photos, then the dialog with +// the time field only (there is no single video) and the summary that says the photos are skipped. Nothing starts. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (test, tries = 100) => { for (let i = 0; i < tries && !test(); i++) await sleep(100); return test(); }; +const tiles = () => [...document.querySelectorAll('.mosaico .tess[data-id]')]; +const isVideo = (tile) => Boolean(tile.querySelector('use[href="#i-play"]')); +await until(() => tiles().filter(isVideo).length >= 4 && tiles().length >= 8); +[...document.querySelectorAll('.strumenti .btn')].find((b) => b.textContent.includes('Seleziona')).click(); +await sleep(300); +const chosen = [...tiles().filter(isVideo).slice(0, 4), ...tiles().filter((x) => !isVideo(x)).slice(0, 4)]; +for (const tile of chosen) { + tile.click(); + await sleep(60); +} +const frames = () => document.querySelector('.salva .fotogrammi-selezione'); +await until(() => frames() && !frames().disabled); +frames().click(); +const dialog = () => document.querySelector('.dialogo.fotogrammi'); +await until(() => dialog()?.querySelector('.riepilogo-fotogrammi .riepilogo-copia')); +await sleep(500); +document.activeElement?.blur(); +return dialog().querySelector('.riepilogo-fotogrammi').textContent; diff --git a/tools/Febe.Schermate/passi/fotogrammi-striscia.js b/tools/Febe.Schermate/passi/fotogrammi-striscia.js new file mode 100644 index 0000000..1454485 --- /dev/null +++ b/tools/Febe.Schermate/passi/fotogrammi-striscia.js @@ -0,0 +1,42 @@ +// The dialog «Fotogrammi» from the viewer in «N in tutto» (spec §4.10, tappa E3): 8 frames, the strip of the first six +// previews with «e altri 2», JPG with its note «con perdita: qualità 92», output «Nella cartella delle copie» with the +// row of the folder. Same video as fotogrammi-visualizzatore.js. Nothing is downloaded or copied. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (test, tries = 100) => { for (let i = 0; i < tries && !test(); i++) await sleep(100); return test(); }; +const json = (path) => fetch(path, { headers: { Accept: 'application/json' } }).then((r) => r.json()); + +const marta = (await json('/api/accounts')).accounts.find((a) => a.username === 'marta.demo'); +const videos = []; +for (let cursor = null, i = 0; i < 20; i++) { + const page = await json(`/api/library?accounts=${marta.id}&mode=files&limit=600${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`); + videos.push(...page.tiles.filter((x) => x.cover && x.cover.kind === 'video')); + if (!(cursor = page.older)) break; +} +let found = null; +for (let i = 0; i < videos.length && !found; i += 16) { + const entries = await Promise.all(videos.slice(i, i + 16).map((x) => json(`/api/entries/${x.id}`))); + found = entries.find((e) => e.media.some((m) => (m.copies || []).some((c) => c.variant === 'frame'))); +} +const { navigate } = await import('/js/core/shell.js'); +await navigate(`/libreria?account=${found.account.id}&dal=${found.publishedDay}&al=${found.publishedDay}`); +const tile = () => document.querySelector(`.mosaico .tess[data-entry="${found.id}"]`); +await until(tile); +tile().click(); +await until(() => document.querySelector('.vis .azione-fotogramma') && document.querySelector('.vis video')?.readyState >= 1); +document.querySelector('.vis video').pause(); +document.querySelector('.vis .azione-fotogramma').click(); +const dialog = () => document.querySelector('.dialogo.fotogrammi'); +await until(() => dialog()?.querySelector('.modo-fotogrammi')); +dialog().querySelector('.modo-fotogrammi').previousElementSibling.querySelector('[data-value=numero]').click(); +const count = dialog().querySelector('input[type=number]'); +count.value = '8'; +count.dispatchEvent(new Event('input', { bubbles: true })); +[...dialog().querySelectorAll('[role=radio][data-value=jpg]')].pop().click(); +dialog().querySelector('input[type=radio][value=cartella]').click(); +await until(() => { + const images = [...dialog().querySelectorAll('.striscia-fotogrammi img')]; + return images.length === 6 && images.every((i) => i.complete && i.naturalWidth > 0) && /Copia/.test(dialog().querySelector('footer .btn.primo').textContent); +}, 150); +await sleep(500); +document.activeElement?.blur(); +return [dialog().querySelector('.altri-fotogrammi')?.textContent, dialog().querySelector('.riepilogo-fotogrammi').textContent]; diff --git a/tools/Febe.Schermate/passi/fotogrammi-visualizzatore.js b/tools/Febe.Schermate/passi/fotogrammi-visualizzatore.js new file mode 100644 index 0000000..d75a359 --- /dev/null +++ b/tools/Febe.Schermate/passi/fotogrammi-visualizzatore.js @@ -0,0 +1,41 @@ +// «Fotogramma» from the viewer (spec §4.6, §4.10, tappa E3; composed from the dialogs of mockup 13 and mockup 02): the +// video of @marta.demo that the demo has a frame of, the player at 1,25 s, the dialog «Fotogrammi» in «Questo istante» +// with its preview, the scrubber, the time field and «Fotogramma a …». Nothing is downloaded or copied. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (test, tries = 100) => { for (let i = 0; i < tries && !test(); i++) await sleep(100); return test(); }; +const json = (path) => fetch(path, { headers: { Accept: 'application/json' } }).then((r) => r.json()); + +// The video with a frame copy: the newest of @marta.demo's videos whose viewer lists a «fotogramma» row. +const marta = (await json('/api/accounts')).accounts.find((a) => a.username === 'marta.demo'); +const videos = []; +for (let cursor = null, i = 0; i < 20; i++) { + const page = await json(`/api/library?accounts=${marta.id}&mode=files&limit=600${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`); + videos.push(...page.tiles.filter((x) => x.cover && x.cover.kind === 'video')); + if (!(cursor = page.older)) break; +} +let found = null; +for (let i = 0; i < videos.length && !found; i += 16) { + const entries = await Promise.all(videos.slice(i, i + 16).map((x) => json(`/api/entries/${x.id}`))); + found = entries.find((e) => e.media.some((m) => (m.copies || []).some((c) => c.variant === 'frame'))); +} +const { navigate } = await import('/js/core/shell.js'); +await navigate(`/libreria?account=${found.account.id}&dal=${found.publishedDay}&al=${found.publishedDay}`); +const tile = () => document.querySelector(`.mosaico .tess[data-entry="${found.id}"]`); +await until(tile); +tile().click(); +await until(() => document.querySelector('.vis .azione-fotogramma') && document.querySelector('.vis video')?.readyState >= 1); + +const video = document.querySelector('.vis video'); +video.pause(); +video.currentTime = 1.25; +await until(() => !video.seeking && Math.abs(video.currentTime - 1.25) < 0.01, 50); +document.querySelector('.vis .azione-fotogramma').click(); +const dialog = () => document.querySelector('.dialogo.fotogrammi'); +await until(() => { + const img = dialog()?.querySelector('.anteprima-fotogramma img'); + return img && img.complete && img.naturalWidth > 0 && /Fotogramma a/.test(dialog().querySelector('.istante-mostrato')?.textContent || ''); +}); +await until(() => dialog().querySelector('.riepilogo-fotogrammi .riepilogo-copia')); +await sleep(400); +document.activeElement?.blur(); +return [dialog().querySelector('.istante-mostrato')?.textContent, dialog().querySelector('.riepilogo-fotogrammi')?.textContent]; diff --git a/tools/Febe.Schermate/passi/visualizzatore-fotogramma.js b/tools/Febe.Schermate/passi/visualizzatore-fotogramma.js new file mode 100644 index 0000000..0c54e39 --- /dev/null +++ b/tools/Febe.Schermate/passi/visualizzatore-fotogramma.js @@ -0,0 +1,33 @@ +// The viewer of the video the demo has a frame of (spec §4.6, §4.10, tappa E3; composed from mockup 02): in the File +// panel the copy rows with their form, «Copiato in Disco USB … · intero» and «… · fotogramma a 0:01,125 · PNG», and +// «Fotogramma» among the actions at the bottom. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const until = async (test, tries = 100) => { for (let i = 0; i < tries && !test(); i++) await sleep(100); return test(); }; +const json = (path) => fetch(path, { headers: { Accept: 'application/json' } }).then((r) => r.json()); + +const marta = (await json('/api/accounts')).accounts.find((a) => a.username === 'marta.demo'); +const videos = []; +for (let cursor = null, i = 0; i < 20; i++) { + const page = await json(`/api/library?accounts=${marta.id}&mode=files&limit=600${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`); + videos.push(...page.tiles.filter((x) => x.cover && x.cover.kind === 'video')); + if (!(cursor = page.older)) break; +} +let found = null; +for (let i = 0; i < videos.length && !found; i += 16) { + const entries = await Promise.all(videos.slice(i, i + 16).map((x) => json(`/api/entries/${x.id}`))); + found = entries.find((e) => e.media.some((m) => (m.copies || []).some((c) => c.variant === 'frame'))); +} +const { navigate } = await import('/js/core/shell.js'); +await navigate(`/libreria?account=${found.account.id}&dal=${found.publishedDay}&al=${found.publishedDay}`); +const tile = () => document.querySelector(`.mosaico .tess[data-entry="${found.id}"]`); +await until(tile); +tile().click(); +await until(() => document.querySelector('.vis .azione-fotogramma') && document.querySelectorAll('.vis .riga-copia').length >= 2 + && document.querySelector('.vis video')?.readyState >= 2); +const video = document.querySelector('.vis video'); +video.pause(); +video.currentTime = 1.125; +await until(() => !video.seeking, 50); +await sleep(600); +document.activeElement?.blur(); +return [...document.querySelectorAll('.vis .riga-copia')].map((r) => r.textContent);