diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md
index 5f032cd..b6567d8 100644
--- a/docs/SPECIFICA.md
+++ b/docs/SPECIFICA.md
@@ -215,14 +215,14 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz
### 4.6 Libreria
-- Mosaico di tutti gli elementi in ordine di pubblicazione, raggruppati per giorno (mockup 01). Filtri per tipo, account, periodo, provenienza (scaricati o importati). Ricerca per nome dell'account e testo della didascalia.
+- Mosaico di tutti gli elementi in ordine di pubblicazione, raggruppati per giorno (mockup 01). Filtri per tipo, account, periodo, provenienza (scaricati o importati); dalla tappa E4, fra i tipi, «Video fermi» dopo «Video», solo nella Libreria (§4.10). Ricerca per nome dell'account e testo della didascalia.
- Deve restare fluida con 200.000 elementi: caricamento a finestre, miniature generate una volta e conservate.
-- **«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.
+- **«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, con «Video fermi» (tappa E4) solo i video fermi. 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 (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»).
+- 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, per un video fermo, l'etichetta «Video fermo» e «Salva il fotogramma», e nel pannello File la riga «Video fermo» con l'esito dell'analisi, 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.
+- Selezione multipla per esportare (elenco CSV di §4.8; «Copia in…» e «Fotogrammi…» di §4.10), per cercare i video fermi («Cerca i video fermi», tappa E4, §4.10) o per eliminare. Dal traguardo 0.3.0 un filtro «Copie» (Tutti, Non ancora copiati, Copiati, Tolti o superati) in Libreria e nella scheda dell'account.
### 4.7 Percorsi e nomi dei file
@@ -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; 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.
+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»); dalla tappa E4 (29 novembre 2026) i video fermi («È un video fermo?», «Cerca i video fermi», «Salva il fotogramma», il filtro «Video fermi»); l'automatica con E5. 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».
@@ -296,10 +296,15 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
- **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 (risposta di Alberto del 29 novembre 2026, §16 domanda 33). Limiti (risposta di Alberto del 29 novembre 2026, §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 (risposta di Alberto del 29 novembre 2026, §16 domanda 32). Il formato proposto è **PNG** (risposta di Alberto del 29 novembre 2026, §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» (risposta di Alberto del 29 novembre 2026, §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».
+- **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` è di «Salva il fotogramma» (tappa E4, qui sotto). «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» (risposta di Alberto del 29 novembre 2026, §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 (risposta di Alberto del 29 novembre 2026, §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. 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.
+- **Video fermo** (mostra sempre la stessa immagine): l'analisi si fa **solo a richiesta**, dal visualizzatore («È un video fermo?») o dalla selezione («Cerca i video fermi»), mai in sottofondo su tutta la libreria. Esiti: «Fermo», «In movimento», «Non analizzabile», salvati per SHA-256 (`video_analysis`, con il numero dell'algoritmo per poter rianalizzare, l'istante del fotogramma scelto e il motivo): restano se l'elemento si elimina, e un file che cambia SHA-256 torna «mai analizzato». Vale l'esito dell'algoritmo più alto. Per un video fermo il visualizzatore mostra l'etichetta «Video fermo», nel pannello File «Un'immagine sola per tutto il video: basta un fotogramma · fotogramma a 0:01,125» e «Salva il fotogramma»; per gli altri «No: l'immagine cambia» o «Non analizzabile: …» con il motivo, e «Analizza di nuovo» su un «Non analizzabile» o su un esito di un algoritmo di prima, se i fotogrammi si possono prendere. Nelle destinazioni si copia comunque **il video intero**, che tiene l'audio: nessuna scelta per cartella (risposta di Alberto del 29 novembre 2026, §16 domanda 39). «È un video fermo?» non si mostra per un video i cui fotogrammi non si possono prendere.
+- **Come si riconosce un video fermo** (tappa E4, algoritmo 1; numeri in `StillVideoAnalyzer`, misure in `docs/decisioni.md`). Febe guarda **sette fotogrammi**, uno in ognuna di sette parti uguali di ciò che il video mostra, quindi lontano dall'inizio e dalla fine, a punti diversi da una parte all'altra (a passi uguali un filmato breve ripetuto cadrebbe sempre sulla stessa immagine): di un filmato ripetuto da 2 a 40 volte, anche non un numero intero, abbracciano almeno il 48 % del giro, quindi un'immagine mostrata per meno di metà giro può ancora sfuggire; uno sì e uno no può essere un fotogramma chiave vicino, che si decodifica da solo, gli altri sono proprio quello mostrato in quel punto. Un video di al più sette immagini si guarda tutto. Di ognuno fa una griglia di 32 × 32 blocchi e una più fitta (fino a 128 × 128), per le cose piccole che in un blocco si medierebbero (neve, rumore, scritte piccole). I fotogrammi **quasi neri** all'inizio o alla fine (dissolvenze) si mettono da parte; uno fra due immagini si confronta con loro, senza mai sceglierlo: il nero di uno stacco vuol dire «In movimento», un'immagine scura che la grana porta sopra e sotto la soglia no; se uno solo non è nero, Febe ne guarda altri fra quelli neri intorno, e finché non ha visto altre immagini non dice «Fermo». Una dissolvenza, dove la luce dei blocchi cambia nella stessa misura, si compensa, anche se la luce sta in pochi blocchi (una scritta sul nero), in un colore solo (un cartello blu) o è poca (una foto scura); e ciò che il bianco bruciato può nascondere non conta come movimento. L'immagine ferma è la mediana dei fotogrammi, blocco per blocco. Il video è «Fermo» se ogni fotogramma ne differisce **in media al più di 3 su 255** e i blocchi che differiscono **più di 12 coprono al più il 5 % dell'immagine**: un piccolo adesivo animato o una scritta piccola che si muove lasciano il video «Fermo» (risposta di Alberto del 29 novembre 2026, §16 domande 44 e 47), e il pannello File aggiunge «· una piccola parte si muove». Un video **tutto nero o tutto di un solo colore è «Non analizzabile»** (risposta di Alberto del 29 novembre 2026, §16 domanda 42); lo sono anche un video in un codec che Febe non decodifica, uno che non si legge, uno di durata sconosciuta e uno la cui analisi richiede troppo tempo. Un fotogramma da guardare che non c'è (file troncato o rovinato) vuol dire «non si legge», mai «Fermo», a meno che gli altri mostrino già il movimento; un errore del disco o della rete invece non dice nulla del video e non si salva. Nero e colore unico si giudicano anche sui singoli pixel: una scritta chiara sul nero, o piccola su un fondo unito, è un'immagine. Un video di un solo fotogramma è «Fermo», se quel fotogramma non è nero o di un solo colore. Un cambio della regola o delle soglie alza il numero dell'algoritmo.
+- **«È un video fermo?»** (tappa E4), dal visualizzatore, parte **anche durante una sessione del motore**, come un fotogramma: una sola analisi, al più 30 secondi; oltre, «L'analisi richiede troppo tempo: avviala dalla selezione» («…: resta l'esito di prima» se il video ha già un esito, che la selezione salterebbe), e non si salva nulla (risposta di Alberto del 29 novembre 2026, §16 domanda 43). Prima di analizzare Febe rifà lo SHA-256 del file: se non è quello registrato lo dice («Il file della libreria non corrisponde a quello registrato.») e non salva nulla. Passa davanti alla ricerca della selezione, che rifà poi il video lasciato.
+- **«Cerca i video fermi»** (tappa E4), dalla barra della selezione della Libreria e della scheda account (risposta di Alberto del 29 novembre 2026, §16 domanda 41). La finestra conta prima («28 video da analizzare · 12 già analizzati · le 5 foto si saltano»); poi un video alla volta, al più 2 minuti l'uno (oltre: «Non analizzabile: l'analisi richiedeva troppo tempo», che si salva), **mai durante una sessione del motore e mai insieme a importazione, copie o ricostruzione** (o uno zip di più di 20 fotogrammi): se una comincia mentre Febe analizza, il video si lascia e si rifà dopo. Non tiene occupato nessuno di quei lavori, che partono subito. Un video già analizzato con l'algoritmo di adesso si salta, tranne quelli la cui analisi richiedeva troppo tempo, che ogni avvio riprova una volta; uno stesso file in due elementi si analizza una volta, da quello dei due che è sul disco. Un video già in coda non si aggiunge di nuovo («I video scelti sono già in coda.»). Avanzamento, motivo dell'attesa e «Interrompi» in Dashboard → Esportazione; alla fine «Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile», con «Mostra i video fermi». Non riprende da sola alla riapertura di Febe: si rilancia.
+- **«Salva il fotogramma»** (tappa E4), solo dal visualizzatore di un video fermo, uno per volta (risposta di Alberto del 29 novembre 2026, §16 domanda 46): il fotogramma **più nitido fra quelli guardati dall'analisi, mai uno nero di una dissolvenza**, a piena risoluzione e come il video si vede; PNG proposto, JPG «con perdita» o WEBP senza perdita; «Scarica» o «Nella cartella delle copie», con il nome `…_fotogramma.png`; la finestra dice «Il fotogramma non ha l'audio» (risposta di Alberto del 29 novembre 2026, §16 domanda 45). La copia è un fotogramma come gli altri, con l'istante dell'analisi: non fa «Copiato» il video, e lo stesso istante già copiato con «Questo istante» è «già copiato»; «Copia di nuovo» gli ridà lo stesso nome. Se mentre il lavoro aspetta il file della libreria cambia, vale l'istante dell'analisi del file nuovo, o il fotogramma si salta con la nota, anche se il lavoro si ferma e riprende a metà della scrittura.
+- **Filtro «Video fermi»** (tappa E4; risposta di Alberto del 29 novembre 2026, §16 domanda 40): nella Libreria, fra i tipi, dopo «Video» (`?tipo=fermi`); non nelle schede degli account. Mostra gli elementi (post, storie, in evidenza, taggati) con almeno un video presente in libreria la cui ultima analisi è «Fermo»; con «Tutte le foto» solo quei video. Un video mai analizzato non c'è. Nessun segno sulle tessere.
+- Copie, conversioni e analisi lunghe partono fuori dalle sessioni del motore (l'analisi di un video solo, chiesta dal visualizzatore, anche durante: al più 30 secondi); 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.**
@@ -792,7 +797,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) 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` |
+| `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), dalla tappa E3 (copie convertite e fotogrammi in `export_copy` ed `export_item`, conversione della libreria in `media_conversion`, senza una migrazione nuova) e dalla tappa E4 (`video_analysis`, con le colonne della migrazione `0005`): 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, con l'istante del fotogramma di un «Fermo» (`frame_at_ms`) e i codici del motivo (`note`); 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:
@@ -801,6 +806,7 @@ Vincoli che contano:
- Indici su (account, data di pubblicazione), SHA-256, impronta, stato. Dalla migrazione `0002` (tappa D1) anche `ix_entry_discovered` su `entry (discovered_at)`, per le miniature della cronologia della Dashboard (§7.9), e `ix_media_entry_files` su `media (entry_id, state, kind)`, per i conteggi di «Tutte le foto» (§4.6).
- Dalla migrazione `0003` (tappa E1): l'identità di una copia è unica sulle righe correnti, «Copiato» e «Non riuscito» (`ux_export_copy_identity`); un percorso di una destinazione è tenuto al più da una copia «Copiato» o «Superato», senza distinguere le maiuscole ASCII, e un percorso «Tolto» è di nuovo libero (`ux_export_copy_path`); una copia non è mai «Superato» dal suo stesso originale (se il file della libreria torna quello di prima, la copia torna «Copiato»); una cartella senza il suo account non è mai automatica; una copia tiene identificativo e nome dell'account rimosso solo finché è senza account, e le copie orfane di un account si trovano per quelli (`ix_export_copy_orphan`); nella stessa cartella al più una conversione corrente per file e formato (`ux_media_conversion_current`); le ricerche vanno per SHA-256 (`ix_export_copy_sha256`, `ix_export_copy_superseded_by`); il filtro «Copie» su tutta la libreria legge `ix_export_copy_destination`, e le copie di una destinazione e i file di un lavoro si sfogliano per chiave senza riordinarli (`ix_export_copy_destination_id`, `ix_export_item_run`); una destinazione con copie o lavori e una riga `media` con un convertito registrato non si cancellano (`ON DELETE RESTRICT`); ogni colonna di chiave esterna delle tabelle nuove ha il suo indice.
- Dalla migrazione `0004` (tappa E2): soltanto l'indice `ix_media_sha256_entry` su `media (sha256, entry_id)` dove lo SHA-256 c'è, per il filtro «Copie» (§4.6, §4.10), che dalle copie arriva agli elementi senza leggere le righe dei file; nessuna tabella e nessuna colonna cambia. Misure in `docs/decisioni.md`.
+- Dalla migrazione `0005` (tappa E4): in `video_analysis` le colonne `frame_at_ms` (millisecondi dell'istante mostrato, presente per un «Fermo» e solo per lui) e `note` (codici in inglese separati da spazi, sempre presenti per un «Non analizzabile»: `FrameNotAvailable`, `DurationUnknown`, `Unreadable`, `TooSlow`, `AllDark`, `SingleColor`; su un «Fermo» `SmallMotion`), con i `CHECK` che lo impongono, e l'indice parziale `ix_video_analysis_still` sui soli «Fermo», per il filtro «Video fermi» (§4.6, §4.10). Nessuna versione prima di E4 scriveva la tabella: una riga messa a mano che i `CHECK` non ammettono si toglie, e il video si analizza di nuovo a richiesta.
- Versione dello schema in `PRAGMA user_version`, migrazioni come file SQL numerati eseguiti all'avvio dentro una transazione. Un solo scrittore: le scritture passano da una coda.
### 8.4 Miniature e impronte
@@ -916,7 +922,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 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 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»), e dalla tappa E4 «Salva il fotogramma» (la stessa finestra senza i tre modi, con l'anteprima del fotogramma scelto dall'analisi) e «Cerca i video fermi» (il riepilogo e «Analizza N video»; dialoghi del 13); in Libreria e nella scheda account il menu dell'icona CSV («Esporta l'elenco (CSV)», «Copia i file in…»), «Copia in…», «Fotogrammi…» e dalla tappa E4 «Cerca i video fermi» nella barra della selezione, nella sola Libreria il tipo «Video fermi» dopo «Video» (mockup 01), 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?» («Analisi in corso…» mentre lavora) o, per un video fermo, l'etichetta «Video fermo» e «Salva il fotogramma», e nel pannello File la riga «Video fermo» con l'esito e «Analizza di nuovo», 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», dalla tappa E4 il riquadro «Video fermi» (avanzamento della ricerca, motivo dell'attesa, «Interrompi» e, finita, il riepilogo finché Febe non si chiude) 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):
@@ -1129,11 +1135,11 @@ Ogni tappa finisce con i controlli «Fatto quando» eseguiti e mostrati, `docs/s
| **E1 Schema** | Migrazione `0003` (la `0002` è di D1) con le tabelle di §8.3, `export_account` e `media_conversion` comprese, archivi e `ExportSettings` con le chiavi `esportazione.*`. Nessun cambio di comportamento | §8.3, §4.10 | Database delle versioni 1 e 2 aggiornati con `foreign_key_check` pulito; database più nuovo rifiutato |
| **E2 Copie esterne** | Destinazioni (generale e per account), controlli delle cartelle, `/esporta` in Docker, «Copia in…» degli originali, adozione, stati «Tolto» e «Superato», «già copiato» su tessere, visualizzatore, scheda account e filtro «Copie», scheda «Esportazione» della Dashboard | §4.10, §10.3, §11, §12, §13.2 | Prove: cartelle rifiutate, radice mai creata, `/esporta` non montata quindi nulla scritto, nessuna sovrascrittura, adozione, filtro «Copie» con 200.000 elementi entro 250 ms. Schermate confrontate (§10.7) e guida dell'esportazione |
| **E3 Formati e fotogrammi** | Conversione delle copie e della libreria (il convertito si aggiunge, l'originale resta), metadati copiati, rimuxaggio, fotogrammi a richiesta, zip | §4.10, §3 | Prove: JPG → JPG è una copia, PNG con trasparenza → JPG, WEBP senza perdita con i pixel identici all'originale, metadati presenti nel convertito, MOV → MP4, fotogramma a un istante, ogni k secondi, N; libreria con originale intatto |
-| **E4 Video fermi** | Analisi a richiesta, `video_analysis`, «Salva il fotogramma» | §4.10 | Prove su video costruiti dalle prove (immagine fissa con audio, dissolvenza dal nero, movimento, clip brevissima, tutto nero, rotazione); soglie in `docs/decisioni.md` |
+| **E4 Video fermi** | Analisi a richiesta («È un video fermo?» e «Cerca i video fermi» dalla selezione), `video_analysis` con la migrazione `0005`, filtro «Video fermi», «Salva il fotogramma» | §4.10, §4.6, §8.3 | Prove su video costruiti dalle prove (immagine fissa con audio, dissolvenza dal nero e al nero, movimento, piccola parte che si muove, clip brevissima, tutto nero, tutto di un solo colore, rotazione); soglie con le misure in `docs/decisioni.md`; filtro con 200.000 elementi nei tempi della prova di scala |
| **E5 Esportazione automatica** | Destinazioni automatiche, domanda «Solo i nuovi», giro orario, «Riconosci le copie già presenti» | §4.10 | Prove: «Tolto» e «Superato» non si ricopiano, destinazione irraggiungibile in pausa e poi ripresa, nessuna copia durante una sessione del motore; guida completa |
| **D1 Dashboard e ordine** | Issue #59 (decisione di Alberto del 25 novembre 2026). «Cosa scaricare prima», generale e per account, con il peso dei tipi sulle visite dopo il Giro dei seguiti e l'ordine della coda dei file (§7.2, §6.5, §4.4, §8.3); la Dashboard al posto di Attività: prima voce della barra laterale, pagina iniziale (`/`, `/attivita` e la finestra di Windows portano a `/dashboard`), compatta, con l'anteprima del browser sempre visibile e le miniature nella cronologia con l'anteprima ingrandita (§7.9, §10.2); «Raggruppa i post» / «Tutte le foto» nella Libreria e nella scheda account (§4.6); migrazione `0002` con `account.download_order`, `entry.is_reel`, `ix_entry_discovered` e `ix_media_entry_files` (§8.3) | §4.4, §4.6, §6.5, §7.2, §7.9, §10.2, §10.3, §14.3 | Prove del motore con orologio virtuale e seme fisso: ordine predefinito storie, evidenza, post, reel, taggati; con un altro ordine la prima visita dopo il giro è più spesso del primo tipo, ma non sempre, e il giro resta primo; un tipo senza lavoro dovuto non si visita; coda dei file nell'ordine dell'account; simulazione di 30 giorni per i tre profili senza superamenti dei tetti, con pause, frequenze e composizione delle sessioni invariate. Interfaccia: `/` e `/attivita` aprono la Dashboard; «Tutte le foto» con 200.000 elementi nei tempi della prova di scala; la scelta del modo si ricorda per pagina e senza memoria del browser torna «Raggruppa i post». Schermate composte confrontate (§10.7) con le differenze in `docs/schermate/differenze.md`; guida aggiornata |
-Dipendenze: C1 → C2 → C3 → C4; C5 dopo C2; C6 indipendente dalle altre; D1 indipendente dalle altre (costruita prima di E2, la cui scheda nasce quindi nella Dashboard); E1 → E2 → E3 → E4, con E3 dopo C1 per le foto e dopo C2 per il rimuxaggio, i fotogrammi dopo C3 (e dopo C4 per HEVC), E4 dopo C3; E5 dopo E2. La migrazione `0002` è di D1 (la prima dopo quelle già unite); E1 prende la `0003` e si concorda con le tappe di #36 che toccano lo schema.
+Dipendenze: C1 → C2 → C3 → C4; C5 dopo C2; C6 indipendente dalle altre; D1 indipendente dalle altre (costruita prima di E2, la cui scheda nasce quindi nella Dashboard); E1 → E2 → E3 → E4, con E3 dopo C1 per le foto e dopo C2 per il rimuxaggio, i fotogrammi dopo C3 (e dopo C4 per HEVC), E4 dopo C3; E5 dopo E2. La migrazione `0002` è di D1 (la prima dopo quelle già unite); E1 prende la `0003` e si concorda con le tappe di #36 che toccano lo schema; la `0004` è di E2, la `0005` di E4.
`docs/stato.md` è il filo fra le sessioni: che cosa è fatto, che cosa è in corso, che cosa è stato rimandato e perché. `docs/decisioni.md` raccoglie ogni scelta tecnica presa strada facendo, con data e motivo.
@@ -1195,6 +1201,15 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del
| 36 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: un WEBP con perdita con «WEBP senza perdita»: si copia byte per byte o si ricodifica senza perdita? | E3, prima di unire | Risposta: byte per byte: è lo stesso formato, e ricodificarlo lo farebbe solo più grande |
| 37 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: 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 | Risposta: sì, «già in libreria», mai una coppia di doppioni |
| 38 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: 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 | Risposta: sì: sono i limiti di memoria e di tempo di un server di casa |
+| 39 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: video fermi nelle cartelle delle copie: serve una scelta? Alberto aveva detto che si copia il video intero, che tiene l'audio. Nessuna scelta (proposta), oppure per cartella «Video intero», «Solo il fotogramma» o «Video e fotogramma» | E4, prima di cominciare | Risposta: nessuna scelta: si copia sempre il video intero, e l'immagine si salva a mano con «Salva il fotogramma» |
+| 40 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.6, §4.10). Domanda di allora: un filtro «Video fermi» nella Libreria? | E4, prima di cominciare | Risposta: sì: fra i filtri «Tipo», dopo «Video», solo nella Libreria e non nelle schede degli account; mostra gli elementi con almeno un video analizzato e risultato fermo |
+| 41 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: analisi di più video insieme dalla selezione: come si chiama e come si comporta? | E4, prima di cominciare | Risposta: «Cerca i video fermi», con una finestra che conta («28 video da analizzare · 12 già analizzati · le 5 foto si saltano»); un video alla volta, mai durante una sessione del motore e mai insieme a importazione, copie o ricostruzione; avanzamento e «Interrompi» in Dashboard → Esportazione; non riprende da sola alla riapertura: si rilancia, e i già analizzati si saltano |
+| 42 | **Risposta di Alberto del 29 novembre 2026: «Non analizzabile»** (§4.10). Domanda di allora: un video tutto nero, o tutto di un solo colore, è «Fermo», perché mostra sempre la stessa immagine (proposta), o «Non analizzabile»? | E4, prima di cominciare | Risposta: «Non analizzabile», con il motivo («il video è tutto nero», «il video è tutto di un solo colore»): non c'è un'immagine da salvare |
+| 43 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: «È un video fermo?» dal visualizzatore può partire anche durante una sessione del motore, o aspetta anche lei che finisca? | E4, prima di cominciare | Risposta: sì, come un fotogramma: una sola analisi, al più 30 secondi; oltre, «L'analisi richiede troppo tempo: avviala dalla selezione». Dalla selezione si aspetta la fine della sessione |
+| 44 | **Risposta di Alberto del 29 novembre 2026: sì, con le soglie adattate alla risposta 47** (§4.10). Domanda di allora: le soglie dell'analisi: 7 fotogrammi lontani dall'inizio e dalla fine, i quasi neri messi da parte, fermo se la differenza media è al più 3 su 255 e nessuna zona cambia più di 16 su 255; 30 secondi dal visualizzatore e 2 minuti per video dalla selezione. Vanno bene, o servono più fotogrammi? | E4, prima di cominciare | Risposta: sì, con una tolleranza per una zona piccola che si muove al posto di «nessuna zona» (domanda 47): media al più 3 su 255, e i blocchi oltre 12 su 255 al più il 5 % dell'immagine; oltre i 2 minuti «Non analizzabile». Numeri tarati sulle prove, con le misure in `docs/decisioni.md`; sui video veri del telefono si guardano con le prove dal vivo (`docs/prove-dal-vivo.md`, F8) |
+| 45 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: quale fotogramma salva «Salva il fotogramma»: il più nitido fra quelli guardati o sempre quello a metà del video? | E4, prima di cominciare | Risposta: il più nitido fra quelli guardati dall'analisi, mai uno nero di una dissolvenza; PNG `…_fotogramma.png`; «Scarica» o «Nella cartella delle copie»; la finestra dice «Il fotogramma non ha l'audio» |
+| 46 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: «Salva il fotogramma» solo dal visualizzatore, o anche per più video fermi insieme, dalla selezione? | E4, prima di cominciare | Risposta: per ora solo dal visualizzatore, uno per volta |
+| 47 | **Risposta di Alberto del 29 novembre 2026: «Fermo» se la parte che si muove è piccola** (§4.10). Domanda di allora: una foto con un piccolo adesivo animato o una scritta che si muove è «In movimento», così «basta un fotogramma» è sempre vero (proposta), o «Fermo» quando la parte che si muove è piccola? | E4, prima di cominciare | Risposta: «Fermo» quando la parte che si muove copre al più una piccola frazione dell'immagine, misurata a blocchi (5 %, §4.10), e il pannello File lo dice («una piccola parte si muove»); il fotogramma salvato resta il più nitido |
---
@@ -1574,7 +1589,14 @@ Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con
| Copia esterna | `ExportCopy` | Un file copiato in una destinazione, con il suo stato (Copiato, Tolto, Superato, Non riuscito) |
| File dovuto | due file (`ExportFilterSql.DueFile`) | Un file che «Copia in…» copierebbe: presente in libreria, di un account che si esporta e ha una destinazione, di un tipo che la destinazione copia (§4.10) |
| Fotogramma | `Frame` | Un'immagine presa da un video |
-| Video fermo | `StillVideo` | Video che mostra sempre la stessa immagine: basta un fotogramma |
+| Video fermo | `StillVideo` | Video che mostra sempre la stessa immagine, salvo al più una piccola parte che si muove: basta un fotogramma (§4.10) |
+| Analisi (di un video) | `StillVideoAnalyzer`, `VideoAnalysis` | Il confronto di sette fotogrammi che dice se un video è fermo, con il numero dell'algoritmo; solo a richiesta (§4.10) |
+| Fermo, In movimento, Non analizzabile | `VideoAnalysisOutcome` (`Still`, `Moving`, `NotAnalyzable`) | I tre esiti di un'analisi (§4.10) |
+| È un video fermo? | `StillVideoService.AnalyseNowAsync` | L'analisi di un video dal visualizzatore (§4.10) |
+| Cerca i video fermi | `StillVideoService.StartAsync` | L'analisi dei video di una selezione, uno alla volta, fuori dalle sessioni del motore (§4.10) |
+| Salva il fotogramma | `FrameMode.Still` | Il fotogramma più nitido di un video fermo, con `_fotogramma` nel nome (§4.10) |
+| Video fermi (filtro) | `LibraryKindFilter.StillVideos` | Il tipo della Libreria con gli elementi che hanno un video risultato «Fermo» (§4.6, §4.10) |
+| Una piccola parte si muove | `VideoAnalysisNotes.SmallMotion` | La nota di un video fermo in cui qualche blocco cambia, entro il 5 % dell'immagine (§4.10) |
| 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) |
diff --git a/docs/decisioni.md b/docs/decisioni.md
index 69155f9..f5d7f49 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -663,3 +663,18 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-29 | **Il motore non rimette a riposo la pagina che Alberto ha appena ripreso**: a fine sessione e dopo la guida di Alberto il riposo (`about:blank`) si dà solo se, ottenuto il turno, Alberto non guida il browser e l'interruttore non è su Verifica o Scollegato (`KeepsPageAfterWaitingForTurn`); `IsRunning` si accende in `StartAsync` prima di avviare il lavoro | Le prove del desktop su #67 cadevano a volte: fra il controllo e il turno Alberto poteva riprendere il browser, e il motore gli toglieva la pagina. Resta una finestra stretta fra il turno e la navigazione, scritta in `docs/stato.md` |
| 2026-12-01 | **Prove ferme nella CI (502 e 532): `--blame-hang-timeout 20m --blame-hang-dump-type none` su ogni `dotnet test` e lo stato della macchina durante le prove** (`.gitea/scripts/macchina.sh`: ogni 15 s ora, carico, memoria, scambio e pressione PSI in `macchina.log`, nel pacchetto `febe-ci` con i `.trx`). Nessun limite ai Chromium paralleli | Nelle due pause si sono fermate insieme tutte le prove in corso, anche le H.265, che non usano browser (aperti solo 5 e 3 Chromium), e tutto è ripartito insieme: un limite a 4 Chromium non le avrebbe evitate e allunga le prove (da 242 a 332 s in una misura sola, nell'immagine della CI in locale). Il quadro fa pensare alla macchina del runner (memoria, disco o sospensione), ma non è verificato: un buco negli orari di `macchina.log` dirà una sospensione, le righe senza buchi che cosa mancava. Venti minuti senza una prova che comincia o finisce chiudono l'esecuzione con i nomi delle prove in corso; niente dump, che può pesare gigabyte nel pacchetto |
| 2026-12-01 | **Prove da capo a fondo: il tempo scorre cinque volte più in fretta con un orologio che non somma le attese** (`ScaledClock`, uno solo per `ServerTestBed` e `DesktopBed`: `Now` dipende solo dal tempo vero) **e l'unica sessione è quella chiesta con «Controlla ora»** (la prima di suo è oltre la durata della prova). `CompressedClock` resta per le prove di raccolta, con un flusso per volta. Quando un'attesa scade, la prova dice che cosa faceva Febe (motore, interruttore, sessioni, coda, azioni, eventi, stato dei file, coda del registro; mai corpi, cookie o indirizzi dei file). Sostituisce per queste prove la riga del 13 ottobre (10×) | `TheRealServerCollectsFromTheTestSite…` cadeva a volte dopo 90 s senza dire perché. `CompressedClock` sommava le attese dei lavori di sottofondo (misurato: circa 34× invece di 10×, a salti di decine di secondi): i 30 s di una pagina vera e i pochi minuti della prima sessione finivano subito, e il controllo di marta.prova falliva (riprovato un'ora dopo) o i suoi file restavano in coda. Dopo la sessione i file aspettano la prossima, almeno 20 minuti (120 s veri): allungare il limite non bastava. La causa è l'orologio: con quello nuovo, anche lasciando al motore la sua sessione a «Ho finito» (un altro account per primo in 35 giri su 40), 40 giri su 40 sono passati; la sola sessione chiesta rende certo l'ordine. Senza più la sessione del motore, «Controlla ora» si chiede di nuovo prima di aspettare la verifica: altrimenti, a sessione finita, la pausa è fra 20 e 90 minuti |
+| 2026-11-29 | **Tappa E4, risposte di Alberto alle domande 39–47 di §16** prima del codice: nessuna scelta nelle destinazioni, sempre il video intero (39); filtro «Video fermi» solo nella Libreria (40); «Cerca i video fermi» dalla selezione, un video alla volta, mai durante una sessione né con importazione, copie o ricostruzione, senza ripresa da solo (41); tutto nero o di un solo colore «Non analizzabile», non «Fermo» (42); dal visualizzatore anche durante una sessione, 30 secondi (43); soglie di base adattate alla 47 (44); il fotogramma più nitido, mai uno nero, PNG `_fotogramma` (45); solo dal visualizzatore (46); una piccola parte che si muove lascia il video «Fermo», non «In movimento» (47). Nessuna coda in sottofondo sulla libreria: resta «solo a richiesta» (risposta 9 di #58) | Le domande di E4; per 42 e 47 Alberto ha scelto l'alternativa alla proposta |
+| 2026-11-29 | Tappa E4, migrazione `0005_video_fermi.sql` (prima libera): `video_analysis` prende `frame_at_ms` e `note`, con i `CHECK` nello schema (`(outcome = 'Still') = (frame_at_ms IS NOT NULL)`, come in `export_copy`; nota sempre presente per un «Non analizzabile»): SQLite li accetta in `ADD COLUMN` e li verifica sulle righe presenti, perciò la migrazione toglie prima le righe «Fermo» e «Non analizzabile», impossibili perché nessun Febe prima di E4 scrive la tabella; le «In movimento» restano. Indice parziale `ix_video_analysis_still (sha256) WHERE outcome = 'Still'` per il filtro. `VideoAnalysisStore` fa gli stessi controlli. Codici in `VideoAnalysisNotes`: `FrameNotAvailable`, `DurationUnknown`, `Unreadable`, `TooSlow`, `AllDark`, `SingleColor`, e `SmallMotion` su un «Fermo». Gli esiti non vanno in `_febe.jsonl` e non sono legati a `media`: un database perso li perde, e si rifanno a richiesta | «Salva il fotogramma» deve sapere l'istante scelto senza rifare l'analisi; un vincolo nello schema vale anche per ciò che non passa dall'archivio; senza il `DELETE` una riga scritta a mano fermerebbe l'avvio |
+| 2026-11-29 | Tappa E4, **algoritmo 1** (`StillVideoAnalyzer`, sopra `VideoFrameReader`: fotogrammi esatti agli istanti mostrati, elenchi di modifiche compresi, diritti). Sette fotogrammi, uno in ognuna di sette parti uguali (dove, dal 2026-12-01: riga «revisione dell'analisi»), uno sì e uno no spostato sul fotogramma chiave mostrato più vicino entro un quarto di parte (`LocateNearKey`, nuovo: uno chiave si decodifica da solo). Griglia 32 × 32 di medie di luma BT.709, B−Y, R−Y e quota di pixel bruciati (un canale da 250 in su), più la griglia fitta del 2026-12-01. Scuro: nessun blocco con la media di R, G o B da 32 in su (non sulla luma: un blu puro ha luma 18); gli scuri all'inizio e alla fine si mettono da parte, uno fra due immagini si confronta (dal 2026-12-01, riga «seconda revisione dell'analisi»; prima voleva dire «In movimento»). Dissolvenza: guadagno = mediana dei rapporti dei blocchi (non scuri, non bruciati) solo se concordano (come, dal 2026-12-01: stessa riga), il più chiaro scalato verso il più scuro, così il rumore non si amplifica; i blocchi con più del 10 % di pixel bruciati restano fuori dalla stima (se ne avanzano abbastanza). Differenza di un blocco = ΔY + 0,25 · (Δ(B−Y) + Δ(R−Y)), in valore assoluto. Immagine ferma = mediana inferiore dei fotogrammi blocco per blocco, portati alla luce del più chiaro. Mentre decodifica, una coppia di fotogrammi con la media oltre 3 o i blocchi cambiati oltre il 15 % (tre volte il 5 %: un oggetto cambia il posto vecchio, quello nuovo e i bordi dei blocchi) dice subito «In movimento» e il resto non si decodifica. Tutti scuri: `AllDark`; tutti di un solo colore (deviazione standard dei blocchi sotto 2 su luma e croma): `SingleColor` | Il metodo di prima (`VideoFrameDecoder.AnalyseStillness`, mai chiamato, ora tolto) confrontava solo con il primo fotogramma e si rompeva sulle dissolvenze; la mediana non contiene l'adesivo che si sposta, quindi ogni fotogramma ne differisce solo dove l'adesivo sta. Con un guadagno solo una dissolvenza su colori saturi dava il 7,8 % dei blocchi cambiati e risultava «In movimento» |
+| 2026-11-29 | Tappa E4, **soglie con le misure** (costanti di `StillVideoAnalyzer`; video costruiti dalle prove, `PcmVideos`, 144 × 256 a 30 fps, e flussi di conformità, rimisurati il 2026-12-01 con la revisione dell'analisi; D = differenza media con ogni blocco limitato a 12, A = quota di blocchi oltre 12). Fermo: D ≤ 3 (`MeanThreshold`), A ≤ 5 % (`AreaThreshold`), blocco cambiato oltre 12 (`BlockThreshold`). **Fermi**: immagine fissa D 0, A 0; grana ±3 0,40 / 0; grana ±8 0,98 / 0; dissolvenza dal nero di 9 fotogrammi su 30 0,41 / 0, di 20 su 30 0,33 / 0; al nero 1,85 / 0; luce che pulsa fra 60 % e 100 % 0,35 / 0; tutti sfocati tranne uno 0,29 / 0 (scelto quello nitido); coppie dissolte al 95 % 0,42, all'80 % 0,39, al 60 % 0,64, al 40 % 1,06, al 20 % 1,69, A sempre 0. **In movimento**: gradiente della dimostrazione D 11,98, A 99,4 %; panoramica di 1 px a fotogramma 4,52 / 13,4 %, di 2 px 3,45 / 10,6 %; due foto in sequenza 6,14 / 50,1 %; conformità H.264 D 3,3–12, A 15–99,9 %; HEVC D 1,2–12, A 4–99,8 % (i più bassi sono quelli decisi dalla coppia o dalla griglia fitta). Un campo di un solo colore dissolto al 20 % dà D 3,18 (quantizzazione): per questo il colore unico si guarda prima, e si guarda che il colore sia lo stesso in tutti i fotogrammi. I numeri valgono per i video costruiti: i video veri del telefono (grana, esposizione automatica, ricodifiche di Instagram) sono **da provare dal vivo** (`docs/prove-dal-vivo.md`, F8). Un cambio della regola o delle soglie alza `Algorithm` a 2: le righe vecchie restano e si rianalizza a richiesta, senza migrazione | Il peggiore dei fermi è lontano dalle soglie (D 1,85), il movimento più lento provato supera di poco quella della media (panoramica di 2 px: D 3,45, A 10,6 %): per questo servono le prove su video veri; §15 E4 vuole le soglie scritte |
+| 2026-11-29 | Tappa E4, **piccola parte che si muove** (risposta 47): tolleranza di area al 5 % dei blocchi al posto della soglia sul blocco peggiore (16 su 255) della prima proposta. Misure: adesivo che attraversa la foto, 1 % dell'area → A 1,95 %, Fermo; 2,6 % → 4,1 %, Fermo; 3,6 % → 4,79 %, Fermo; 4,1 % e 4,5 % → 5,47 %, In movimento; 6,9 % e 10,4 % → coppie al 17,0 % e 19,6 %, In movimento. Adesivo a scacchi animato sul posto, 1–10,4 % dell'area → A 0,8–2,0 %, Fermo (gli scacchi da 4 px si mediano nei blocchi: prova debole). Scritta che scorre: 8 px su 256 (3,1 %) e 10 px (3,9 %) → 2,95 %, Fermo; 12 px (4,7 %) → 4,88 %, Fermo, ma 5,08 %, In movimento, in un altro punto dell'immagine; 16 px (6,3 %) → 5,9 %, In movimento; 24 px → 8,85 %; 64 px (25 %) → coppia al 24,2 %. **Da sapere**: contano interi i blocchi toccati solo in parte, quindi il 5 % è in pratica un oggetto del 4 % circa, e una scritta alta fra 1/32 e 1/20 dell'immagine è ferma o no secondo dove cade nei blocchi; con l'8 % passerebbe anche una di due righe di blocchi. Tenuto il 5 % detto ad Alberto, da guardare con le prove dal vivo. Un «Fermo» in cui qualche blocco ha superato 12 ha la nota `SmallMotion` («· una piccola parte si muove») | Con la soglia sul blocco peggiore l'adesivo era «In movimento», contro la risposta 47; la nota dice perché il fotogramma non è tutto il video |
+| 2026-11-29 | Tappa E4, **fotogramma scelto**: il più nitido dei fotogrammi guardati e non scuri, con la nitidezza = varianza del laplaciano (4 vicini) della luma a piena risoluzione; a pari nitidezza il primo mostrato. L'istante si salva in millisecondi arrotondati in su (`ExportFrames.ActualMs`, come nelle copie), quindi «Salva il fotogramma» decodifica proprio il fotogramma guardato. **Nessun codice «troppo breve»**: un video di un fotogramma è quell'immagine, una clip di 0,4 s si analizza come le altre | A piena risoluzione perché la sfocatura leggera sparisce in un'immagine ridotta a 128 px; un video brevissimo non è illeggibile |
+| 2026-11-29 | Tappa E4, **tempi e limiti**: 30 s dal visualizzatore, 2 min per video dalla selezione (risposta 44), tempo reale come nei fotogrammi di E3; lo SHA-256 rifatto prima e l'attesa di `ConversionThrottle` non contano. Oltre i 30 s non si salva nulla; oltre i 2 min si salva «Non analizzabile» `TooSlow`, e un altro avvio della selezione ci riprova, una volta (2026-12-01). Misure (compilazione Release, questo PC; in movimento / sette fotogrammi comunque / variante ferma): H.264 176 × 144 16 / 66 / 34 ms, 352 × 288 39 / 125 / 30 ms; HEVC 416 × 240 63 / 221 / 87 ms, 832 × 480 177 / 672 / 359 ms, 1016 × 760 con 500 fotogrammi e un solo IDR 1,0 / 4,0 / 0,29 s (Debug 5,1 / 21 / 1,3 s), 2560 × 1600 0,78 / 1,8 / 1,8 s; rimisurate il 2026-12-01 (in movimento / variante ferma): H.264 176 × 144 18 / 29 ms; HEVC 416 × 240 76 / 104 ms, 832 × 480 133 / 208 ms; 1920 × 1080 0,67–0,86 s; 2560 × 1600 1,08 s; 1088 × 1920 I_PCM fermo 0,49 s. Stima, non verificata: un 1080p del telefono con un fotogramma chiave ogni 1–2 s circa 2–4 s (tre fotogrammi non sono chiave); un 1080p di 60 s con un solo IDR 35–40 s, oltre il visualizzatore ma entro la selezione | Un GOP lungo va decodificato tutto; il limite della selezione è il più largo che c'è, perciò si dice e si salva |
+| 2026-11-29 | Tappa E4, **`StillVideoService`** (in `Febe.Core`, con un `Func` per trovare il file e un richiamo `Changed` al posto di `IMediaFileResolver` e `LibraryChanges`, che stanno in `Febe.Web`). Un'analisi dal visualizzatore ferma quella della selezione in corso, che torna in testa alla coda; due del visualizzatore vanno una alla volta. Il lavoro della selezione è in memoria, un file (SHA-256) una volta, i conteggi della conferma sono per file; non prende lease di `LongWorkGate` (non deve bloccare importazione e copie) ma aspetta prima di ogni video e, ogni 5 s durante l'analisi, guarda se è cominciata una sessione o un lavoro lungo e allora lascia il video senza salvare nulla; passa da `ConversionThrottle`, così non decodifica insieme alla conversione della libreria. File andato, cambiato o errore imprevisto: «saltato», niente salvato, nel registro solo il tipo. «Interrompi» vuota la coda; alla chiusura `FebeApp` chiude il servizio e ne aspetta il ciclo prima dell'archivio (al più 5 s, 2026-12-01). Un file che non si apre, o che smette di leggersi, non salva `Unreadable` (poteva essere un blocco momentaneo) | «Mai durante una sessione» e «mai insieme a importazione, copie, ricostruzione» (risposta 41) devono valere anche per un'analisi di due minuti, senza tenere fermo nessuno |
+| 2026-11-29 | Tappa E4, **«Salva il fotogramma»**: `GET /api/media/{id}/still/frame` per l'anteprima e «Scarica» (mai in cache: una nuova analisi può scegliere un altro fotogramma allo stesso indirizzo) e `FrameMode.Still` (`mode: "fermo"`, impostazione del lavoro «Fermo») per «Nella cartella delle copie»: suffisso `_fotogramma`, identità `export_copy` di E3 (variante, formato, istante). Un video non fermo o mai analizzato si conta (`notStill`) e non crea un elemento del lavoro, perché il `CHECK` di `export_item` vuole l'istante; il modo vale per un solo file anche nel Core (risposta 46) e gli altri indirizzi dei fotogrammi lo rifiutano con 400. «Copia di nuovo» di una copia `_fotogramma` la riconosce dal nome e lo ridà (2026-12-01). «Scarica» passa da una richiesta e non da un collegamento, così un 409 o un 503 si legge | Il fotogramma è una copia come le altre; un 409 dentro un collegamento scaricherebbe un file di errore |
+| 2026-11-29 | Tappa E4, **filtro «Video fermi»** (`LibraryKindFilter.StillVideos`, `kind=stillvideos`): la lista degli SHA-256 fermi da `ix_video_analysis_still` con `NOT EXISTS` di un algoritmo più alto; raggruppato, `+e.id IN (lista)` con un `CROSS JOIN` dalla lista a `ix_media_sha256_entry` e il controllo «video in libreria» su `ix_media_entry_files`; in «Tutte le foto» `+m.sha256 IN (lista)`. Nessun indice nuovo oltre a quello della `0005` (un indice parziale su `media` non veniva scelto senza `ANALYZE`). Misure di `LibraryScaleTests` (200.000 elementi, 21.359 analisi, 11.409 «Fermo», 10.005 nel filtro; senza statistiche / con `ANALYZE`, Debug): finestra 55 / 55 ms, a metà 101 / 105, tutte le foto 73 / 86, un account 75 / 82, un account in tutte le foto 93 / 96 (limite 250); totali 128 / 126, giorni 131 / 131, giorni di tutte le foto 200 / 192 (limite 600); giorni di un account 78 / 83 e 91 / 77 (limite 1500). La lista costa circa 44 ms per 10.000 video fermi e cresce con loro, non con la libreria | Senza il `+` e il `CROSS JOIN` SQLite partiva da `ix_media_state` (88 ms) o, nei conteggi per elemento di «Tutte le foto», girava tutti gli SHA fermi per ogni elemento: 1,1 s la finestra, 107 s i totali di un account |
+| 2026-11-29 | Tappa E4, **interfaccia**: un evento `fermi` ridisegna solo il pannello del visualizzatore (il video non riparte) e rinfresca la Libreria solo con il filtro «Video fermi»; «Analizza di nuovo» su ogni «Non analizzabile» e su un esito di un algoritmo vecchio, se i fotogrammi si possono prendere; la pagina che ha avviato la ricerca la segue ogni 1,5 s anche cambiando pagina e ne dice la fine una volta. Nessun segno sulle tessere. **Dimostrazione**: due video fermi (il più recente di @marta.demo su un'immagine senza copie: quale, dipende dal giorno e dall'ora, anche una storia o vecchio di mesi; e una storia video di un altro account), ognuno con il suo file costruito dalla copertina (240 × 432, 16 fotogrammi, i primi due dissolti) e la sua impronta vera, analizzati davvero; `VerifySource` spento solo nella dimostrazione, per i video che condividono il file che si muove | Un fermo condiviso sulle impronte delle copertine darebbe «non corrisponde» a «Nella cartella delle copie»; ridisegnare la Libreria a ogni video analizzato sposterebbe ciò che si guarda |
+| 2026-12-01 | Tappa E4, **revisione dell'analisi** (sempre algoritmo 1: non è ancora uscito). (a) I sette istanti stanno a punti diversi dentro le sette parti (`Offsets`, i cui numeri sono della riga «seconda revisione dell'analisi»), su ciò che la traccia mostra e non sulla durata dichiarata; solo uno sì e uno no va sul fotogramma chiave vicino; al più sette immagini si guardano tutte, e se gli istanti cadono su meno immagini se ne aggiungono per posizione. (b) Griglia fitta (fino a 128 per lato, celle di almeno 4 px, solo luma) con le stesse soglie, per neve, fiocchi e scritte piccole. (c) Il bianco bruciato si conta canale per canale e ciò che può nascondere si toglie dalla differenza; il guadagno usa anche i blocchi bruciati se gli altri non bastano. (d) Nero e colore unico anche sui pixel: `BrightDetail` 96, varianza 64, scarto 32, quota 0,0002; il colore dev'essere lo stesso in tutti i fotogrammi. (e) Un solo fotogramma non nero: se ne guardano altri lì intorno (`Around`), e `AllDark` se lì c'è altro che non si è visto. (f) Un fotogramma da guardare che manca: `Unreadable`, salvo movimento già visto. (g) Istanti oltre 1e9 s: `DurationUnknown`; l'annullamento vale anche mentre si cerca il punto d'ingresso. Misure: filmati ripetuti da 4 a 20 volte sempre «In movimento» con due fotogrammi; 720 × 1280 rumore pieno D 5,94, A 21,1 %, In movimento; 1.000 fiocchi 4 × 4 a 720 × 1280 A 7,3 %, In movimento, 300 A 2,3 %, Fermo con `SmallMotion`; 1.000 a 1088 × 1920 A 4,0 %, Fermo con `SmallMotion`; trame che scorrono D 4,3–4,7, In movimento; nessun flusso di conformità è diventato «non si legge» | Sette centri uguali su fotogrammi chiave dicevano «Fermo» di un filmato ripetuto, di un video tagliato o rovinato e di ciò che si muove sotto i blocchi; «In movimento» di una scheda bianca che si dissolve |
+| 2026-12-01 | Tappa E4, **errori di lettura**: il flusso dell'analisi ricorda la prima `IOException` (non `EndOfStreamException`) o `UnauthorizedAccessException` e `Analyse` la rilancia: dal visualizzatore «file assente», dalla selezione «saltato», niente salvato. **Troppo lento**: una riga `TooSlow` non vale come già analizzata (`IsSettled`), ogni avvio la riprova una volta; il visualizzatore oltre i 30 s dice «avviala dalla selezione» solo se la selezione lo analizzerebbe, altrimenti «resta l'esito di prima» (`TooSlowKept`). **File**: se quello in coda non è sul disco si usa un altro della libreria con lo stesso SHA-256. **In coda**: `added` nella risposta di `/start`. **Chiusura**: `FebeApp` aspetta al più 5 s il video al lavoro (l'esito non si salverebbe comunque); `FebeAppHooks.StillVideoAnalyser` per le prove | Un disco di rete staccato a metà lasciava «non si legge» per sempre; «avviala dalla selezione» mandava a una selezione che saltava il video; una lettura ferma teneva fermi motore e browser alla chiusura |
+| 2026-12-01 | Tappa E4, **eventi `libreria`**: in attesa uno per motivo (`PendingLibraryChanges`, riempito direttamente, non dal canale che scarta), e a ogni giro un evento per ognuno: Dashboard e Account saltano `fermi`, che non cambia nulla lì. **Visualizzatore**: un evento `fermi` conta se l'elemento ha un video (l'esito è del file, non dell'account); conta solo l'ultima rilettura; si chiude quando cambia la pagina sotto (`febe:pagina`). **Copie**: `ExportCopyRequest.Still` dal nome `_fotogramma` (anche « (2)»); un lavoro «Fermo» il cui file è cambiato prende l'istante dell'analisi nuova o salta con la nota `NotStill` (l'istante dell'elemento del lavoro non cambia: è la sua identità) | Un evento solo, l'ultimo, faceva perdere la fine di una copia durante «Cerca i video fermi»; un fotogramma qualunque di un file nuovo non è quello che Alberto ha scelto |
+| 2026-12-01 | Tappa E4, **seconda revisione dell'analisi** (sempre algoritmo 1: non è ancora uscito) e di ciò che le sta intorno. (a) `Offsets` = 0,54, 0,865, 0,417, 0,253, 0,432, 0,45, 0,46, trovati con una ricerca: di un filmato ripetuto da 1,9 a 40 volte, anche non un numero intero, i sette istanti abbracciano almeno il 49 % del giro (la prova chiede il 48 %); con quelli di prima il 28 %, e a quasi sette ripetizioni cadevano tutti insieme. Fra fotogrammi veri (18.054 coppie di numero di fotogrammi e periodo) i sette stanno entro mezzo giro in 5 casi (prima 820) ed entro il 40 % in nessuno (prima 338); il tratto più lungo non guardato è di 1,32 parti, il primo e l'ultimo istante restano lontani dalle estremità. Limite dichiarato: un'immagine mostrata per meno di metà giro può sfuggire. (b) Guadagno di una dissolvenza: per blocco il canale più forte non bruciato (non la luma: un blu puro ne ha poca), da 8 in su (`GainFloor`, era 16), almeno 10 blocchi (`GainBlocks`); mediana dei rapporti pesata sulla luce, e concordano se almeno metà della luce sta entro ±5 % (`GainAgreement` 0,1 in tutto) o 1,5 livelli, se sono di più (`GainNoise`); poi il rapporto fra le somme dei blocchi concordi; campo da 1/16 a 16 (`GainRange`, era 8). Prima con i soli blocchi non bruciati, poi con tutti, poi nessun guadagno. (c) Un fotogramma scuro fra due che non lo sono si confronta con l'ultimo chiaro (movimento con la media oltre 3 o l'area oltre il 15 %) e poi con la mediana, e non si sceglie mai. (d) Stesso colore: il canale più forte non bruciato del fotogramma più chiaro, guadagno entro 1/16–16, sul fotogramma come un blocco solo. (e) Un elemento «Fermo» di un lavoro tiene sempre lo SHA-256 sul quale il suo istante è stato scelto: registrarvi quello del file nuovo prima di scriverlo faceva credere, alla ripresa, che il file non fosse cambiato. (f) Anche ogni dialogo si chiude quando cambia la pagina sotto (`febe:pagina`), come se fosse annullato. Misure: 26 immagini × 11 dissolvenze × 2 grane, tutte «Fermo» (prima circa 150 no); scritta, marchio e banda sul nero, foto scure al 10, 14 e 18 %, cartello blu, dissolvenze da 0,5 a 2 s, sempre «Fermo» con D ≤ 0,59 e A 0; sfumature e scritte intorno alla soglia del nero con grana fino a ±10, mai «In movimento»; due immagini in un giro ripetuto circa 7 volte, sempre «In movimento». Resta «In movimento» ciò che ricomprime ogni fotogramma a blocchi 8 × 8 con passo da 8 in su, come prima | Un'immagine ferma su nero, un cartello blu o una foto scura che si dissolvono, o scure quanto la soglia, risultavano «In movimento», e un filmato di due immagini ripetuto circa 7 volte «Fermo»; «Salva il fotogramma» ripreso dopo una pausa salvava l'istante vecchio; una finestra aperta dal visualizzatore o dalla selezione restava sopra la pagina nuova, con i bottoni di ciò che non si vede più |
diff --git a/docs/guida/Dashboard-e-arresti.md b/docs/guida/Dashboard-e-arresti.md
index 3845597..9ecc988 100644
--- a/docs/guida/Dashboard-e-arresti.md
+++ b/docs/guida/Dashboard-e-arresti.md
@@ -36,7 +36,7 @@ Comandi: **«Metti in pausa»** (Febe non apre nulla finché non premi «Riprend
browser»**, **«Diagnostica»** (vedi sotto).
La Dashboard ha due schede: **Motore**, tutto quello che c'è qui sopra, ed **Esportazione**, con le
-[copie esterne](Esportazione) in corso, da riprendere e già fatte. Le copie non fermano il motore e non usano Instagram;
+[copie esterne](Esportazione) in corso, da riprendere e già fatte e la ricerca dei video fermi. Le copie non fermano il motore e non usano Instagram;
quando una copia aspetta di essere ripresa, la scheda Motore lo dice con un avviso.
## Il rapporto di diagnostica
diff --git a/docs/guida/Esportazione.md b/docs/guida/Esportazione.md
index aa2af57..a1d3346 100644
--- a/docs/guida/Esportazione.md
+++ b/docs/guida/Esportazione.md
@@ -5,9 +5,9 @@ cartella di rete, un'altra cartella del server. La libreria non cambia: Febe leg
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 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.
+In questa versione (tappa E4) ci sono le copie degli originali, i formati delle copie, la conversione della libreria, i
+fotogrammi dei video e l'analisi dei video fermi (vedi «Video fermi»). Le copie automatiche arrivano con la tappa E5:
+fino ad allora il comando «Automatica» non c'è.
> **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
@@ -228,6 +228,47 @@ tutto». Al più 1.000 fotogrammi per video («Più di 1.000 fotogrammi per un v
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.
+## Video fermi
+
+Un **video fermo** mostra sempre la stessa immagine, per esempio una foto con la musica: basta un fotogramma. Febe lo
+controlla **solo quando glielo chiedi**, mai da sola su tutta la libreria, e ricorda la risposta.
+
+**Dal visualizzatore**, sotto un video: **«È un video fermo?»**. Guarda sette fotogrammi sparsi nel video e risponde in
+pochi secondi, anche mentre il motore è in sessione. Se ci vorrebbero più di 30 secondi dice «L'analisi richiede troppo
+tempo: avviala dalla selezione» (o «…: resta l'esito di prima», se il video ne ha già uno) e non cambia nulla. La
+risposta resta nel pannello File, riga «Video fermo»:
+
+- **«Un'immagine sola per tutto il video: basta un fotogramma»**: il video è fermo, ha l'etichetta «Video fermo» e il
+ pulsante «Salva il fotogramma». Se una **piccola parte** si muove (un adesivo animato, una scritta bassa che scorre: i
+ riquadri che cambiano sono al più il 5 % dell'immagine, cioè in pratica un oggetto un po' più piccolo) il video è fermo
+ lo stesso, e la riga aggiunge «una piccola parte si muove»;
+- **«No: l'immagine cambia»**: il video è in movimento;
+- **«Non analizzabile»**, con il motivo: il video è tutto nero o tutto di un solo colore, non si legge, la sua durata
+ non si conosce, è in un codec che Febe non decodifica, oppure l'analisi richiedeva troppo tempo. «Analizza di nuovo»
+ ci riprova, quando i fotogrammi del video si possono prendere.
+
+Le dissolvenze dal nero e al nero non contano come movimento, nemmeno di una scritta sul nero, di un cartello di un
+colore solo o di una foto scura.
+
+**Dalla selezione**, in Libreria e nella scheda di un account: «Seleziona», scegli le tessere, **«Cerca i video
+fermi»**. La finestra conta prima («28 video da analizzare · 12 già analizzati · le 5 foto si saltano»), poi Febe
+analizza un video alla volta, al più due minuti l'uno, mai durante una sessione del motore né mentre lavorano
+importazione, copie o ricostruzione: quelle partono subito, e la ricerca aspetta. L'avanzamento e **«Interrompi»** sono
+nella Dashboard, scheda Esportazione; alla fine un avviso dice quanti sono i fermi, con «Mostra i video fermi». Se
+chiudi Febe a metà, la ricerca non riprende da sola: rilanciala, e i video già analizzati si saltano (non quelli la cui
+analisi richiedeva troppo tempo: a ogni ricerca Febe ci riprova).
+
+**Il filtro «Video fermi»**, in Libreria fra i tipi, dopo «Video», mostra ciò che le analisi hanno trovato finora (un
+video mai analizzato non c'è). Non sta nelle schede degli account.
+
+**«Salva il fotogramma»**, nel visualizzatore di un video fermo, salva il fotogramma **più nitido** fra quelli guardati,
+mai uno nero di una dissolvenza: PNG (di solito), JPG (con perdita) o WEBP senza perdita, con «Scarica» o «Nella
+cartella delle copie», e il nome `video_fotogramma.png` (anche con «Copia di nuovo»). **Il fotogramma non ha l'audio.**
+Si salva un video alla volta.
+È un fotogramma come gli altri: non fa «copiato» il video.
+
+**«Copia in…» copia sempre il video intero**, anche quando è fermo: il video tiene l'audio.
+
## Conversione della libreria
Oltre alle copie, Febe può tenere **nella libreria** un file convertito accanto a ogni foto o video: Impostazioni ▸
@@ -269,6 +310,8 @@ 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.
+- **Video fermi** (quando hai chiesto «Cerca i video fermi»): quanti analizzati e quanti fermi, perché aspetta,
+ **«Interrompi»**; finita la ricerca, il riepilogo con «Mostra i video fermi», finché Febe non si chiude.
- **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
diff --git a/docs/guida/Home.md b/docs/guida/Home.md
index 5827132..f40bd20 100644
--- a/docs/guida/Home.md
+++ b/docs/guida/Home.md
@@ -51,6 +51,8 @@ fare solo con Instagram o su Windows:
`/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).
+- **Video fermi (tappa E4, 29 novembre 2026):** pronti, da provare dal vivo: le soglie dell'analisi sono tarate su video
+ costruiti, non ancora su video veri. Vedi [Copie esterne](Esportazione), «Video fermi».
## Pagine della guida
@@ -62,7 +64,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…», formati, fotogrammi, conversione della libreria, 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, video fermi, 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/Libreria.md b/docs/guida/Libreria.md
index cf864df..104e538 100644
--- a/docs/guida/Libreria.md
+++ b/docs/guida/Libreria.md
@@ -5,9 +5,11 @@ anche con centinaia di migliaia di elementi: carica a finestre e le miniature si
## Filtri e ricerca
-- **Tipo:** Tutto, Foto, Video, Storie, In evidenza, Taggati. «Foto» e «Video» riguardano i post (un post con almeno
- una foto, o almeno un video); storie, evidenza e taggati hanno la loro voce. «Tutto» non comprende le foto del
- profilo, che stanno nella scheda dell'account.
+- **Tipo:** Tutto, Foto, Video, Video fermi, Storie, In evidenza, Taggati. «Foto» e «Video» riguardano i post (un post
+ con almeno una foto, o almeno un video); storie, evidenza e taggati hanno la loro voce. «Video fermi» mostra gli
+ elementi di ogni tipo con almeno un video che hai fatto analizzare e che è risultato fermo
+ ([Copie esterne](Esportazione), «Video fermi»). «Tutto» non comprende le foto del profilo, che stanno nella scheda
+ dell'account.
- **Account**, **Periodo** (ultimi 7 o 30 giorni, quest'anno, l'anno scorso, oppure dal… al…), **Provenienza**
(scaricati da Instagram o importati). Ogni menu mostra il nome del filtro finché non scegli un valore.
- **Ricerca** per nome dell'account e testo della didascalia (senza distinguere maiuscole e accenti).
@@ -27,7 +29,7 @@ nome nel suggerimento):
dell'elemento, poi la posizione nella serie). È utile quando un post ha più foto. La tessera di un file di una serie
dice la sua posizione («2/4»); la riga del giorno conta i file («23 file nuovi») e il titolo dice file ed elementi
(«61.034 file in 48.212 elementi di 38 account»). Con «Foto» e «Video» si vedono solo le foto, o solo i video, dei
- post. Un file non ancora scaricato non ha tessera.
+ post; con «Video fermi» solo i video fermi. Un file non ancora scaricato non ha tessera.
Filtri, ricerca e caricamento a finestre funzionano allo stesso modo nei due modi. Febe ricorda la scelta in questo
browser, una per la Libreria e una per le schede degli account. A differenza del tema, che Febe salva e ritrova in
@@ -44,8 +46,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**;
-- 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.
+- per i video, **«Fotogramma»** e **«È un video fermo?»** (o «Salva il fotogramma» se lo è); con le copie esterne,
+ **«Copia in…»** (vedi [Copie esterne](Esportazione)); nel pannello File la riga «Video fermo», le righe delle copie e,
+ con la conversione della libreria accesa, dei file convertiti.
## Eliminare
@@ -67,8 +70,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); **Fotogrammi…** per i video scelti; con una cartella delle copie anche
-«Copia in…» ([Copie esterne](Esportazione)). «Fine» chiude la selezione.
+**Elimina** (con la stessa conferma di sopra); **Fotogrammi…** e **«Cerca i video fermi»** 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 90f734a..2c65359 100644
--- a/docs/guida/Problemi-comuni.md
+++ b/docs/guida/Problemi-comuni.md
@@ -159,6 +159,12 @@ Vedi anche [Copie esterne](Esportazione).
| «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 |
+| «L'analisi richiede troppo tempo: avviala dalla selezione» | «È un video fermo?» ha al più 30 secondi: seleziona il video in Libreria e premi «Cerca i video fermi», che ha due minuti per video. Se il pannello File dice già «Non analizzabile: l'analisi richiedeva troppo tempo», anche la selezione ci ha provato: ci riprova a ogni ricerca, quindi meglio quando il computer ha poco da fare |
+| «L'analisi richiede troppo tempo: resta l'esito di prima» | Hai premuto «Analizza di nuovo» e 30 secondi non bastano. L'esito che vedi nel pannello File resta, e la selezione non lo rifà: il video risulta già analizzato |
+| «Cerca i video fermi» non va avanti: «Il motore è in sessione…», «Un'importazione, una copia o una ricostruzione è al lavoro…» | È voluto: la ricerca aspetta e riprende da sola. Se hai chiuso Febe, rilanciala: i video già analizzati si saltano |
+| Un video che mi sembra fermo risulta «No: l'immagine cambia» (o il contrario) | L'analisi guarda sette fotogrammi e ammette che cambi al più il 5 % dei riquadri in cui Febe divide l'immagine: contano interi anche quelli toccati solo in parte, quindi un adesivo o una scritta vicini al 5 % possono già contare come movimento. Il fotogramma si può sempre prendere con «Fotogramma» |
+| Il filtro «Video fermi» è vuoto | Mostra solo i video che hai fatto analizzare: «È un video fermo?» nel visualizzatore, o «Cerca i video fermi» dalla selezione |
+| «Non è un video fermo, o non è stato analizzato» | «Salva il fotogramma» vale per un video risultato fermo, e una nuova analisi ha detto altro: riapri l'elemento; per un altro fotogramma usa «Fotogramma» |
| 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 |
diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md
index a97e2fc..da114c1 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 (tappe E2 ed E3): Docker con `/esporta`, FAT32, cartella di rete su Windows, formati, fotogrammi
+## F. Copie esterne (tappe E2, E3 ed E4): Docker con `/esporta`, FAT32, cartella di rete, formati, fotogrammi, video fermi
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
@@ -673,9 +673,44 @@ Prima: annota il numero dei file di una cartella di account e lo SHA-256 di due
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
+### F8. Video fermi (tappa E4)
+
+Scopo: le soglie dell'analisi (media 3 su 255, 5 % dell'immagine, `docs/decisioni.md`, 29 novembre 2026) sono tarate su
+video costruiti dalle prove. Qui si guarda se reggono con i **video veri**: grana, esposizione automatica, ricodifiche di
+Instagram. Servono una decina di video che hai già in libreria, scelti a occhio:
+
+- due o tre **foto con la musica** (post o storie), meglio se una con grana (poca luce) e una che parte dal nero;
+- una foto con un **piccolo adesivo animato** e una con una **scritta che si muove** (per esempio il testo della canzone);
+- due video del telefono **quasi fermi**: il telefono in mano davanti a una cosa ferma, e su un cavalletto;
+- un video che si muove, uno **tutto nero** o di un solo colore se ce l'hai, uno lungo (oltre un minuto) in 1080p.
+
+1. Apri ogni video nel visualizzatore e premi **«È un video fermo?»**. Annota l'esito, il tempo che ci mette e se sei
+ d'accordo. Atteso: le foto con la musica «Un'immagine sola per tutto il video: basta un fotogramma»; l'adesivo piccolo
+ lo stesso, con «una piccola parte si muove»; il video che si muove e il telefono in mano «No: l'immagine cambia»; il
+ nero «Non analizzabile: il video è tutto nero». **Da guardare**: una scritta che scorre, da circa un
+ trentaduesimo dell'immagine in su (una trentina di pixel su un 1080p messo in orizzontale, sessanta in verticale), può
+ già contare come «In movimento», secondo dove cade nei riquadri; da un sedicesimo in su conta: dimmi se la
+ vorresti ferma.
+2. Su un video fermo: **«Salva il fotogramma»**, «Scarica». Atteso: un file `…_fotogramma.png` a piena risoluzione,
+ diritto, nitido, mai scuro; la finestra dice «Il fotogramma non ha l'audio». Poi «Nella cartella delle copie».
+ Atteso: il file accanto alle copie, il video resta «Non ancora copiato» con il segno «Solo fotogrammi»; chiesto di
+ nuovo, nessun file nuovo.
+3. Dalla Libreria: «Seleziona», scegli una trentina di elementi con video e foto, **«Cerca i video fermi»**. Atteso: i
+ conteggi giusti; l'avanzamento nella Dashboard, scheda Esportazione; alla fine l'avviso con quanti sono fermi, e
+ «Mostra i video fermi» apre la Libreria filtrata. Durante una sessione del motore: atteso «Il motore è in sessione: la
+ ricerca dei video fermi riprende dopo», e riprende. «È un video fermo?» dal visualizzatore invece risponde anche
+ durante la sessione.
+4. Mentre la ricerca lavora, avvia un'importazione. Atteso: l'importazione parte subito, la ricerca aspetta.
+5. «Interrompi» a metà, poi rilancia la stessa selezione. Atteso: i video già analizzati si contano e si saltano.
+6. **«Copia in…»** su un video fermo. Atteso: arriva il video intero, con l'audio.
+7. Sul computer o sul server più lento che usi (Unraid): annota quanto ci mette «È un video fermo?» sul video 1080p
+ lungo. Oltre 30 secondi dice «L'analisi richiede troppo tempo: avviala dalla selezione»: avviala, e annota l'esito.
+
+### F9. Che cosa riferire
- Per ogni passo «come atteso» oppure il testo esatto di ciò che hai visto, con l'ora.
+- In F8 la tabella dei video (che cos'era, esito, d'accordo o no, secondi), senza nomi di persone e senza mandare i
+ video: bastano per cambiare le soglie (che diventano l'algoritmo 2).
- 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.
diff --git a/docs/schermate/01-libreria-tutte-le-foto.png b/docs/schermate/01-libreria-tutte-le-foto.png
index 1d932ca..c293b91 100644
Binary files a/docs/schermate/01-libreria-tutte-le-foto.png and b/docs/schermate/01-libreria-tutte-le-foto.png differ
diff --git a/docs/schermate/01-libreria.png b/docs/schermate/01-libreria.png
index 513123a..b41eaf8 100644
Binary files a/docs/schermate/01-libreria.png and b/docs/schermate/01-libreria.png differ
diff --git a/docs/schermate/11-libreria-fermo-tema-scuro.png b/docs/schermate/11-libreria-fermo-tema-scuro.png
index e067b05..cb9ee64 100644
Binary files a/docs/schermate/11-libreria-fermo-tema-scuro.png and b/docs/schermate/11-libreria-fermo-tema-scuro.png differ
diff --git a/docs/schermate/14-finestra-stretta.png b/docs/schermate/14-finestra-stretta.png
index 4348e18..274bce6 100644
Binary files a/docs/schermate/14-finestra-stretta.png and b/docs/schermate/14-finestra-stretta.png differ
diff --git a/docs/schermate/14-telefono.png b/docs/schermate/14-telefono.png
index 388cc56..cf4f1e1 100644
Binary files a/docs/schermate/14-telefono.png and b/docs/schermate/14-telefono.png differ
diff --git a/docs/schermate/19-libreria-copie.png b/docs/schermate/19-libreria-copie.png
index d9fa64f..904be2b 100644
Binary files a/docs/schermate/19-libreria-copie.png and b/docs/schermate/19-libreria-copie.png differ
diff --git a/docs/schermate/24-visualizzatore-fotogramma.png b/docs/schermate/24-visualizzatore-fotogramma.png
index 69c0af4..5cc0c0f 100644
Binary files a/docs/schermate/24-visualizzatore-fotogramma.png and b/docs/schermate/24-visualizzatore-fotogramma.png differ
diff --git a/docs/schermate/27-visualizzatore-da-analizzare.png b/docs/schermate/27-visualizzatore-da-analizzare.png
new file mode 100644
index 0000000..2c358eb
Binary files /dev/null and b/docs/schermate/27-visualizzatore-da-analizzare.png differ
diff --git a/docs/schermate/27-visualizzatore-non-analizzabile.png b/docs/schermate/27-visualizzatore-non-analizzabile.png
new file mode 100644
index 0000000..083d60b
Binary files /dev/null and b/docs/schermate/27-visualizzatore-non-analizzabile.png differ
diff --git a/docs/schermate/27-visualizzatore-video-fermo.png b/docs/schermate/27-visualizzatore-video-fermo.png
new file mode 100644
index 0000000..2acbc67
Binary files /dev/null and b/docs/schermate/27-visualizzatore-video-fermo.png differ
diff --git a/docs/schermate/28-salva-fotogramma.png b/docs/schermate/28-salva-fotogramma.png
new file mode 100644
index 0000000..79c7091
Binary files /dev/null and b/docs/schermate/28-salva-fotogramma.png differ
diff --git a/docs/schermate/29-libreria-video-fermi.png b/docs/schermate/29-libreria-video-fermi.png
new file mode 100644
index 0000000..7da0d9a
Binary files /dev/null and b/docs/schermate/29-libreria-video-fermi.png differ
diff --git a/docs/schermate/30-video-fermi-selezione.png b/docs/schermate/30-video-fermi-selezione.png
new file mode 100644
index 0000000..672ac1d
Binary files /dev/null and b/docs/schermate/30-video-fermi-selezione.png differ
diff --git a/docs/schermate/31-dashboard-video-fermi.png b/docs/schermate/31-dashboard-video-fermi.png
new file mode 100644
index 0000000..507b1d9
Binary files /dev/null and b/docs/schermate/31-dashboard-video-fermi.png differ
diff --git a/docs/schermate/differenze.md b/docs/schermate/differenze.md
index a5931cd..37aeda1 100644
--- a/docs/schermate/differenze.md
+++ b/docs/schermate/differenze.md
@@ -6,17 +6,17 @@ solo per l'interfaccia di Febe (§10.7).
| Schermata | Indirizzo | Mockup |
|---|---|---|
-| `01-libreria.png` | `/libreria?tema=chiaro`, puntatore su una tessera | `docs/mockup/01-libreria.png` |
-| `01-libreria-tutte-le-foto.png` | `/libreria?tema=chiaro`, «Tutte le foto» scelto (passo `tutte-le-foto.js`; presa il 25/11 da Windows) | `docs/mockup/01-libreria.png` (il mockup non ha l'interruttore, vedi sotto) |
+| `01-libreria.png` | `/libreria?tema=chiaro`, puntatore su una tessera (rifatta il 1/12 da Windows, con «Video fermi») | `docs/mockup/01-libreria.png` |
+| `01-libreria-tutte-le-foto.png` | `/libreria?tema=chiaro`, «Tutte le foto» scelto (passo `tutte-le-foto.js`; presa il 25/11 da Windows, rifatta il 1/12) | `docs/mockup/01-libreria.png` (il mockup non ha l'interruttore, vedi sotto) |
| `02-visualizzatore.png` | `/libreria`, clic su un post con più file, seconda foto | `miniature/02-visualizzatore.png` |
| `03-account.png` | `/account?tema=chiaro` | `docs/mockup/03-account.png` |
| `03-account-telefono.png` | `/account`, 390 × 844 | (nessuno: tabella come elenco) |
| `04-aggiungi-account.png` | `/account?dialogo=aggiungi`, «gaia» scritto nella casella, due profili aggiunti, puntatore su una riga (passo `aggiungi.js`; rifatta il 15/11 da Windows) | `miniature/04-aggiungi-account.png` (superato da #37, vedi sotto) |
| `05-account-impostazioni.png` | `/account/3/impostazioni` (@studio.lumen.demo) | `miniature/05-account-impostazioni.png` |
-| `11-libreria-fermo-tema-scuro.png` | `/libreria?scena=fermo&tema=scuro` | striscia rossa di `miniature/11-attivita-fermo-tema-scuro.png` |
+| `11-libreria-fermo-tema-scuro.png` | `/libreria?scena=fermo&tema=scuro` (rifatta il 1/12 da Windows) | striscia rossa di `miniature/11-attivita-fermo-tema-scuro.png` |
| `12-account-storie-tema-scuro.png` | `/account/2?tema=scuro&tipo=storie` (@marta.demo) | `miniature/12-account-storie-tema-scuro.png` |
-| `14-finestra-stretta.png` | `/libreria`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
-| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività, oggi Dashboard, al telefono) |
+| `14-finestra-stretta.png` | `/libreria`, 860 × 900 (rifatta il 1/12 da Windows) | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
+| `14-telefono.png` | `/libreria`, 390 × 844 (rifatta il 1/12 da Windows) | (il mockup mostra Attività, oggi Dashboard, al telefono) |
| `account-cronologia.png` | `/account/2/cronologia` | (nessuno) |
| `06-attivita.png` | `/dashboard?scena=sessione&tema=chiaro` (Dashboard; rifatta il 25/11 da Windows) | `miniature/06-attivita.png` |
| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto (rifatta il 25/11 da Windows: c'è la riga «Ricerche di profili») | (nessuno: §7.4) |
@@ -46,15 +46,22 @@ solo per l'interfaccia di Febe (§10.7).
| `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` |
+| `19-libreria-copie.png` | `/libreria?copie=copiati`, menu dell'icona CSV aperto (passo `menu-csv.js`; rifatta il 1/12) | 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`, 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` |
+| `24-visualizzatore-fotogramma.png` | `/libreria`, lo stesso video, righe «Copia» con «· intero» e «· fotogramma a 0:01,125 · PNG» (passo `visualizzatore-fotogramma.js`; rifatta il 1/12, con «È un video fermo?») | 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 |
+| `27-visualizzatore-video-fermo.png` | `/libreria?tipo=fermi`, il video fermo di @marta.demo, il lettore a 1 s: etichetta «Video fermo», riga «Video fermo» e «Salva il fotogramma» (passo `visualizzatore-video-fermo.js`; presa il 1/12 da Windows, come le righe seguenti) | composta da `miniature/02-visualizzatore.png` |
+| `27-visualizzatore-da-analizzare.png` | `/libreria`, un video di @marta.demo mai analizzato: «È un video fermo?» fra le azioni (passo `visualizzatore-da-analizzare.js`) | come sopra |
+| `27-visualizzatore-non-analizzabile.png` | `/libreria`, il video di @marta.demo con «Non analizzabile: l'analisi richiedeva troppo tempo» e «Analizza di nuovo» (passo `visualizzatore-non-analizzabile.js`) | come sopra |
+| `28-salva-fotogramma.png` | come la 27, «Salva il fotogramma» con «Nella cartella delle copie» (passo `salva-fotogramma.js`), 1440 × 1000 | la finestra della 22 (dialoghi di `miniature/13-foglio-di-stile.png`) sopra `miniature/02-visualizzatore.png` |
+| `29-libreria-video-fermi.png` | `/libreria?tipo=fermi` | composta da `docs/mockup/01-libreria.png` |
+| `30-video-fermi-selezione.png` | `/libreria?account=2` (@marta.demo), «Seleziona», cinque video e quattro elementi di foto, «Cerca i video fermi» (passo `video-fermi-selezione.js`), 1440 × 1000 | composta dai dialoghi del 13 sopra `docs/mockup/01-libreria.png` |
+| `31-dashboard-video-fermi.png` | `/dashboard/esportazione`, la ricerca di tutti i video della libreria al lavoro (passo `dashboard-video-fermi.js`, l'unico che avvia qualcosa: un'analisi; viene per ultima) | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) |
## Differenze che restano
@@ -203,7 +210,8 @@ barra laterale l'icona vecchia della Dashboard (quattro riquadri), finché non s
### «Raggruppa i post» / «Tutte le foto» (tappa D1, issue #59, dal 25 novembre 2026)
L'interruttore di §4.6 (§10.3 «Schermate della tappa D1») è composto dai mockup 01 e 12, che non lo hanno. Le
-schermate `01-libreria`, `01-*` e `12-*` mostrano «Raggruppa i post», il predefinito, e non sono state rifatte;
+schermate `01-libreria` e `12-*` mostrano «Raggruppa i post», il predefinito, e non erano state rifatte (la `01-libreria`
+lo è dal 1° dicembre, con la tappa E4);
`01-libreria-tutte-le-foto.png` (presa il 25/11 con il programma delle schermate da Windows) mostra «Tutte le foto» ed
è stata messa accanto al mockup 01. Le prove dell'interfaccia (`LibraryModeInterfaceTests`) girano solo nella CI e qui
non sono state eseguite; la scheda account con «Tutte le foto» non ha una schermata. Differenze:
@@ -243,7 +251,8 @@ visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui
- **«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.
+- **«È un video fermo?» non c'era** nel visualizzatore delle schermate del 27/11: è arrivato con la tappa E4 (qui sotto,
+ «Video fermi»).
- **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'è.
Le tessere degli account che non hanno una cartella delle copie, o che non si esportano, non hanno il segno.
@@ -336,7 +345,7 @@ CI. Differenze:
- **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
+ del file nel visualizzatore (720 × 1280, 0:11 nella 22, 0:10 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.
@@ -369,6 +378,66 @@ CI. Differenze:
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.
+### Video fermi (tappa E4, issue #58, dal 29 novembre 2026)
+
+Anche queste parti non hanno un mockup (§10.3 «Schermate dell'esportazione»): sono composte dai mockup esistenti, come
+dice la tabella. Il 1° dicembre le sette schermate nuove `27-…` – `31-…` sono state prese, e le sette che mostrano la riga
+«Tipo» della Libreria o le azioni di un video (`01-libreria`, `01-libreria-tutte-le-foto`, `11-libreria-fermo-tema-scuro`,
+`14-finestra-stretta`, `14-telefono`, `19-libreria-copie`, `24-visualizzatore-fotogramma`) rifatte, 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. Misure: 1440 × 900; 1440 × 1000 per le
+finestre alte (28, 30). Nessun passo copia, scarica o elimina; solo l'ultimo (31) avvia un lavoro, la ricerca dei video
+fermi, e da quel momento la pagina non rilegge l'avanzamento, perché la schermata non cambi mentre si prende. Le stesse
+parti sono state guardate anche in tema scuro, a 860 × 900 e a 390 × 844 (senza schermata nella cartella). Le 18, 21, 22,
+23 e 25 non sono state rifatte: dietro alle loro finestre la riga «Tipo» non ha ancora «Video fermi», e nel visualizzatore
+della 22 manca «È un video fermo?». Le prove dell'interfaccia (`ExportInterfaceTests.StillVideos.cs`) girano nella CI.
+Differenze:
+
+- **Visualizzatore** (mockup 02): l'etichetta «Video fermo» dopo «Profilo privato», con lo stile di «Seguito»; nel
+ pannello File la riga «Video fermo» dopo «Durata», con «Un'immagine sola per tutto il video: basta un fotogramma ·
+ fotogramma a 0:00,375», «No: l'immagine cambia» o «Non analizzabile: …»; «Analizza di nuovo» sotto il valore, come
+ «Copia di nuovo» delle copie (E2). Fra le azioni, dopo «Fotogramma», «È un video fermo?» (mai analizzato) o «Salva il
+ fotogramma» (fermo); un video in movimento o non analizzabile non ha nessuna delle due. Sono sei azioni, tre nel
+ mockup.
+- **«Salva il fotogramma»**: la finestra «Fotogrammi» della tappa E3 (22) senza i tre modi e il cursore: solo
+ l'anteprima del fotogramma scelto, «Il fotogramma più nitido fra quelli guardati dall'analisi, a 0:00,375.», poi le
+ stesse parti «Formato» (con «Il fotogramma non ha l'audio.») e «Dove».
+- **Libreria** (mockup 01): una pastiglia in più, «Video fermi», fra «Video» e «Storie»; non c'è nella scheda account
+ (risposta 40). A 1440 px i filtri restano su una riga e gli strumenti di destra sulla seconda; con un account e un
+ intervallo di date scelti insieme i menu vanno su una riga loro e le righe diventano tre. Al telefono le pastiglie
+ stanno su due righe, come prima. Le tessere non hanno un segno «fermo».
+- **Selezione** (mockup 01 e 12): «Cerca i video fermi» dopo «Fotogrammi…» nella barra, che a 860 px va su due righe e al
+ telefono su quattro (con il conto degli elementi). La conferma è un dialogo del 13: il conto in grassetto («4 video da
+ analizzare · 1 già analizzato · le 12 foto si saltano»: le foto sono i file degli elementi scelti, non gli elementi),
+ due righe d'aiuto, «Annulla» e il pulsante principale «Analizza 4 video».
+- **Dashboard → Esportazione** (mockup 06 e 09): il blocco «Video fermi» fra «Da riprendere» e «Conversione della
+ libreria», solo dopo una ricerca. Al lavoro ha titolo, misuratore, conteggio e «Interrompi», come la copia in corso
+ (passo 2 dell'importazione); finita, una riga («Analizzati 58 video: 0 fermi, 58 in movimento.») in un riquadro come
+ quello della conversione, con «Mostra i video fermi» se ce ne sono.
+- **Contenuti dimostrativi.** La dimostrazione ha due video fermi (uno di @marta.demo, una storia di un altro account),
+ fatti dalla loro copertina: 240 × 432, 2 secondi. Tutti gli altri video sono lo stesso video che si muove, quindi una
+ ricerca non ne trova altri di fermi e la 31 non mostra «1 fermo». Il percorso nella 28 è quello della cartella
+ temporanea della dimostrazione.
+- **Confronto con le immagini** (1° dicembre): etichetta, riga e azioni della 27 hanno posto, misure e colori di quelle del
+ mockup 02; la 28 ha intestazione, piede e parti dei dialoghi del 13, come la 22; pastiglia e barra della selezione sono
+ quelle del mockup 01; misuratore e pulsanti della 31 quelli del foglio di stile. Nessuna differenza da segnalare oltre a
+ quelle qui sopra e ai ritocchi seguenti.
+- **Sistemato il 1° dicembre** dopo il confronto:
+ - in «Salva il fotogramma» la riga sotto l'anteprima aveva 12 px in più sotto, e la prima parte finiva più larga delle
+ altre: ora le parti hanno lo stesso respiro;
+ - al telefono le azioni del visualizzatore, in colonna, prendevano quasi tutto il pannello (restava una riga): ora sono
+ a due a due, e si leggono etichette e data;
+ - al telefono «Seleziona» della Libreria usciva dal bordo destro quando c'è «N doppioni da decidere»: ora gli strumenti
+ di destra vanno a capo;
+ - nella Libreria, quando i menu dei filtri vanno su una riga loro, partivano 6 px più a destra delle pastiglie: ora sono
+ allineati;
+ - al telefono, nella Dashboard, le righe di «Ultimi lavori» non stavano nel riquadro («Resoconto» usciva a destra e il
+ nome della cartella non si vedeva): ora data, lavoro e stato con «Resoconto» vanno uno sotto l'altro.
+- **Senza schermata:** «Analisi in corso…», la riga «No: l'immagine cambia» e «· una piccola parte si muove», «Salva il
+ fotogramma» con «Scarica», «Cerca i video fermi» nella scheda account, l'avviso ambra dell'attesa (importazione, copie,
+ sessione) nella conferma e nella Dashboard, il riepilogo a lavoro finito e l'avviso breve con «Mostra i video fermi», il
+ tema scuro, la finestra stretta e il telefono delle parti nuove.
+
### 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
@@ -384,4 +453,5 @@ disposizione, misure e colori, non più per la forma delle lettere e dei segni:
- **Icone.** Le icone sono disegnate per Febe sulla stessa griglia di 24 con lo stesso spessore: stesso posto, stessa
misura e stesso significato, ma il disegno è diverso da quello dei mockup (per esempio l'ingranaggio, la stella, le
frecce circolari).
-- Le schermate non sono state rifatte: si rifanno alla prossima tornata (`dotnet run --project tools/Febe.Schermate`).
+- Le schermate rifatte o nuove dal 25 novembre (la tabella dice quali) hanno già il carattere e le icone di adesso; le
+ altre si rifanno alla prossima tornata (`dotnet run --project tools/Febe.Schermate`).
diff --git a/docs/stato.md b/docs/stato.md
index 465ef0e..465525a 100644
--- a/docs/stato.md
+++ b/docs/stato.md
@@ -1,8 +1,8 @@
# Stato
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
-Aggiornato il 29 novembre 2026 (confermate da Alberto le risposte delle domande 19–38 di §16; tappa E3 Formati e
-fotogrammi; prima, E2 Copie esterne e E1 Schema unita in `main` con #69 e la catena della
+Aggiornato il 1º dicembre 2026 (tappa E4 Video fermi; #67 e #43 con le decisioni di Alberto del 29 novembre, che ha
+anche confermato le risposte delle domande 19–38 di §16; prove ferme nella CI; 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
@@ -10,6 +10,51 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
## In breve
+**1º dicembre 2026: tappa E4 «Video fermi» dell'esportazione** (#58, ramo `funzione/video-fermi`). Alberto ha risposto il
+29 novembre alle nove domande della tappa, prima del codice: §16, righe 39–47.
+
+- **Analisi** (`src/Febe.Core/Library/StillVideoAnalyzer.cs`, algoritmo 1): sette fotogrammi esatti a istanti diseguali,
+ confronto a blocchi su due griglie con la luce compensata; «Fermo» se la parte che si muove è piccola (5 % dei
+ blocchi), «In movimento» o «Non analizzabile» (tutto nero, un colore solo, codec o file che non si legge, durata
+ ignota, troppo lento). Gli errori del disco non diventano un esito. Esito per SHA-256 in `video_analysis`, migrazione
+ `0005_video_fermi.sql`.
+- **Dove**: «È un video fermo?» nel visualizzatore (30 s, anche durante una sessione), «Salva il fotogramma» (il più
+ nitido, PNG, `…_fotogramma.png`, «Il fotogramma non ha l'audio»; solo dal visualizzatore), «Cerca i video fermi» dalla
+ selezione (un video alla volta, 2 min l'uno, mai durante una sessione, un'importazione, le copie o una ricostruzione;
+ avanzamento e «Interrompi» in Dashboard → Esportazione; non riprende da sola), filtro «Video fermi» in «Tipo», solo in
+ Libreria. La copia resta sempre il video intero.
+- **Revisione a più lenti**, due giri prima dell'unione: 39 rilievi confermati nel primo e 7 nel secondo, tutti corretti. I più seri:
+ un filmato ripetuto passava per fermo; un file troncato o un errore di lettura diventava un esito; una dissolvenza da
+ nero faceva «In movimento» di una scritta ferma; «Salva il fotogramma» ripreso dopo una pausa salvava l'istante vecchio.
+- Documenti: SPECIFICA §4.10 e §16 righe 39–47; righe E4 in `decisioni.md`; guida `Esportazione.md`; prova dal vivo F8;
+ schermate nuove con il confronto in `docs/schermate/differenze.md`.
+- Controlli, su Windows, prima dell'unione di #79 nel ramo: `dotnet build -warnaserror` 0 avvisi, 0 errori;
+ `dotnet test tests/Febe.Tests` 3342 superate, 118 ignorate, 1 non superata:
+ `LibraryScaleTests.LibraryQueriesStayFastWith200000Entries`, «Copie copiati: un account» 252,3 ms contro 250. Da sola,
+ su questo PC, una volta è caduta di nuovo e una è passata; E4 non tocca quella interrogazione. Le prove d'interfaccia in
+ una finestra di Chrome vera fuori schermo: 21 superate su 22 al primo giro, la ventiduesima passata da sola.
+- **Non verificato**: video veri del telefono (prova dal vivo F8, di Alberto); il tempo di un 1080p con un fotogramma
+ chiave ogni 1–2 s (stimati 2–4 s; un 1080p di 60 s con un solo fotogramma chiave ne chiede 35–40, oltre i 30 s del
+ visualizzatore); le schermate non sono state rifatte dopo la revisione; «Salva il fotogramma» in un browser vero
+ verso un disco esterno vero.
+- **Limiti noti** (`decisioni.md`): un blocco toccato in parte conta intero, quindi il 5 % è in pratica un oggetto di
+ circa il 4 %; una scritta che scorre alta fra 1/32 e 1/20 dell'immagine dipende da dove cade; un filmato ripetuto la
+ cui parte diversa dura meno di metà giro può sfuggire; la neve rada resta «Fermo» con «una piccola parte si muove»; un
+ video ricompresso con forza può dirsi «In movimento».
+- **Domande per Alberto**:
+ - la soglia del 5 % va bene con una scritta piccola che si muove, o deve bastare la scritta per dire «In movimento»?
+ - un blocco del browser dalla pagina di riposo (`ERR_BLOCKED_BY_LOCAL_NETWORK_ACCESS_CHECKS`) conta come tentativo in
+ `DownloadQueue`, mentre `SearchPhotoQueue` da quella pagina non scarica: si allineano? (Dipende da H7.)
+ - una pagina del profilo che arriva senza dati si registra come controllo finito, «Nessuna novità», e il prossimo è
+ ore dopo: si riprova prima?
+- **Prossima tappa**: E5 «Esportazione automatica», quando la chiede Alberto.
+
+**29 novembre – 1º dicembre 2026: correzioni**, tutte unite in `main`. #77: #67 (subito dopo «Scollega» si aspetta il
+browser entro un limite, poi la pagina di accesso) e il motore che non rimette a riposo la pagina appena ripresa da
+Alberto (la finestra stretta che resta è nei «Rilievi aperti»). #76: commenti in inglese negli script di shell (#43).
+#78: `--blame-hang-timeout` e `macchina.log` per le prove che si fermano nella CI. #79: la prova da capo a fondo del
+server. Di #43 resta da decidere il filtro della cache di costruzione (`until=24h`).
+
**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): il 29 novembre
2026 Alberto ha confermato le proposte adottate.
@@ -59,7 +104,7 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
La 510 è stata verde alla seconda prova: al primo giro la prova da capo a fondo con il sito di prova
(`TheRealServerCollectsFromTheTestSite…`) ha passato i 90 s, come già una volta prima di E3 (2 min 10 s nella 107).
Riaccaduto il 1º dicembre (551): era la prova, non Febe. Corretta con un orologio che non somma le attese e con la
- sola sessione di «Controlla ora» (`decisioni.md`, 1º dicembre; ramo `correzione/prova-da-capo-a-fondo`); un'attesa
+ sola sessione di «Controlla ora» (`decisioni.md`, 1º dicembre; #79, unita in `main`); un'attesa
scaduta ora dice che cosa faceva Febe. La causa della 551 e della 510 resta dedotta: non c'è il loro registro.
Dopo l'unione la 518 di main è caduta nell'immagine su `APreviewPastItsBudgetSaysToUseTheFolderOfTheCopies`: con
un tempo zero il fotogramma si annullava con un timer, che su una macchina carica scattava dopo la decodifica;
@@ -77,7 +122,7 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
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.
+- **Prossima tappa**: E4 «Video fermi», scelta da Alberto il 29 novembre (qui sopra).
**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
@@ -210,7 +255,7 @@ d'interfaccia di «Tutte le foto» sotto «Video» ora cerca con l'API un video
di un video mancante (la demo non ha i file dei video). Una prova di Collegamento in H.264 è caduta una volta
(about:blank invece di `/benvenuto`) ed è passata alla ripetizione: la corsa è descritta in #67, non corretta. Il 29
novembre 2026 Alberto ha deciso come correggerla (aspettare il browser entro un limite, poi la pagina di accesso; riga
-in `decisioni.md`): non ancora fatto.
+in `decisioni.md`): fatto con #77, unita in `main`.
L'esecuzione 448 di HEVC si è fermata per oltre 3 ore nelle prove senza uscita, oltre i 60 minuti del lavoro: con ogni
probabilità il runner già malato, non le prove; la verifica di HEVC dopo il riavvio (464) ha fatto le prove in 17
minuti.
diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs
index 12951d9..6aeca9d 100644
--- a/src/Febe.App/FebeApp.cs
+++ b/src/Febe.App/FebeApp.cs
@@ -15,6 +15,7 @@ using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
+using Febe.Core.Library.StillVideos;
using Febe.Core.Security;
using Febe.Core.Storage;
using Febe.Data;
@@ -41,6 +42,9 @@ namespace Febe.App;
///
public sealed class FebeApp : IAsyncDisposable
{
+ /// How long a stop waits for «Cerca i video fermi» to give up the video it analyses.
+ private static readonly TimeSpan StillVideosWait = TimeSpan.FromSeconds(5);
+
private readonly FebeAppOptions _options;
private readonly IFebePlatform _platform;
private readonly CancellationTokenSource _lifetime = new();
@@ -361,6 +365,11 @@ public sealed class FebeApp : IAsyncDisposable
s.AddSingleton(new LibraryConversionQueue(Database, Clock));
s.AddSingleton(exportRoot);
s.AddSingleton(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
+ if (hooks.StillVideoAnalyser is { } analyser)
+ {
+ s.AddSingleton(analyser);
+ }
+
s.AddSingleton(sessionState);
s.AddSingleton(Database);
s.AddSingleton(library);
@@ -942,6 +951,17 @@ public sealed class FebeApp : IAsyncDisposable
if (Web is { } web)
{
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
+
+ // «Cerca i video fermi» (tappa E4): the job gives up the video it analyses (nothing stored for it) and ends
+ // before the database closes; it does not resume at the next start (answer 41). Not waited for without an end:
+ // a read stuck on a library that does not answer (a network folder) must not keep the engine and the browser
+ // from closing in time, and its result would not be stored anyway.
+ await Quietly(async () =>
+ {
+ var stills = web.Services.GetRequiredService();
+ stills.Dispose();
+ await stills.Job.WaitAsync(StillVideosWait).ConfigureAwait(false);
+ }).ConfigureAwait(false);
}
if (Engine is { } engine)
diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs
index 955bc86..d0cc01d 100644
--- a/src/Febe.App/IFebePlatform.cs
+++ b/src/Febe.App/IFebePlatform.cs
@@ -176,4 +176,7 @@ public sealed record FebeAppHooks
/// Fake free space and file size limit of the export folders.
public IExportDisk? ExportDisk { get; init; }
+
+ /// Fake analysis of «Video fermi» (a file that does not answer while Febe closes).
+ public Func? StillVideoAnalyser { get; init; }
}
diff --git a/src/Febe.Core/Codecs/H264/H264PcmWriter.cs b/src/Febe.Core/Codecs/H264/H264PcmWriter.cs
index 6582402..44704a7 100644
--- a/src/Febe.Core/Codecs/H264/H264PcmWriter.cs
+++ b/src/Febe.Core/Codecs/H264/H264PcmWriter.cs
@@ -1,4 +1,5 @@
using Febe.Core.Codecs.Containers;
+using Febe.Core.Codecs.Images;
namespace Febe.Core.Codecs.H264;
@@ -213,6 +214,83 @@ public static class H264PcmWriter
return output.ToArray();
}
+ ///
+ /// The demo's still video (tappa E4): alone for two seconds, pictures per
+ /// second, after a short fade from black (the first picture nearly black, the second at half light), as a photo
+ /// shared as a video. «È un video fermo?» finds it «Fermo» and «Salva il fotogramma» takes a frame after the fade.
+ ///
+ /// The picture, × (see ).
+ public static byte[] DemoStillVideo(H264PcmPicture picture)
+ {
+ ArgumentNullException.ThrowIfNull(picture);
+ if (picture.Width != DemoWidth || picture.Height != DemoHeight)
+ {
+ throw new ArgumentException("Il fotogramma deve avere le dimensioni del video dimostrativo.", nameof(picture));
+ }
+
+ var dark = Faded(picture, 0.05);
+ var half = Faded(picture, 0.5);
+ using var output = new MemoryStream();
+ WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, i => i switch { 0 => dark, 1 => half, _ => picture }, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
+ return output.ToArray();
+ }
+
+ ///
+ /// A picture of the samples of (alpha ignored), with the coefficients the decoder uses for a
+ /// stream that says nothing about its colours under 720 lines: BT.601, limited range (luma 16-235, chroma 16-240).
+ /// The chroma of each 2×2 block is the mean of its four pixels. Width and height must be multiples of 16.
+ ///
+ public static H264PcmPicture FromRgba(RgbaImage image)
+ {
+ ArgumentNullException.ThrowIfNull(image);
+ var p = new H264PcmPicture(image.Width, image.Height);
+ var pixels = image.Pixels;
+ var chromaWidth = image.Width / 2;
+ for (var y = 0; y < image.Height; y += 2)
+ {
+ for (var x = 0; x < image.Width; x += 2)
+ {
+ double cb = 0, cr = 0;
+ for (var dy = 0; dy < 2; dy++)
+ {
+ for (var dx = 0; dx < 2; dx++)
+ {
+ var at = (((y + dy) * image.Width) + x + dx) * RgbaImage.BytesPerPixel;
+ double r = pixels[at], g = pixels[at + 1], b = pixels[at + 2];
+ p.Y[((y + dy) * image.Width) + x + dx] = Clamp(16 + (((65.481 * r) + (128.553 * g) + (24.966 * b)) / 255), 16, 235);
+ cb += 128 + (((-37.797 * r) - (74.203 * g) + (112.0 * b)) / 255);
+ cr += 128 + (((112.0 * r) - (93.786 * g) - (18.214 * b)) / 255);
+ }
+ }
+
+ p.Cb[((y / 2) * chromaWidth) + (x / 2)] = Clamp(cb / 4, 16, 240);
+ p.Cr[((y / 2) * chromaWidth) + (x / 2)] = Clamp(cr / 4, 16, 240);
+ }
+ }
+
+ return p;
+ }
+
+ /// The picture with its light scaled by toward black (luma 16, chroma 128).
+ private static H264PcmPicture Faded(H264PcmPicture picture, double factor)
+ {
+ var p = new H264PcmPicture(picture.Width, picture.Height);
+ for (var i = 0; i < p.Y.Length; i++)
+ {
+ p.Y[i] = Clamp(16 + ((picture.Y[i] - 16) * factor), 16, 235);
+ }
+
+ for (var i = 0; i < p.Cb.Length; i++)
+ {
+ p.Cb[i] = Clamp(128 + ((picture.Cb[i] - 128) * factor), 16, 240);
+ p.Cr[i] = Clamp(128 + ((picture.Cr[i] - 128) * factor), 16, 240);
+ }
+
+ return p;
+ }
+
+ private static byte Clamp(double value, int low, int high) => (byte)Math.Clamp((int)Math.Round(value), low, high);
+
/// Picture of the demo video (luma 16-235, chroma 16-240: no zero byte).
public static H264PcmPicture DemoPicture(int index)
{
diff --git a/src/Febe.Core/Domain/Export.cs b/src/Febe.Core/Domain/Export.cs
index 0f66d94..326ef92 100644
--- a/src/Febe.Core/Domain/Export.cs
+++ b/src/Febe.Core/Domain/Export.cs
@@ -343,8 +343,53 @@ public sealed record ExportItem
public string? LastError { get; init; }
}
-/// Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 video_analysis).
-public sealed record VideoAnalysis(string Sha256, int Algorithm, VideoAnalysisOutcome Outcome, DateTimeOffset AnalyzedAt);
+///
+/// Outcome of the still-video analysis of one algorithm for one SHA-256 (spec §8.3 video_analysis, migration
+/// 0005 of tappa E4). is the shown instant of the frame «Salva il fotogramma» saves: set for
+/// and only for it. says why, as codes of
+/// separated by spaces: always set for .
+///
+public sealed record VideoAnalysis(
+ string Sha256,
+ int Algorithm,
+ VideoAnalysisOutcome Outcome,
+ DateTimeOffset AnalyzedAt,
+ TimeSpan? FrameAt = null,
+ string? Note = null);
+
+///
+/// The codes of video_analysis.note (tappa E4), English, separated by spaces like export_item.note. They
+/// say why a video is «Non analizzabile», or () that a small part of a still video moves.
+///
+public static class VideoAnalysisNotes
+{
+ /// The video has no frames Febe can decode (codec, profile or container outside spec §3, damaged headers).
+ public const string FrameNotAvailable = "FrameNotAvailable";
+
+ /// The video has more than one frame and no known duration.
+ public const string DurationUnknown = "DurationUnknown";
+
+ /// The frames of the video cannot be read (a damaged or truncated file).
+ public const string Unreadable = "Unreadable";
+
+ /// The analysis took longer than its time limit (only an analysis from a selection stores it).
+ public const string TooSlow = "TooSlow";
+
+ /// Every frame looked at is black or nearly black (answer 42 of Alberto, 29 November 2026).
+ public const string AllDark = "AllDark";
+
+ /// Every frame looked at is all of one single colour, not dark (answer 42 of Alberto, 29 November 2026).
+ public const string SingleColor = "SingleColor";
+
+ ///
+ /// On a still video: a small part of the picture moves (an animated sticker, a moving caption), within the area a
+ /// still video may change (answer 47 of Alberto, 29 November 2026).
+ ///
+ public const string SmallMotion = "SmallMotion";
+
+ /// Every code of algorithm 1, in the order above.
+ public static IReadOnlyList All { get; } = [FrameNotAvailable, DurationUnknown, Unreadable, TooSlow, AllDark, SingleColor, SmallMotion];
+}
///
/// A converted file added to an entry by the conversion for the library (spec §4.10, §8.3 media_conversion),
diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs
index 5099b4e..08f275f 100644
--- a/src/Febe.Core/Export/ExportCopier.cs
+++ b/src/Febe.Core/Export/ExportCopier.cs
@@ -576,9 +576,29 @@ public sealed class ExportCopier(ExportEnvironment env)
}
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);
+ TimeSpan? chosen = null;
+ if (mode == FrameMode.Still && !string.Equals(batch[0].SourceSha256, sha, StringComparison.Ordinal))
+ {
+ // The file changed since the frame was chosen (a job that waited): the instant is the one of the analysis of
+ // the new file, or there is none (the item keeps the one it was recorded with, the copy says the true one).
+ if (await _env.Storage.VideoAnalyses.GetAsync(sha, ct).ConfigureAwait(false) is not { Outcome: VideoAnalysisOutcome.Still, FrameAt: { } at })
+ {
+ await EndAllAsync(batch, ExportItemState.Skipped, ExportText.Notes.NotStill, null).ConfigureAwait(false);
+ return null;
+ }
+
+ chosen = at;
+ }
+
+ if (mode != FrameMode.Still)
+ {
+ // A «Still» item keeps the SHA-256 its instant was chosen on: a job that pauses once the item is written again
+ // (the disk went in the middle of the file) must still see that the file changed.
+ batch = batch.Select(i => string.Equals(i.SourceSha256, sha, StringComparison.Ordinal) ? i : i with { SourceSha256 = sha }).ToList();
+ }
+
+ var format = batch[0].Format;
var firstId = mode == FrameMode.Count
? await exports.FirstItemIdAsync(x.Run.Id, library.Media.Id, ExportVariant.Frame, format, ct).ConfigureAwait(false) ?? batch[0].Id
: 0;
@@ -625,7 +645,7 @@ public sealed class ExportCopier(ExportEnvironment env)
: [];
using (reader)
{
- var targets = info.Available ? reader.Locate([.. batch.Select(i => i.FrameAt ?? TimeSpan.Zero)]) : [];
+ var targets = info.Available ? reader.Locate([.. batch.Select(i => chosen ?? i.FrameAt ?? TimeSpan.Zero)]) : [];
if (targets.Count != batch.Count)
{
await EndAllAsync(batch, ExportItemState.Skipped, ExportText.Notes.FrameNotAvailable, null).ConfigureAwait(false);
diff --git a/src/Febe.Core/Export/ExportFrames.cs b/src/Febe.Core/Export/ExportFrames.cs
index a856732..3e68259 100644
--- a/src/Febe.Core/Export/ExportFrames.cs
+++ b/src/Febe.Core/Export/ExportFrames.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+using System.Text.RegularExpressions;
namespace Febe.Core.Export;
@@ -6,7 +7,7 @@ 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
+public static partial class ExportFrames
{
/// The shortest step of «Uno ogni k secondi».
public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100);
@@ -26,13 +27,23 @@ public static class ExportFrames
/// The suffix of the single frame of «Salva il fotogramma» (tappa E4).
public const string SingleSuffix = "_fotogramma";
+ ///
+ /// Whether the file of a frame copy has the name «Salva il fotogramma» gives (, also with
+ /// « (2)» of a name already taken): the other ways end with _t… or _f….
+ ///
+ public static bool IsSingleName(string? relativePath) =>
+ relativePath is not null && SingleName().IsMatch(Path.GetFileNameWithoutExtension(relativePath));
+
+ [GeneratedRegex("_fotogramma( \\(\\d+\\))?$", RegexOptions.CultureInvariant)]
+ private static partial Regex SingleName();
+
/// 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.At or FrameMode.Still => 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)),
@@ -48,7 +59,8 @@ public static class ExportFrames
ArgumentNullException.ThrowIfNull(request);
return request.Mode switch
{
- FrameMode.At => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero],
+ // «Salva il fotogramma»: the caller puts the analysis' instant in At (the planner reads it per video).
+ FrameMode.At or FrameMode.Still => [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)),
@@ -102,11 +114,17 @@ public static class ExportFrames
///
/// 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».
+ /// the instants, at least three digits) for «N in tutto»; _fotogramma
+ /// () for «Salva il fotogramma» of a still video.
///
/// 0-based position of the instant in the request.
public static string Suffix(FrameMode mode, TimeSpan actual, int index, int count)
{
+ if (mode == FrameMode.Still)
+ {
+ return SingleSuffix;
+ }
+
if (mode == FrameMode.Count)
{
var digits = Math.Max(3, Math.Max(1, count).ToString(CultureInfo.InvariantCulture).Length);
@@ -153,9 +171,20 @@ public static class ExportFrames
/// 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;
+ ///
+ /// The identity of a frame's instant: its shown time in milliseconds, rounded up (a hostile time table reaches the
+ /// end of what a TimeSpan holds: the whole milliseconds of it, then).
+ ///
+ public static long ActualMs(TimeSpan shown)
+ {
+ if (shown <= TimeSpan.Zero)
+ {
+ return 0;
+ }
+
+ var (ms, rest) = Math.DivRem(shown.Ticks, TimeSpan.TicksPerMillisecond);
+ return Math.Min(ms + (rest > 0 ? 1 : 0), TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond);
+ }
private static long EveryCount(TimeSpan duration, TimeSpan step)
{
diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs
index 67ca130..b6ff08d 100644
--- a/src/Febe.Core/Export/ExportModels.cs
+++ b/src/Febe.Core/Export/ExportModels.cs
@@ -34,6 +34,13 @@ public enum FrameMode
/// «N in tutto»: N frames spread over the video, each in the middle of its share.
Count,
+
+ ///
+ /// «Salva il fotogramma» of a still video (tappa E4, answer 45): the one frame the analysis chose (the sharpest
+ /// looked at, never a dark one), at the instant video_analysis keeps; named …_fotogramma. One video
+ /// only (answer 46).
+ ///
+ Still,
}
/// A request of frames of videos, in a photo format (Jpg, Png or WebpLossless).
@@ -47,7 +54,8 @@ 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);
+/// The frame row is one of «Salva il fotogramma»: the new file is named …_fotogramma again.
+public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt, bool Still = false);
/// A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.
/// The formats of this request («Copia in…» → «Cambia»); null: those of the destination.
@@ -114,6 +122,12 @@ public sealed record ExportPlan(
/// Frames job: videos that would give more than frames (the job is refused).
public int OverCap { get; init; }
+
+ ///
+ /// «Salva il fotogramma» (tappa E4): due videos whose analysis is not «Fermo», or that were never analysed (skipped:
+ /// «Non è un video fermo, o non è stato analizzato»).
+ ///
+ public int NotStill { get; init; }
}
/// Files of a plan copied as they are, of one kind («HEIC», «AVIF», «raw», «GIF», «WebM»).
diff --git a/src/Febe.Core/Export/ExportPlanner.cs b/src/Febe.Core/Export/ExportPlanner.cs
index 43a346e..0846416 100644
--- a/src/Febe.Core/Export/ExportPlanner.cs
+++ b/src/Febe.Core/Export/ExportPlanner.cs
@@ -99,7 +99,12 @@ public sealed class ExportPlanner(ExportEnvironment env)
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:
+ case FrameMode.Still when frames.At is not null || frames.Every is not null || frames.Count is not null:
+ throw new ArgumentException("«Salva il fotogramma» prende il fotogramma scelto dall'analisi: niente istante, intervallo o numero.", nameof(request));
+ case FrameMode.Still when request.Selection is not ExportSelection.Media { MediaIds.Count: 1 }:
+ // Answer 46 of Alberto (29 November 2026): only from the viewer, one video.
+ throw new ArgumentException("«Salva il fotogramma» vale per un video solo, dal visualizzatore.", nameof(request));
+ case FrameMode.At or FrameMode.Every or FrameMode.Count or FrameMode.Still:
break;
default:
throw new ArgumentException("Modo dei fotogrammi sconosciuto.", nameof(request));
@@ -294,6 +299,24 @@ public sealed class ExportPlanner(ExportEnvironment env)
Prediction = ExportPrediction.Converted,
FirstOfVideo = true,
};
+ if (frames.Mode == FrameMode.Still)
+ {
+ // «Salva il fotogramma» (tappa E4): the instant the analysis chose, by SHA-256 of the file; a video
+ // that is not «Fermo» (or was never analysed) gives nothing.
+ var analysis = await _env.Storage.VideoAnalyses.GetAsync(c.Sha256!, ct).ConfigureAwait(false);
+ if (analysis is not { Outcome: VideoAnalysisOutcome.Still, FrameAt: { } still })
+ {
+ yield return frame with { Action = PlannedCopy.NotStill };
+ continue;
+ }
+
+ var chosen = frame with { FrameAt = still };
+ yield return seen.Add((destination, c.AccountId, c.Sha256!, (long)still.TotalMilliseconds, frames.Format))
+ ? chosen
+ : chosen with { Action = PlannedCopy.AlreadyCopied };
+ continue;
+ }
+
var duration = c.Duration ?? TimeSpan.Zero;
if (frames.Mode != FrameMode.At && c.Duration is null)
{
@@ -409,6 +432,9 @@ internal enum PlannedCopy
/// Frames job: a video over frames.
OverCap,
+
+ /// «Salva il fotogramma» (tappa E4): a video whose analysis is not «Fermo», or that was never analysed.
+ NotStill,
}
/// Counts of a plan while its files go by.
@@ -441,15 +467,20 @@ internal sealed class PlanTally
public int OverCap { get; private set; }
+ public int NotStill { get; private set; }
+
public void Add(PlannedFile file)
{
- if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing))
+ if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing or PlannedCopy.NotStill))
{
Videos++;
}
switch (file.Action)
{
+ case PlannedCopy.NotStill:
+ NotStill++;
+ return;
case PlannedCopy.Missing:
Missing++;
return;
@@ -545,6 +576,7 @@ internal sealed class PlanTally
PhotosSkipped = PhotosSkipped,
Frames = Frames,
OverCap = OverCap,
+ NotStill = NotStill,
};
}
diff --git a/src/Febe.Core/Export/ExportRunSettings.cs b/src/Febe.Core/Export/ExportRunSettings.cs
index f6f6a4b..a2f3b62 100644
--- a/src/Febe.Core/Export/ExportRunSettings.cs
+++ b/src/Febe.Core/Export/ExportRunSettings.cs
@@ -11,7 +11,10 @@ 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.
+ ///
+ /// How the frames of a frames job were asked (tappa E3): Istante, Ogni or Numero:N; Fermo
+ /// for «Salva il fotogramma» of a still video (tappa E4).
+ ///
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).
@@ -36,6 +39,11 @@ internal static class ExportRunSettings
return (FrameMode.Every, 0);
}
+ if (string.Equals(text, "Fermo", StringComparison.Ordinal))
+ {
+ return (FrameMode.Still, 1);
+ }
+
return text.StartsWith("Numero:", StringComparison.Ordinal)
&& int.TryParse(text.AsSpan("Numero:".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var count) && count > 0
? (FrameMode.Count, count)
@@ -49,6 +57,7 @@ internal static class ExportRunSettings
{
FrameMode.At => "Istante",
FrameMode.Every => "Ogni",
+ FrameMode.Still => "Fermo",
_ => string.Create(CultureInfo.InvariantCulture, $"Numero:{count}"),
},
ct);
diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs
index f8c22d9..1309938 100644
--- a/src/Febe.Core/Export/ExportService.cs
+++ b/src/Febe.Core/Export/ExportService.cs
@@ -208,7 +208,7 @@ public sealed class ExportService : IAsyncDisposable
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 or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap)
+ if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap or PlannedCopy.NotStill)
{
continue;
}
@@ -303,9 +303,9 @@ public sealed class ExportService : IAsyncDisposable
{
await ExportRunSettings.SetFramesAsync(store, runId, frames.Mode, frames.Count ?? 0, none).ConfigureAwait(false);
}
- else if (request.Exact is { Variant: ExportVariant.Frame })
+ else if (request.Exact is { Variant: ExportVariant.Frame } exact)
{
- await ExportRunSettings.SetFramesAsync(store, runId, FrameMode.At, 1, none).ConfigureAwait(false);
+ await ExportRunSettings.SetFramesAsync(store, runId, exact.Still ? FrameMode.Still : FrameMode.At, 1, none).ConfigureAwait(false);
}
if (request.Exact is not null)
diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs
index ed1edd8..7d4e183 100644
--- a/src/Febe.Core/Export/ExportText.cs
+++ b/src/Febe.Core/Export/ExportText.cs
@@ -39,6 +39,9 @@ public static class ExportText
public const string AsIsTooLarge = ImageConversionLosses.AsIsTooLarge;
public const string AsIsNotRemuxable = MediaConversionResult.AsIsNotRemuxable;
public const string FrameNotAvailable = "FrameNotAvailable";
+
+ // Tappa E4: «Salva il fotogramma» of a file that changed meanwhile, and is not a still video as far as Febe knows.
+ public const string NotStill = "NotStill";
public const string TransparencyWhite = ImageConversionLosses.TransparencyWhite;
public const string CopiedInAnotherFormat = "CopiedInAnotherFormat";
public const string LostTracks = Mp4Remuxer.LostTracks;
@@ -142,6 +145,7 @@ public static class ExportText
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.NotStill => "Il video è cambiato: il file di adesso non è un video fermo, o non è stato analizzato",
Notes.TransparencyWhite => "La trasparenza è diventata bianco",
Notes.CopiedInAnotherFormat => "Già copiato in un altro formato",
ImageConversionLosses.LostTexts => "Non tenuti: testi",
diff --git a/src/Febe.Core/Library/StillVideoAnalyzer.cs b/src/Febe.Core/Library/StillVideoAnalyzer.cs
new file mode 100644
index 0000000..1bdace6
--- /dev/null
+++ b/src/Febe.Core/Library/StillVideoAnalyzer.cs
@@ -0,0 +1,944 @@
+using System.Buffers;
+using System.Runtime.ExceptionServices;
+using Febe.Core.Codecs.Containers;
+using Febe.Core.Codecs.Images;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+
+namespace Febe.Core.Library;
+
+/// What found about a video (spec §4.10 «È un video fermo?», tappa E4).
+/// «Fermo», «In movimento» or «Non analizzabile».
+///
+/// For only: the shown instant, in whole milliseconds rounded up as the frame
+/// copies name them (), of the sharpest frame looked at that is not dark: the frame
+/// «Salva il fotogramma» saves.
+///
+///
+/// Codes of : why the video is not analysable (always set then), or
+/// on a still video where a small part moves; null otherwise.
+///
+/// Frames decoded and looked at.
+/// Clockwise rotation of the track (0, 90, 180, 270): the frames looked at are already upright.
+/// Whether the container has an audio track (the saved frame never has it).
+///
+/// The largest mean block difference, 0–255, each block capped at : of a
+/// frame from the still picture, or of the pair that showed the motion.
+///
+/// The largest fraction (0–1) of the picture that changed beyond the local threshold, likewise.
+/// The sharpness of the chosen frame: the variance of the Laplacian of its luma (0 without one).
+public sealed record StillVideoResult(
+ VideoAnalysisOutcome Outcome,
+ TimeSpan? FrameAt,
+ string? Note,
+ int Sampled,
+ int Rotation,
+ bool HasAudio,
+ double Difference,
+ double MovingArea,
+ double Sharpness)
+{
+ /// The algorithm that gave the result: .
+ public int Algorithm => StillVideoAnalyzer.Algorithm;
+
+ /// in milliseconds.
+ public long? FrameAtMs => FrameAt is { } at ? (long)at.TotalMilliseconds : null;
+
+ /// The row of video_analysis for the file of , analysed at .
+ public VideoAnalysis ToAnalysis(string sha256, DateTimeOffset analyzedAt) =>
+ new(sha256, Algorithm, Outcome, analyzedAt, FrameAt, Note);
+}
+
+///
+/// Whether a video only shows one picture (a photo with music, for example), so that one frame stands for it (spec
+/// §4.10 «Video fermi», tappa E4, algorithm 1). Written in house on : exact frames at the
+/// shown times, edit lists included, upright.
+///
+/// frames spread over what the video track shows (not over the length the headers say), one
+/// in each of as many equal parts, at the uneven inside them: equal steps would fall on the same
+/// picture of a clip repeated over and over. Every other one may move to a key frame shown within a quarter of a part,
+/// which decodes alone; the ones between are the frame shown at the instant, so that the pictures between key frames are
+/// looked at too. Never the very first or last frame, where fades and black frames sit. A track of at most
+/// pictures is looked at whole; when the instants fall on fewer pictures (some are held for long)
+/// others are added by their position.
+/// Each frame is reduced to a grid of × blocks and to a finer one (of
+/// up to cells a side, at least pixels each), with the mean of each
+/// channel and the share of it clipped at white; its sharpness is the variance of the Laplacian of its luma.
+/// A frame with no block as bright as in any colour, and no detail as bright as
+/// , is dark: dark frames at the start or the end (a fade from or to black) are set aside; a
+/// dark frame between two that are not is compared like any other (a dim picture whose grain crosses the threshold is
+/// still; black between two pictures is not), and is never the one chosen. A single frame that is not dark says nothing
+/// of the video: more are then looked at between the dark ones around it.
+/// A fade is undone before frames are compared: when the brightness ratios of the blocks agree (a fade scales
+/// them all alike), each counted by its light so that a card on black or a dark photo tells its fade too, the picture is
+/// scaled to the frame's brightness; what clipping at white may hide is bounded, channel by channel, and never taken for
+/// a change.
+/// The still picture is the median of the frames, block by block, so a part that moves does not belong to it. The
+/// video is still when every frame differs from it by a mean of at most (each block capped
+/// at ) and the blocks that differ by more than cover at most
+/// of the picture, on both grids (the finer one by its luma): a small animated sticker or a
+/// moving caption leaves the video still (answer 47 of Alberto, 29 November 2026), and snow or static, whose blocks
+/// average out, does not. While decoding, a pair of frames that differs over three times that area (a moving part
+/// changes the picture at its old and its new place, and the edges of the blocks add some) or by a larger mean already
+/// says «In movimento», and the rest is not decoded.
+/// No frame that is not dark: «Non analizzabile» (); every one of the same
+/// single colour: «Non analizzabile» (, answer 42). A frame that should have
+/// been looked at and gives no picture: «Non analizzabile» (), unless the
+/// others already show motion.
+///
+/// Any change to the rule or to the thresholds raises .
+///
+public static class StillVideoAnalyzer
+{
+ /// The algorithm number stored with each result (video_analysis.algorithm).
+ public const int Algorithm = 1;
+
+ /// Frames looked at.
+ public const int Samples = 7;
+
+ /// Blocks of the grid on each side.
+ public const int GridSize = 32;
+
+ /// Cells of the finer grid on each side, at most.
+ public const int FineGridSize = 128;
+
+ /// The smallest side of a cell of the finer grid, in pixels.
+ internal const int FineCell = 4;
+
+ ///
+ /// Where each frame looked at sits inside its part of the video (0–1): the first and the last far from the ends, the
+ /// others uneven (found by a search), so that for a clip repeated 2 to 40 times, also not a whole number, the seven
+ /// frames never fall within less than 48 % of it. A picture shown for less than half of the clip can still be missed.
+ ///
+ internal static readonly double[] Offsets = [0.54, 0.865, 0.417, 0.253, 0.432, 0.45, 0.46];
+
+ ///
+ /// A frame none of whose blocks has a red, green or blue mean as bright as this (0–255) is dark: black or nearly
+ /// black.
+ ///
+ public const double DarkLevel = 32;
+
+ ///
+ /// A frame whose blocks spread less than this (standard deviation of luma and of each chroma difference, 0–255) is
+ /// of a single colour.
+ ///
+ public const double UniformSpread = 2;
+
+ /// The local threshold: a block whose difference is larger has changed (0–255).
+ public const double BlockThreshold = 12;
+
+ /// The largest mean block difference from the still picture (0–255), each block capped at .
+ public const double MeanThreshold = 3;
+
+ /// The largest fraction of the picture that may change in a still video (answer 47).
+ public const double AreaThreshold = 0.05;
+
+ ///
+ /// While decoding, a pair of frames differing over this many times moves: a part of
+ /// that area changes it at its old and its new place, and the edges of the blocks add some.
+ ///
+ internal const double EarlyAreaFactor = 3;
+
+ /// Blocks darker than this (their largest channel) in both frames do not take part in the estimate of a fade.
+ internal const double GainFloor = 8;
+
+ /// The fewest blocks that can tell a fade.
+ internal const int GainBlocks = 10;
+
+ /// A block this near (0–255) to what the fade makes of it follows it: the rounding of a dim frame.
+ internal const double GainNoise = 1.5;
+
+ /// The width of the band, as a share of the ratio, in which the blocks holding half of the light must be for it to be a fade.
+ internal const double GainAgreement = 0.1;
+
+ /// The largest brightness ratio undone as a fade.
+ internal const double GainRange = 16;
+
+ ///
+ /// A channel of a block with more of its pixels clipped at white than this does not take part in the estimate of a
+ /// fade, unless the others tell none.
+ ///
+ internal const double ClippedShare = 0.1;
+
+ /// A channel at least this bright (0–255) is taken as clipped at white.
+ internal const int White = 250;
+
+ /// The weight of each chroma difference against the luma one.
+ internal const double ChromaWeight = 0.25;
+
+ /// A pixel with a channel at least this bright (0–255) is a detail that a dark frame does not have.
+ internal const int BrightDetail = 96;
+
+ /// The variance of the luma of the pixels from which a frame is not of a single colour.
+ internal const double UniformVariance = 64;
+
+ /// A pixel whose luma is further than this from the mean is a detail that a frame of a single colour does not have.
+ internal const double UniformDetail = 32;
+
+ /// The share of the pixels that may be such a detail in a dark frame or in one of a single colour.
+ internal const double DetailShare = 0.0002;
+
+ /// The latest instant a video may show (past it the time table is damaged or hostile).
+ internal static readonly TimeSpan LatestInstant = TimeSpan.FromSeconds(1e9);
+
+ ///
+ /// Analyses the video in (left open) in at most : past it the
+ /// result is «Non analizzabile» with (a zero budget gives it at once). It
+ /// never throws for a video it cannot read, but an error of the stream itself (a disk or a share that went) is thrown:
+ /// it says nothing of the video. A cancellation of stays a cancellation.
+ ///
+ /// The stream could not be read.
+ /// The stream could not be read.
+ public static StillVideoResult Analyse(Stream seekable, TimeSpan budget, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(seekable);
+ using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ if (budget <= TimeSpan.Zero)
+ {
+ limit.Cancel();
+ }
+ else if (budget < TimeSpan.FromDays(1))
+ {
+ limit.CancelAfter(budget);
+ }
+
+ // The readers take an IOException for a damaged file and go on: the watched stream remembers the real ones.
+ var watched = new WatchedStream(seekable);
+ StillVideoResult result;
+ try
+ {
+ result = Run(watched, limit.Token);
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ result = NotAnalyzable(VideoAnalysisNotes.TooSlow, 0, 0, false);
+ }
+
+ watched.Fault?.Throw();
+ return result;
+ }
+
+ /// Analyses the video in with no limit but .
+ public static StillVideoResult Analyse(Stream seekable, CancellationToken ct) => Analyse(seekable, TimeSpan.MaxValue, ct);
+
+ ///
+ /// Analyses the video file at on the thread pool, as :
+ /// a file that cannot be opened is «Non analizzabile» (); one that stops being
+ /// readable meanwhile throws.
+ ///
+ public static Task AnalyseAsync(string path, TimeSpan budget, CancellationToken ct = default)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ return Task.Run(
+ () =>
+ {
+ FileStream stream;
+ try
+ {
+ stream = ContainerReader.OpenRead(path);
+ }
+ catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
+ {
+ return NotAnalyzable(VideoAnalysisNotes.Unreadable, 0, 0, false);
+ }
+
+ using (stream)
+ {
+ return Analyse(stream, budget, ct);
+ }
+ },
+ ct);
+ }
+
+ private static StillVideoResult Run(Stream stream, CancellationToken ct)
+ {
+ ct.ThrowIfCancellationRequested();
+ using var reader = VideoFrameReader.Open(stream, out var info, ct);
+ if (!info.Available)
+ {
+ return NotAnalyzable(VideoAnalysisNotes.FrameNotAvailable, 0, info);
+ }
+
+ var shown = reader.Shown();
+ if (shown.Count == 0 || (info.SampleCount > 1 && info.Duration <= TimeSpan.Zero) || shown[^1].Actual > LatestInstant)
+ {
+ return NotAnalyzable(VideoAnalysisNotes.DurationUnknown, 0, info);
+ }
+
+ var targets = Targets(reader, shown);
+ var frames = new List(targets.Count);
+ if (Look(reader, targets, frames, ct) is { } pair)
+ {
+ return Moving(frames.Count, info, pair.Mean, pair.Area);
+ }
+
+ var expected = targets.Count;
+ if (frames.Count == expected && expected > 1 && frames.Count(f => !f.Dark) == 1)
+ {
+ // One picture alone among dark frames: the others between the dark frames around it are looked at too.
+ var between = Around(shown, frames);
+ var seen = targets.Select(t => t.Sample).ToHashSet();
+ var more = Targets(reader, between).Where(t => !seen.Contains(t.Sample)).ToList();
+ expected += more.Count;
+ if (Look(reader, more, frames, ct) is { } second)
+ {
+ return Moving(frames.Count, info, second.Mean, second.Area);
+ }
+
+ if (frames.Count == expected && frames.Count(f => !f.Dark) == 1 && Around(shown, frames).Count > 1)
+ {
+ return NotAnalyzable(VideoAnalysisNotes.AllDark, frames.Count, info);
+ }
+ }
+
+ // In the order they are shown: dark frames at the start or the end are a fade; between two that are not, the
+ // picture changes unless they are its like (a dim picture around the threshold).
+ // Motion proved by the frames there are stands; with a frame missing nothing else can be said.
+ frames.Sort((a, b) => a.Actual.CompareTo(b.Actual));
+ var complete = frames.Count == expected;
+ var first = frames.FindIndex(f => !f.Dark);
+ if (first < 0)
+ {
+ return NotAnalyzable(complete ? VideoAnalysisNotes.AllDark : VideoAnalysisNotes.Unreadable, frames.Count, info);
+ }
+
+ var last = frames.FindLastIndex(f => !f.Dark);
+ var pictures = frames.GetRange(first, last - first + 1);
+ foreach (var i in Enumerable.Range(0, pictures.Count).Where(i => pictures[i].Dark))
+ {
+ var (mean, area) = Compare(pictures[i], pictures.Take(i).Last(f => !f.Dark));
+ if (mean > MeanThreshold || area > EarlyAreaFactor * AreaThreshold)
+ {
+ return Moving(frames.Count, info, mean, area);
+ }
+ }
+
+ if (pictures.All(f => f.Uniform))
+ {
+ // Before the comparison of the blocks, which cannot undo a fade of a colour that clips or of a dark one.
+ if (!SameColour(pictures))
+ {
+ return Moving(frames.Count, info, 0, 0);
+ }
+
+ return NotAnalyzable(complete ? VideoAnalysisNotes.SingleColor : VideoAnalysisNotes.Unreadable, frames.Count, info);
+ }
+
+ var (difference, changed, small) = AgainstStillPicture(pictures);
+ if (difference > MeanThreshold || changed > AreaThreshold)
+ {
+ return Moving(frames.Count, info, difference, changed);
+ }
+
+ if (!complete)
+ {
+ return NotAnalyzable(VideoAnalysisNotes.Unreadable, frames.Count, info);
+ }
+
+ // The sharpest picture (the first shown of equally sharp ones): never a dark frame, nor one dimmed by a fade.
+ var chosen = pictures[0];
+ foreach (var f in pictures.Skip(1).Where(f => !f.Dark))
+ {
+ if (f.Sharpness > chosen.Sharpness)
+ {
+ chosen = f;
+ }
+ }
+
+ return new StillVideoResult(VideoAnalysisOutcome.Still, TimeSpan.FromMilliseconds(ExportFrames.ActualMs(chosen.Actual)),
+ small ? VideoAnalysisNotes.SmallMotion : null, frames.Count, info.Rotation, info.HasAudio,
+ Math.Round(difference, 2), Math.Round(changed, 4), Math.Round(chosen.Sharpness, 2));
+ }
+
+ ///
+ /// The frames to look at among (pictures in shown order): all of them when they are at most
+ /// ; otherwise one in each of as many equal parts of the time they cover, at the uneven
+ /// , every other one moved to a near key frame; then others by position when fewer than
+ /// come out.
+ ///
+ private static List Targets(VideoFrameReader reader, IReadOnlyList shown)
+ {
+ if (shown.Count <= Samples)
+ {
+ return [.. shown];
+ }
+
+ var (from, last) = (shown[0].Actual, shown[^1].Actual);
+ var length = last - from + ((last - from) / (shown.Count - 1));
+ var instants = Offsets.Select((o, i) => from + TimeSpan.FromTicks((long)(length.Ticks * ((i + o) / Samples)))).ToList();
+ var exact = reader.Locate(instants);
+ var near = reader.LocateNearKey(instants, length / (4 * Samples));
+ var targets = new List(Samples);
+ var taken = new HashSet();
+ for (var i = 0; i < Samples; i++)
+ {
+ var target = i % 2 == 0 && near[i].Actual >= from && near[i].Actual <= last ? near[i] : exact[i];
+ if (taken.Add(target.Sample))
+ {
+ targets.Add(target);
+ }
+ }
+
+ // Pictures held for long take several instants: the others are looked at by their position.
+ for (var i = 0; i < Samples && targets.Count < Samples; i++)
+ {
+ var target = shown[(int)(shown.Count * ((i + Offsets[i]) / Samples))];
+ if (taken.Add(target.Sample))
+ {
+ targets.Add(target);
+ }
+ }
+
+ return targets;
+ }
+
+ /// The pictures shown between the dark frames nearest to the only one that is not dark.
+ private static List Around(IReadOnlyList shown, List frames)
+ {
+ var lit = frames.Single(f => !f.Dark).Actual;
+ var before = frames.Where(f => f.Dark && f.Actual < lit).Select(f => f.Actual).DefaultIfEmpty(TimeSpan.MinValue).Max();
+ var after = frames.Where(f => f.Dark && f.Actual > lit).Select(f => f.Actual).DefaultIfEmpty(TimeSpan.MaxValue).Min();
+ return [.. shown.Where(t => t.Actual > before && t.Actual < after)];
+ }
+
+ ///
+ /// Decodes the targets and adds them to : the difference of the first pair that moves, or
+ /// null when none does (or the stream is damaged: fewer frames than targets come out).
+ ///
+ private static (double Mean, double Area)? Look(VideoFrameReader reader, List targets, List frames, CancellationToken ct)
+ {
+ try
+ {
+ foreach (var frame in reader.Decode(targets, ct))
+ {
+ Signature signature;
+ using (frame)
+ {
+ signature = Signature.Of(frame.Image, frame.Actual);
+ }
+
+ ct.ThrowIfCancellationRequested();
+ frames.Add(signature);
+ if (signature.Dark)
+ {
+ continue;
+ }
+
+ foreach (var other in frames.Where(f => !f.Dark && f != signature && !(f.Uniform && signature.Uniform)))
+ {
+ var (mean, area) = Compare(signature, other);
+ if (mean > MeanThreshold || area > EarlyAreaFactor * AreaThreshold)
+ {
+ // One pair that moves is enough: the rest of the video is not decoded.
+ return (mean, area);
+ }
+ }
+ }
+ }
+ catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
+ {
+ // A damaged stream past the frames read so far: the caller sees that some are missing.
+ }
+
+ return null;
+ }
+
+ private static StillVideoResult NotAnalyzable(string note, int sampled, VideoFrameInfo info) =>
+ NotAnalyzable(note, sampled, info.Rotation, info.HasAudio);
+
+ private static StillVideoResult NotAnalyzable(string note, int sampled, int rotation, bool hasAudio) =>
+ new(VideoAnalysisOutcome.NotAnalyzable, null, note, sampled, rotation, hasAudio, 0, 0, 0);
+
+ private static StillVideoResult Moving(int sampled, VideoFrameInfo info, double difference, double area) =>
+ new(VideoAnalysisOutcome.Moving, null, null, sampled, info.Rotation, info.HasAudio, Math.Round(difference, 2), Math.Round(area, 4), 0);
+
+ ///
+ /// Whether the pictures, each of a single colour, all show the same colour, fades undone on its largest channel that
+ /// is not clipped at white.
+ ///
+ private static bool SameColour(List pictures)
+ {
+ var brightest = pictures.MaxBy(p => p.Luma.Sum())!.Whole;
+ var channel = Enumerable.Range(0, Grid.Channels)
+ .OrderBy(c => brightest.Clipped[c][0] > ClippedShare || brightest.Mean[c][0] < GainFloor)
+ .ThenByDescending(c => brightest.Mean[c][0])
+ .First();
+ return pictures.All(p =>
+ {
+ var gain = Math.Clamp(p.Whole.Mean[channel][0] / Math.Max(1.0, brightest.Mean[channel][0]), 1 / GainRange, GainRange);
+ return Measure(p.Whole, brightest, gain, gain, ChromaWeight).Area == 0;
+ });
+ }
+
+ /// The difference of two frames on the blocks, after a fade between them is undone: the darker one against the brighter.
+ private static (double Mean, double Area) Compare(Signature a, Signature b)
+ {
+ var gain = Gain(a, b);
+ return gain <= 1
+ ? Measure(a.Coarse, b.Coarse, gain, gain, ChromaWeight)
+ : Measure(b.Coarse, a.Coarse, 1 / gain, 1 / gain, ChromaWeight);
+ }
+
+ ///
+ /// The largest difference of a frame from the still picture, on the blocks and on the finer cells (luma only): the
+ /// median of the frames, each first brought to the brightness of the brightest one. «Small» tells that at least the
+ /// area of a block changed.
+ ///
+ private static (double Mean, double Area, bool Small) AgainstStillPicture(List pictures)
+ {
+ if (pictures.Count < 2)
+ {
+ return (0, 0, false);
+ }
+
+ var reference = pictures.MaxBy(p => p.Luma.Sum())!;
+ var gains = pictures.Select(p => Gain(p, reference)).ToArray();
+ var (mean, area) = AgainstStillPicture([.. pictures.Select(p => p.Coarse)], gains, ChromaWeight);
+ var (fineMean, fineArea) = pictures.All(p => p.Fine.Columns == reference.Fine.Columns && p.Fine.Rows == reference.Fine.Rows)
+ ? AgainstStillPicture([.. pictures.Select(p => p.Fine)], gains, 0)
+ : (0, 0); // a stream that changes size: the cells are not the same places
+ return (Math.Max(mean, fineMean), Math.Max(area, fineArea), area > 0 || fineArea >= 1.0 / Signature.Blocks);
+ }
+
+ private static (double Mean, double Area) AgainstStillPicture(Grid[] frames, double[] gains, double chroma)
+ {
+ var still = new Grid(frames[0].Columns, frames[0].Rows);
+ var values = new double[frames.Length];
+ for (var channel = 0; channel < Grid.Channels; channel++)
+ {
+ for (var i = 0; i < still.Count; i++)
+ {
+ // The lower median: with an even count the lower of the two middle values, so that of two frames neither
+ // is averaged away.
+ float clipped = 0;
+ for (var k = 0; k < frames.Length; k++)
+ {
+ values[k] = frames[k].Mean[channel][i] / gains[k];
+ clipped = Math.Max(clipped, frames[k].Clipped[channel][i]);
+ }
+
+ Array.Sort(values);
+ still.Mean[channel][i] = (float)values[(values.Length - 1) / 2];
+ still.Clipped[channel][i] = clipped;
+ }
+ }
+
+ var lowest = gains.Min();
+ double mean = 0, area = 0;
+ for (var k = 0; k < frames.Length; k++)
+ {
+ var (m, a) = Measure(frames[k], still, gains[k], lowest, chroma);
+ mean = Math.Max(mean, m);
+ area = Math.Max(area, a);
+ }
+
+ return (mean, area);
+ }
+
+ ///
+ /// The mean difference of the cells (each capped at ) and the fraction of them over it,
+ /// between and brought to its brightness (
+ /// times its own). A cell clipped at white may hide brightness: a frame darker than the picture may show there up to
+ /// what the picture lost, a brighter one less than the picture (measured on frames as dark as
+ /// ) has; that much of the difference does not count.
+ ///
+ private static (double Mean, double Area) Measure(Grid frame, Grid picture, double gain, double lowest, double chroma)
+ {
+ var above = 255 * Math.Max(0, 1 - gain);
+ var below = 255 * Math.Max(0, (gain / lowest) - 1);
+ var scale = 1 / Math.Max(1, gain);
+ double sum = 0;
+ var changed = 0;
+ for (var i = 0; i < frame.Count; i++)
+ {
+ var d = scale * Difference(Channel(0, i), Channel(1, i), Channel(2, i), chroma);
+ if (d > BlockThreshold)
+ {
+ changed++;
+ }
+
+ sum += Math.Min(d, BlockThreshold);
+ }
+
+ return (sum / frame.Count, (double)changed / frame.Count);
+
+ double Channel(int c, int i)
+ {
+ var d = frame.Mean[c][i] - Math.Min(255, gain * picture.Mean[c][i]);
+ return d > 0
+ ? Math.Max(0, d - (picture.Clipped[c][i] * above))
+ : Math.Min(0, d + (frame.Clipped[c][i] * below));
+ }
+ }
+
+ /// The difference of two colours: of luma, and of B − Y and R − Y by the weight .
+ private static double Difference(double red, double green, double blue, double chroma)
+ {
+ var luma = Bt709(red, green, blue);
+ return Math.Abs(luma) + (chroma * (Math.Abs(blue - luma) + Math.Abs(red - luma)));
+ }
+
+ private static double Bt709(double red, double green, double blue) => (0.2126 * red) + (0.7152 * green) + (0.0722 * blue);
+
+ ///
+ /// The brightness of against when it is a fade of it, 1 otherwise: from the
+ /// blocks not clipped at white or, when they are too few or do not agree, from all of them (a white card).
+ ///
+ private static double Gain(Signature a, Signature b) => Fade(a, b, clippedToo: false) ?? Fade(a, b, clippedToo: true) ?? 1;
+
+ ///
+ /// The ratio between two frames that the blocks agree on, or null. Each block counts by its brightness: the median
+ /// of the ratios, provided at least half of the light is in blocks that follow it within
+ /// (a different picture gives ratios all over), and the blocks are at least ; then the ratio
+ /// of the light of those blocks. The largest channel of a block that is not clipped is measured, so that a saturated
+ /// or dark picture takes part too; a block under in both frames does not.
+ ///
+ private static double? Fade(Signature a, Signature b, bool clippedToo)
+ {
+ var blocks = new List<(float A, float B, double Ratio)>(Signature.Blocks);
+ double light = 0;
+ for (var i = 0; i < Signature.Blocks; i++)
+ {
+ float largest = 0, va = 0, vb = 0;
+ for (var c = 0; c < Grid.Channels; c++)
+ {
+ var (ca, cb) = (a.Coarse.Mean[c][i], b.Coarse.Mean[c][i]);
+ if (Math.Max(ca, cb) > largest
+ && (clippedToo || (a.Coarse.Clipped[c][i] <= ClippedShare && b.Coarse.Clipped[c][i] <= ClippedShare)))
+ {
+ (largest, va, vb) = (Math.Max(ca, cb), ca, cb);
+ }
+ }
+
+ if (largest >= GainFloor)
+ {
+ blocks.Add((va, vb, Math.Max(va, 0.5) / Math.Max(vb, 0.5)));
+ light += largest;
+ }
+ }
+
+ if (blocks.Count < GainBlocks)
+ {
+ return null;
+ }
+
+ blocks.Sort((x, y) => x.Ratio.CompareTo(y.Ratio));
+ double median = 1, passed = 0;
+ foreach (var (va, vb, ratio) in blocks)
+ {
+ (median, passed) = (ratio, passed + Math.Max(va, vb));
+ if (passed >= light / 2)
+ {
+ break;
+ }
+ }
+
+ double agreeing = 0, lightA = 0, lightB = 0;
+ foreach (var (va, vb, _) in blocks)
+ {
+ // Measured on the darker frame, where one level of rounding weighs the most.
+ var (darker, expected) = median <= 1 ? (va, vb * median) : (vb, va / median);
+ if (Math.Abs(darker - expected) <= Math.Max(GainNoise, GainAgreement / 2 * expected))
+ {
+ agreeing += Math.Max(va, vb);
+ (lightA, lightB) = (lightA + va, lightB + vb);
+ }
+ }
+
+ var gain = lightA / Math.Max(lightB, 0.5);
+ return agreeing >= light / 2 && gain is >= 1 / GainRange and <= GainRange ? gain : null;
+ }
+
+ /// The picture in cells: for each channel the mean of the cell and the share of it clipped at white.
+ private sealed class Grid
+ {
+ internal const int Channels = 3;
+
+ internal Grid(int columns, int rows)
+ {
+ (Columns, Rows) = (columns, rows);
+ for (var c = 0; c < Channels; c++)
+ {
+ (Mean[c], Clipped[c]) = (new float[Count], new float[Count]);
+ }
+ }
+
+ internal int Columns { get; }
+
+ internal int Rows { get; }
+
+ internal int Count => Columns * Rows;
+
+ /// The means of each cell, by channel: red, green and blue.
+ internal float[][] Mean { get; } = new float[Channels][];
+
+ /// The shares of each cell clipped at white, by channel.
+ internal float[][] Clipped { get; } = new float[Channels][];
+
+ ///
+ /// The grid of an RGBA frame. Each cell covers at least one pixel, so a frame narrower than the grid (or a stream
+ /// that changes size) still gives a full grid.
+ ///
+ internal static Grid Of(RgbaImage image, int columns, int rows)
+ {
+ var grid = new Grid(columns, rows);
+ var (w, h) = (image.Width, image.Height);
+ ReadOnlySpan pixels = image.Pixels;
+ var stride = image.Stride;
+ for (var gy = 0; gy < rows; gy++)
+ {
+ var y0 = gy * h / rows;
+ var y1 = Math.Max(y0 + 1, (gy + 1) * h / rows);
+ for (var gx = 0; gx < columns; gx++)
+ {
+ var x0 = gx * w / columns;
+ var x1 = Math.Max(x0 + 1, (gx + 1) * w / columns);
+ long r = 0, g = 0, b = 0;
+ int wr = 0, wg = 0, wb = 0;
+ for (var y = y0; y < y1; y++)
+ {
+ var row = pixels.Slice((y * stride) + (x0 * RgbaImage.BytesPerPixel), (x1 - x0) * RgbaImage.BytesPerPixel);
+ for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel)
+ {
+ var (pr, pg, pb) = (row[i], row[i + 1], row[i + 2]);
+ r += pr;
+ g += pg;
+ b += pb;
+ wr += pr >= White ? 1 : 0;
+ wg += pg >= White ? 1 : 0;
+ wb += pb >= White ? 1 : 0;
+ }
+ }
+
+ float count = (long)(y1 - y0) * (x1 - x0);
+ var cell = (gy * columns) + gx;
+ (grid.Mean[0][cell], grid.Mean[1][cell], grid.Mean[2][cell]) = (r / count, g / count, b / count);
+ (grid.Clipped[0][cell], grid.Clipped[1][cell], grid.Clipped[2][cell]) = (wr / count, wg / count, wb / count);
+ }
+ }
+
+ return grid;
+ }
+ }
+
+ /// What is kept of a frame looked at: its grids, whether it is dark or of one colour, its sharpness.
+ private sealed class Signature
+ {
+ internal const int Blocks = GridSize * GridSize;
+
+ private Signature(TimeSpan actual, Grid whole, Grid coarse, Grid fine)
+ {
+ (Actual, Whole, Coarse, Fine) = (actual, whole, coarse, fine);
+ }
+
+ internal TimeSpan Actual { get; }
+
+ internal Grid Coarse { get; }
+
+ internal Grid Fine { get; }
+
+ /// The luma of each block.
+ internal double[] Luma { get; } = new double[Blocks];
+
+ /// The frame as one cell: its mean colour.
+ internal Grid Whole { get; }
+
+ internal bool Dark { get; private set; }
+
+ internal bool Uniform { get; private set; }
+
+ internal double Sharpness { get; private set; }
+
+ /// The signature of an upright RGBA frame.
+ internal static Signature Of(RgbaImage image, TimeSpan actual)
+ {
+ var (w, h) = (image.Width, image.Height);
+ var coarse = Grid.Of(image, GridSize, GridSize);
+ var fine = Grid.Of(image, Math.Clamp(w / FineCell, 1, FineGridSize), Math.Clamp(h / FineCell, 1, FineGridSize));
+ var whole = Grid.Of(image, 1, 1);
+ var s = new Signature(actual, whole, coarse, fine);
+ var blue = new double[Blocks];
+ var red = new double[Blocks];
+ var brightest = 0.0;
+ for (var i = 0; i < Blocks; i++)
+ {
+ double r = coarse.Mean[0][i], g = coarse.Mean[1][i], b = coarse.Mean[2][i];
+ var luma = Bt709(r, g, b);
+ (s.Luma[i], blue[i], red[i]) = (luma, b - luma, r - luma);
+ brightest = Math.Max(brightest, Math.Max(r, Math.Max(g, b)));
+ }
+
+ ReadOnlySpan pixels = image.Pixels;
+ s.Dark = brightest < DarkLevel && !HasBrightDetail(pixels, w, h, image.Stride);
+ s.Uniform = Spread(s.Luma) < UniformSpread && Spread(blue) < UniformSpread && Spread(red) < UniformSpread
+ && !HasDetail(pixels, w, h, image.Stride, Bt709(whole.Mean[0][0], whole.Mean[1][0], whole.Mean[2][0]));
+ s.Sharpness = LaplacianVariance(pixels, w, h, image.Stride);
+ return s;
+ }
+
+ /// Whether some pixels are bright: a small text on black, lost in the means of the blocks.
+ private static bool HasBrightDetail(ReadOnlySpan pixels, int w, int h, int stride)
+ {
+ long bright = 0;
+ for (var y = 0; y < h; y++)
+ {
+ var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel);
+ for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel)
+ {
+ bright += Math.Max(row[i], Math.Max(row[i + 1], row[i + 2])) >= BrightDetail ? 1 : 0;
+ }
+ }
+
+ return bright > DetailShare * w * h;
+ }
+
+ /// Whether the pixels vary, though the blocks do not: a small text, a fine texture.
+ private static bool HasDetail(ReadOnlySpan pixels, int w, int h, int stride, double mean)
+ {
+ double squares = 0;
+ long far = 0;
+ for (var y = 0; y < h; y++)
+ {
+ var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel);
+ for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel)
+ {
+ var d = Bt709(row[i], row[i + 1], row[i + 2]) - mean;
+ squares += d * d;
+ far += Math.Abs(d) > UniformDetail ? 1 : 0;
+ }
+ }
+
+ return squares >= UniformVariance * w * h || far > DetailShare * w * h;
+ }
+
+ private static double Spread(double[] values)
+ {
+ var mean = values.Average();
+ var sum = 0.0;
+ foreach (var v in values)
+ {
+ sum += (v - mean) * (v - mean);
+ }
+
+ return Math.Sqrt(sum / values.Length);
+ }
+
+ ///
+ /// The variance of the 4-neighbour Laplacian of the luma over the inner pixels: larger for a sharper picture,
+ /// smaller for one blurred by the compression or dimmed by a fade (0 for a frame under 3 × 3 pixels).
+ ///
+ private static double LaplacianVariance(ReadOnlySpan pixels, int w, int h, int stride)
+ {
+ if (w < 3 || h < 3)
+ {
+ return 0;
+ }
+
+ var luma = ArrayPool.Shared.Rent(w * h);
+ try
+ {
+ for (var y = 0; y < h; y++)
+ {
+ var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel);
+ for (var x = 0; x < w; x++)
+ {
+ var p = x * RgbaImage.BytesPerPixel;
+ luma[(y * w) + x] = (byte)(((54 * row[p]) + (183 * row[p + 1]) + (19 * row[p + 2]) + 128) >> 8);
+ }
+ }
+
+ double sum = 0, squares = 0;
+ for (var y = 1; y < h - 1; y++)
+ {
+ var at = y * w;
+ for (var x = 1; x < w - 1; x++)
+ {
+ var i = at + x;
+ double lap = (4 * luma[i]) - luma[i - 1] - luma[i + 1] - luma[i - w] - luma[i + w];
+ sum += lap;
+ squares += lap * lap;
+ }
+ }
+
+ var n = (double)(w - 2) * (h - 2);
+ var mean = sum / n;
+ return Math.Max(0, (squares / n) - (mean * mean));
+ }
+ finally
+ {
+ ArrayPool.Shared.Return(luma);
+ }
+ }
+ }
+
+ ///
+ /// The stream, remembering the first error of its own: an or an
+ /// thrown by it, not the ones the readers raise above it for a file cut
+ /// short or damaged.
+ ///
+ private sealed class WatchedStream(Stream inner) : Stream
+ {
+ internal ExceptionDispatchInfo? Fault { get; private set; }
+
+ public override bool CanRead => true;
+
+ public override bool CanSeek => true;
+
+ public override bool CanWrite => false;
+
+ public override long Length
+ {
+ get
+ {
+ try
+ {
+ return inner.Length;
+ }
+ catch (Exception ex)
+ {
+ Remember(ex);
+ throw;
+ }
+ }
+ }
+
+ public override long Position
+ {
+ get => inner.Position;
+ set => inner.Position = value; // reads nothing: an error comes from a damaged table
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
+
+ public override int Read(Span buffer)
+ {
+ try
+ {
+ return inner.Read(buffer);
+ }
+ catch (Exception ex)
+ {
+ Remember(ex);
+ throw;
+ }
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
+
+ public override void Flush()
+ {
+ }
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ private void Remember(Exception ex)
+ {
+ if (ex is UnauthorizedAccessException or (IOException and not EndOfStreamException))
+ {
+ Fault ??= ExceptionDispatchInfo.Capture(ex);
+ }
+ }
+ }
+}
diff --git a/src/Febe.Core/Library/StillVideos/StillVideoService.cs b/src/Febe.Core/Library/StillVideos/StillVideoService.cs
new file mode 100644
index 0000000..6d1e683
--- /dev/null
+++ b/src/Febe.Core/Library/StillVideos/StillVideoService.cs
@@ -0,0 +1,834 @@
+using System.Security.Cryptography;
+using Febe.Core.Abstractions;
+using Febe.Core.Codecs.Containers;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library.Conversion;
+using Febe.Core.Storage;
+
+namespace Febe.Core.Library.StillVideos;
+
+/// What «È un video fermo?» and «Cerca i video fermi» need from the rest of Febe (tappa E4, D5).
+public sealed record StillVideoEnvironment
+{
+ public required IFebeStorage Storage { get; init; }
+
+ /// The full path of a library file on disk, or null when it is not there.
+ public required Func Resolve { get; init; }
+
+ public required IClock Clock { get; init; }
+
+ /// Import, copies, rebuild and zips of frames: the job waits while one holds it. Null: nothing to wait for (tests).
+ public LongWorkGate? Gate { get; init; }
+
+ /// The job never analyses during an engine session; the viewer may (answer 43).
+ public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
+
+ /// One heavy decode at a time with the conversions (E3, D16): the job takes it, the viewer does not.
+ public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
+
+ /// The file's SHA-256 is checked against the record before it is analysed (false only in the demo).
+ public bool VerifySource { get; init; } = true;
+
+ /// The longest analysis from the viewer, waiting for another included (answer 43); past it nothing is stored.
+ public TimeSpan ViewerBudget { get; init; } = TimeSpan.FromSeconds(30);
+
+ /// The longest analysis of one video of the job (answer 44); past it «Non analizzabile» (TooSlow) is stored.
+ public TimeSpan JobBudget { get; init; } = TimeSpan.FromMinutes(2);
+
+ /// How often the job looks again while it waits, and while it analyses whether it must give way.
+ public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5);
+
+ /// Called with the account of a video whose analysis was stored (the composition publishes a library change).
+ public Action? Changed { get; init; }
+
+ /// One line for the log: only Italian text and exception type names, never paths or messages.
+ public Action? Log { get; init; }
+
+ ///
+ /// Test seam: analyses the file at a path within a budget ( from the viewer,
+ /// whose budget is the token), honouring the token. By default
+ /// on the opened file.
+ ///
+ public Func? Analyser { get; init; }
+}
+
+/// How an analysis asked from the viewer ended.
+public enum StillVideoAnswerKind
+{
+ /// Analysed and stored: is the row.
+ Analysed,
+
+ /// No such file in the database (404).
+ NotFound,
+
+ /// A photo (400).
+ NotAVideo,
+
+ /// The file is not on disk (404).
+ FileMissing,
+
+ /// The bytes on disk are not the recorded ones (409): nothing stored.
+ SourceChanged,
+
+ /// Past (503): nothing stored.
+ TooSlow,
+
+ ///
+ /// As , on a video with a result the selection would skip: that result stays (503).
+ ///
+ TooSlowKept,
+}
+
+/// The answer to «È un video fermo?» from the viewer.
+/// How it ended.
+/// The stored row, for .
+/// What the analyser found, for (audio, rotation, measures).
+/// The account of the file, when known.
+public sealed record StillVideoAnswer(StillVideoAnswerKind Kind, VideoAnalysis? Analysis, StillVideoResult? Result, long? AccountId)
+{
+ /// The Italian text of a failure; null for .
+ public string? Message => Kind switch
+ {
+ StillVideoAnswerKind.NotFound => StillVideoText.NotFound,
+ StillVideoAnswerKind.NotAVideo => StillVideoText.NotAVideo,
+ StillVideoAnswerKind.FileMissing => StillVideoText.FileMissing,
+ StillVideoAnswerKind.SourceChanged => StillVideoText.SourceChanged,
+ StillVideoAnswerKind.TooSlow => StillVideoText.TooSlow,
+ StillVideoAnswerKind.TooSlowKept => StillVideoText.TooSlowKept,
+ _ => null,
+ };
+}
+
+///
+/// What «Cerca i video fermi» would do for a selection, counted by file (SHA-256): a video found under two entries is
+/// analysed once.
+///
+/// Videos in the library with no result of the current algorithm.
+///
+/// Videos in the library with a result of the current algorithm (skipped); one whose analysis took too long counts among
+/// those to analyse.
+///
+/// Photos of the selection (skipped).
+/// Videos of the selection not in the library (not downloaded, deleted, file not recorded).
+public sealed record StillVideoPlan(int ToAnalyse, int AlreadyAnalysed, int PhotosSkipped, int Missing)
+{
+ /// The videos of the selection.
+ public int Videos => ToAnalyse + AlreadyAnalysed + Missing;
+}
+
+/// The job «Cerca i video fermi» as the Dashboard shows it.
+/// True while videos are queued or one is analysed.
+/// Videos of the job (since the last start of a job that was not running).
+/// Videos settled: + + + .
+/// Found «Fermo».
+/// Found «In movimento».
+/// Found «Non analizzabile».
+/// Left out without a result: the file went or changed, or an unexpected error.
+/// True once «Interrompi» ended the job.
+/// Why the job waits now (an engine session, a long work, the viewer), or null.
+/// The library file analysed now, or null.
+/// Of the answer of a start: the videos it added to the job (those already queued are not); else 0.
+public sealed record StillVideoProgress(
+ bool Running,
+ int Total,
+ int Done,
+ int Still,
+ int Moving,
+ int NotAnalyzable,
+ int Skipped,
+ bool Stopped,
+ string? Waiting,
+ long? CurrentMediaId,
+ int Added = 0);
+
+///
+/// «È un video fermo?» (spec §4.10, tappa E4, D5): only on request, never in the background over the library.
+///
+/// , from the viewer: at any time, also during an engine session (answer 43), one at
+/// a time, within ; past it nothing is stored. It comes before the job:
+/// the video the job is analysing is put back at the front of its queue.
+/// , «Cerca i video fermi» from a selection (answer 41): a job in memory, one video at a
+/// time, never during an engine session and never while an import, a copy, a rebuild or a zip of frames holds the
+/// (it takes no lease, so it never blocks them: a video being analysed when one starts is
+/// given up and analysed again after). Each video within , inside the
+/// ; past it «Non analizzabile» (TooSlow) is stored. Videos with a result of the current
+/// algorithm are skipped, but for those whose analysis took too long (a start tries them again, once): so a job ended by
+/// «Interrompi» or by closing Febe is not resumed by itself: started again, it goes on where it was.
+///
+/// Results go to video_analysis by SHA-256 of the file (checked against the record first), with
+/// .
+///
+public sealed class StillVideoService : IDisposable
+{
+ private readonly StillVideoEnvironment _env;
+ private readonly Func _analyse;
+ private readonly CancellationTokenSource _life = new();
+ private readonly SemaphoreSlim _one = new(1, 1);
+ private readonly Lock _lock = new();
+
+ // The job, under _lock.
+ private readonly LinkedList _queue = new();
+ private readonly HashSet _queued = new(StringComparer.Ordinal);
+ private CancellationTokenSource _jobStop = new();
+ private CancellationTokenSource? _item;
+ private JobItem? _current;
+ private Task _loop = Task.CompletedTask;
+ private bool _running;
+ private int _viewers;
+ private TaskCompletionSource _wake = NewWake();
+ private int _total;
+ private int _still;
+ private int _moving;
+ private int _notAnalyzable;
+ private int _skipped;
+ private bool _stopped;
+ private string? _waiting;
+ private bool _disposed;
+
+ public StillVideoService(StillVideoEnvironment env)
+ {
+ _env = env ?? throw new ArgumentNullException(nameof(env));
+ _analyse = env.Analyser ?? AnalyseFile;
+ }
+
+ private sealed record JobItem(string Sha256, long MediaId, long AccountId);
+
+ /// The job now.
+ public StillVideoProgress Progress
+ {
+ get
+ {
+ lock (_lock)
+ {
+ return Snapshot();
+ }
+ }
+ }
+
+ /// The loop of the job now: completed when no job runs (for the tests and an orderly stop).
+ public Task Job
+ {
+ get
+ {
+ lock (_lock)
+ {
+ return _loop;
+ }
+ }
+ }
+
+ // ------------------------------------------------------------------------------------------------- viewer
+
+ ///
+ /// «È un video fermo?» for one library file, now (D5): resolves it, checks its SHA-256, analyses it and stores the
+ /// result, also when one is already stored («Analizza di nuovo»). Never throws for what the page can be told.
+ ///
+ public async Task AnalyseNowAsync(long mediaId, CancellationToken ct = default)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ var storage = _env.Storage;
+ var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false);
+ if (media is null)
+ {
+ return new StillVideoAnswer(StillVideoAnswerKind.NotFound, null, null, null);
+ }
+
+ if (media.Kind != MediaKind.Video)
+ {
+ return new StillVideoAnswer(StillVideoAnswerKind.NotAVideo, null, null, null);
+ }
+
+ var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false);
+ var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false);
+ if (account is null)
+ {
+ return new StillVideoAnswer(StillVideoAnswerKind.NotFound, null, null, null);
+ }
+
+ var path = media.Sha256 is { Length: 64 } && EntryStateRules.IsPresent(media.State) ? _env.Resolve(account, media) : null;
+ if (path is null)
+ {
+ return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id);
+ }
+
+ var sha = media.Sha256!.ToLowerInvariant();
+ EnterViewer();
+ try
+ {
+ if (_env.VerifySource)
+ {
+ // Outside the budget, as reading the file for a frame is: the page shows that it is working.
+ string actual;
+ try
+ {
+ actual = await HashAsync(path, ct).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id);
+ }
+
+ if (!string.Equals(actual, sha, StringComparison.Ordinal))
+ {
+ return new StillVideoAnswer(StillVideoAnswerKind.SourceChanged, null, null, account.Id);
+ }
+ }
+
+ using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ if (_env.ViewerBudget <= TimeSpan.Zero)
+ {
+ // No time at all: cancelled now, not by a timer that a busy machine may fire after a quick analysis.
+ budget.Cancel();
+ }
+ else
+ {
+ budget.CancelAfter(_env.ViewerBudget);
+ }
+
+ StillVideoResult result;
+ try
+ {
+ await _one.WaitAsync(budget.Token).ConfigureAwait(false);
+ try
+ {
+ result = await Task.Run(() => _analyse(path, Timeout.InfiniteTimeSpan, budget.Token), budget.Token).ConfigureAwait(false);
+ }
+ finally
+ {
+ _one.Release();
+ }
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ return await TooSlowAsync(sha, account.Id).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // The file went between the check and the analysis, or stopped being readable during it.
+ return new StillVideoAnswer(StillVideoAnswerKind.FileMissing, null, null, account.Id);
+ }
+
+ if (result is { Outcome: VideoAnalysisOutcome.NotAnalyzable, Note: VideoAnalysisNotes.TooSlow })
+ {
+ return await TooSlowAsync(sha, account.Id).ConfigureAwait(false);
+ }
+
+ var analysis = result.ToAnalysis(sha, _env.Clock.Now);
+ await storage.VideoAnalyses.SetAsync(analysis, CancellationToken.None).ConfigureAwait(false);
+ _env.Changed?.Invoke(account.Id);
+ return new StillVideoAnswer(StillVideoAnswerKind.Analysed, analysis, result, account.Id);
+ }
+ finally
+ {
+ LeaveViewer();
+ }
+ }
+
+ ///
+ /// The answer past the budget of the viewer: «avviala dalla selezione» only for a video the selection would analyse.
+ ///
+ private async Task TooSlowAsync(string sha, long accountId)
+ {
+ var kept = await _env.Storage.VideoAnalyses.GetAsync(sha, CancellationToken.None).ConfigureAwait(false);
+ return new StillVideoAnswer(kept is not null && IsSettled(kept) ? StillVideoAnswerKind.TooSlowKept : StillVideoAnswerKind.TooSlow, null, null, accountId);
+ }
+
+ ///
+ /// Whether the job skips a video with this result: one of the current algorithm, unless its analysis took too long
+ /// (it is not an analysis of the video: another moment, or an idle machine, may give one).
+ ///
+ private static bool IsSettled(VideoAnalysis analysis) =>
+ analysis.Algorithm >= StillVideoAnalyzer.Algorithm
+ && !(analysis.Outcome == VideoAnalysisOutcome.NotAnalyzable
+ && (analysis.Note ?? string.Empty).Split(' ').Contains(VideoAnalysisNotes.TooSlow, StringComparer.Ordinal));
+
+ // ------------------------------------------------------------------------------------------------- job
+
+ /// The counts of the confirmation of «Cerca i video fermi» for .
+ public async Task PlanAsync(ExportSelection selection, CancellationToken ct = default)
+ {
+ var (items, already, photos, missing) = await CollectAsync(selection, ct).ConfigureAwait(false);
+ return new StillVideoPlan(items.Count, already, photos, missing);
+ }
+
+ ///
+ /// Starts «Cerca i video fermi» for , or adds its videos to the job already running (a
+ /// video already queued is not queued twice). Returns the job as it is then, with how many videos were added.
+ ///
+ public async Task StartAsync(ExportSelection selection, CancellationToken ct = default)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ var (items, _, _, _) = await CollectAsync(selection, ct).ConfigureAwait(false);
+ lock (_lock)
+ {
+ if (!_running || _jobStop.IsCancellationRequested)
+ {
+ // A new job (none runs, or the last one was stopped and is still giving up its video): its counts go.
+ _total = _still = _moving = _notAnalyzable = _skipped = 0;
+ _stopped = false;
+ _waiting = null;
+ }
+
+ if (_jobStop.IsCancellationRequested)
+ {
+ // Not disposed: the loop that is ending may still read its token.
+ _jobStop = new CancellationTokenSource();
+ }
+
+ var added = 0;
+ foreach (var item in items)
+ {
+ if (_queued.Add(item.Sha256))
+ {
+ _queue.AddLast(item);
+ _total++;
+ added++;
+ }
+ }
+
+ if (_queue.Count > 0 && !_running)
+ {
+ _running = true;
+ _loop = Task.Run(LoopAsync);
+ }
+
+ return Snapshot() with { Added = added };
+ }
+ }
+
+ /// «Interrompi»: the queue empties, the video being analysed is given up and nothing is stored for it.
+ public StillVideoProgress Stop()
+ {
+ lock (_lock)
+ {
+ if (_running)
+ {
+ _queue.Clear();
+ _queued.Clear();
+ _stopped = true;
+ _waiting = null;
+ _jobStop.Cancel();
+ }
+
+ return Snapshot();
+ }
+ }
+
+ public void Dispose()
+ {
+ lock (_lock)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+ _queue.Clear();
+ _queued.Clear();
+ }
+
+ _life.Cancel();
+ // The loop may still be ending: the token sources are left to the collector, as LongWorkGate does.
+ }
+
+ private async Task LoopAsync()
+ {
+ while (true)
+ {
+ JobItem item;
+ lock (_lock)
+ {
+ if (_queue.First is not { } first || _life.IsCancellationRequested)
+ {
+ _running = false;
+ _current = null;
+ _waiting = null;
+ return;
+ }
+
+ item = first.Value;
+ }
+
+ try
+ {
+ await RunItemAsync(item).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (_life.IsCancellationRequested)
+ {
+ lock (_lock)
+ {
+ _running = false;
+ _current = null;
+ return;
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // Given way (viewer, session, long work: the video stays at the front) or «Interrompi» (the queue is
+ // empty): the top of the loop decides.
+ }
+ catch (Exception ex)
+ {
+ // One video never stops the job: it is left out without a result, the log gets the type only.
+ _env.Log?.Invoke($"Un video non si è potuto analizzare ({ex.GetType().Name}).");
+ Settle(item, null);
+ }
+ }
+ }
+
+ /// Waits for its turn, then analyses and stores the result; leaves it at the front when it gives way.
+ private async Task RunItemAsync(JobItem item)
+ {
+ var life = _life.Token;
+ CancellationTokenSource itemSource;
+ CancellationToken stop;
+ while (true)
+ {
+ var reason = BackgroundReason();
+ lock (_lock)
+ {
+ stop = _jobStop.Token;
+ stop.ThrowIfCancellationRequested();
+ reason ??= _viewers > 0 ? StillVideoText.Viewer : null;
+ _waiting = reason;
+ if (reason is null)
+ {
+ itemSource = CancellationTokenSource.CreateLinkedTokenSource(life, stop);
+ _item = itemSource;
+ _current = item;
+ break;
+ }
+ }
+
+ await WaitAsync(stop).ConfigureAwait(false);
+ }
+
+ using var watch = CancellationTokenSource.CreateLinkedTokenSource(itemSource.Token);
+ var watcher = WatchAsync(itemSource, watch.Token);
+ try
+ {
+ var token = itemSource.Token;
+ var storage = _env.Storage;
+ var sha = item.Sha256;
+ if (await storage.VideoAnalyses.GetAsync(sha, token).ConfigureAwait(false) is { } existing && IsSettled(existing))
+ {
+ // Analysed meanwhile (from the viewer, or under another entry of the same file).
+ Settle(item, existing.Outcome);
+ return;
+ }
+
+ var path = await PathAsync(item, token).ConfigureAwait(false);
+ if (path is null)
+ {
+ Settle(item, null);
+ return;
+ }
+
+ if (_env.VerifySource)
+ {
+ string actual;
+ try
+ {
+ actual = await HashAsync(path, token).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Settle(item, null);
+ return;
+ }
+
+ if (!string.Equals(actual, sha, StringComparison.Ordinal))
+ {
+ Settle(item, null);
+ return;
+ }
+ }
+
+ StillVideoResult result;
+ try
+ {
+ result = await _env.Throttle.RunAsync(t => _analyse(path, _env.JobBudget, t), token).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ Settle(item, null);
+ return;
+ }
+
+ token.ThrowIfCancellationRequested();
+ await storage.VideoAnalyses.SetAsync(result.ToAnalysis(sha, _env.Clock.Now), CancellationToken.None).ConfigureAwait(false);
+ Settle(item, result.Outcome);
+ _env.Changed?.Invoke(item.AccountId);
+ }
+ finally
+ {
+ await watch.CancelAsync().ConfigureAwait(false);
+ await watcher.ConfigureAwait(false);
+ lock (_lock)
+ {
+ if (ReferenceEquals(_item, itemSource))
+ {
+ _item = null;
+ }
+
+ _current = null;
+ }
+
+ itemSource.Dispose();
+ }
+ }
+
+ ///
+ /// The library file of on disk, if it is still the same file in the library; otherwise another
+ /// file of the library with the same bytes (the same video under another entry or account).
+ ///
+ private async Task PathAsync(JobItem item, CancellationToken ct)
+ {
+ var storage = _env.Storage;
+ var media = await storage.Media.GetAsync(item.MediaId, ct).ConfigureAwait(false);
+ if (media is not null && media.Kind == MediaKind.Video && EntryStateRules.IsPresent(media.State)
+ && string.Equals(media.Sha256?.ToLowerInvariant(), item.Sha256, StringComparison.Ordinal)
+ && await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) is { } entry
+ && await ResolveAsync(media, entry.AccountId, ct).ConfigureAwait(false) is { } path)
+ {
+ return path;
+ }
+
+ foreach (var location in await storage.Media.FindBySha256Async(item.Sha256, ct).ConfigureAwait(false))
+ {
+ if (location.Media.Kind == MediaKind.Video && EntryStateRules.IsPresent(location.Media.State)
+ && await ResolveAsync(location.Media, location.Entry.AccountId, ct).ConfigureAwait(false) is { } other)
+ {
+ return other;
+ }
+ }
+
+ return null;
+ }
+
+ /// The path of a library file that is really on the disk, or null.
+ private async Task ResolveAsync(Media media, long accountId, CancellationToken ct)
+ {
+ var account = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
+ var path = account is null ? null : _env.Resolve(account, media);
+ return path is not null && File.Exists(path) ? path : null;
+ }
+
+ ///
+ /// While a video is analysed, every : an engine session or a long work that
+ /// started meanwhile makes the job give way (the video is analysed again after).
+ ///
+ private async Task WatchAsync(CancellationTokenSource item, CancellationToken ct)
+ {
+ try
+ {
+ while (!ct.IsCancellationRequested)
+ {
+ await _env.Clock.Delay(_env.Poll, ct).ConfigureAwait(false);
+ await Task.Yield();
+ if (!ct.IsCancellationRequested && BackgroundReason() is { } reason)
+ {
+ lock (_lock)
+ {
+ _waiting = reason;
+ }
+
+ await item.CancelAsync().ConfigureAwait(false);
+ return;
+ }
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ // The video ended.
+ }
+ catch (ObjectDisposedException)
+ {
+ // The video ended and its token source went.
+ }
+ }
+
+ /// Waits , or less when an analysis from the viewer ends.
+ private async Task WaitAsync(CancellationToken stop)
+ {
+ Task wake;
+ lock (_lock)
+ {
+ wake = _wake.Task;
+ }
+
+ using var linked = CancellationTokenSource.CreateLinkedTokenSource(_life.Token, stop);
+ var delay = _env.Clock.Delay(_env.Poll, linked.Token);
+ await Task.WhenAny(delay, wake).ConfigureAwait(false);
+ await linked.CancelAsync().ConfigureAwait(false);
+ await Task.Yield();
+ _life.Token.ThrowIfCancellationRequested();
+ stop.ThrowIfCancellationRequested();
+ }
+
+ /// Why the job may not analyse now, but for the viewer: an engine session or a long work.
+ private string? BackgroundReason()
+ {
+ if (_env.Session.InSession)
+ {
+ return StillVideoText.InSession;
+ }
+
+ return _env.Gate?.Busy is not null ? StillVideoText.LongWork : null;
+ }
+
+ /// Counts (with its outcome, or as left out) and takes it off the front of the queue.
+ private void Settle(JobItem item, VideoAnalysisOutcome? outcome)
+ {
+ lock (_lock)
+ {
+ if (_queue.First is not { } first || !ReferenceEquals(first.Value, item))
+ {
+ return; // «Interrompi» emptied the queue meanwhile
+ }
+
+ _queue.RemoveFirst();
+ _queued.Remove(item.Sha256);
+ switch (outcome)
+ {
+ case VideoAnalysisOutcome.Still:
+ _still++;
+ break;
+ case VideoAnalysisOutcome.Moving:
+ _moving++;
+ break;
+ case VideoAnalysisOutcome.NotAnalyzable:
+ _notAnalyzable++;
+ break;
+ default:
+ _skipped++;
+ break;
+ }
+ }
+ }
+
+ private void EnterViewer()
+ {
+ CancellationTokenSource? preempted;
+ lock (_lock)
+ {
+ _viewers++;
+ preempted = _item;
+ _item = null;
+ if (preempted is not null)
+ {
+ _waiting = StillVideoText.Viewer;
+ }
+ }
+
+ // Outside the lock: the token's callbacks run synchronously.
+ try
+ {
+ preempted?.Cancel();
+ }
+ catch (ObjectDisposedException)
+ {
+ // That video had just ended.
+ }
+ }
+
+ private void LeaveViewer()
+ {
+ TaskCompletionSource wake;
+ lock (_lock)
+ {
+ _viewers--;
+ wake = _wake;
+ _wake = NewWake();
+ }
+
+ wake.TrySetResult();
+ }
+
+ ///
+ /// The present videos of to analyse, one per SHA-256 in media order, with the counts of
+ /// those already analysed (by file), the photos and the videos not in the library.
+ ///
+ private async Task<(List Items, int Already, int Photos, int Missing)> CollectAsync(ExportSelection selection, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(selection);
+ var storage = _env.Storage;
+ var accounts = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).Select(a => a.Id).ToHashSet();
+ var present = new List();
+ var seen = new HashSet(StringComparer.Ordinal);
+ 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 || c.Sha256 is not { Length: 64 } || !accounts.Contains(c.AccountId))
+ {
+ missing++;
+ }
+ else if (seen.Add(c.Sha256.ToLowerInvariant()))
+ {
+ present.Add(new JobItem(c.Sha256.ToLowerInvariant(), c.MediaId, c.AccountId));
+ }
+ }
+ }
+
+ var items = new List();
+ var already = 0;
+ foreach (var chunk in present.Chunk(500))
+ {
+ var found = await storage.VideoAnalyses.GetManyAsync(chunk.Select(i => i.Sha256).ToList(), ct).ConfigureAwait(false);
+ foreach (var item in chunk)
+ {
+ if (found.TryGetValue(item.Sha256, out var analysis) && IsSettled(analysis))
+ {
+ already++;
+ }
+ else
+ {
+ items.Add(item);
+ }
+ }
+ }
+
+ return (items, already, photos, missing);
+ }
+
+ private StillVideoProgress Snapshot()
+ {
+ var done = _still + _moving + _notAnalyzable + _skipped;
+ return new StillVideoProgress(_running, _total, done, _still, _moving, _notAnalyzable, _skipped, _stopped, _running ? _waiting : null, _current?.MediaId);
+ }
+
+ private static TaskCompletionSource NewWake() => new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ private static StillVideoResult AnalyseFile(string path, TimeSpan budget, CancellationToken ct)
+ {
+ using var stream = ContainerReader.OpenRead(path);
+ return StillVideoAnalyzer.Analyse(stream, budget == Timeout.InfiniteTimeSpan ? TimeSpan.MaxValue : budget, ct);
+ }
+
+ private static async Task HashAsync(string path, CancellationToken ct)
+ {
+ var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024,
+ FileOptions.Asynchronous | FileOptions.SequentialScan);
+ await using (stream.ConfigureAwait(false))
+ {
+ return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
+ }
+ }
+}
diff --git a/src/Febe.Core/Library/StillVideos/StillVideoText.cs b/src/Febe.Core/Library/StillVideos/StillVideoText.cs
new file mode 100644
index 0000000..554c6fc
--- /dev/null
+++ b/src/Febe.Core/Library/StillVideos/StillVideoText.cs
@@ -0,0 +1,90 @@
+using Febe.Core.Engine;
+
+namespace Febe.Core.Library.StillVideos;
+
+/// The Italian texts of «È un video fermo?» and «Cerca i video fermi» (spec §4.10, tappa E4).
+public static class StillVideoText
+{
+ /// The analysis from the viewer did not end within its budget (answer 43): nothing is stored.
+ public const string TooSlow = "L'analisi richiede troppo tempo: avviala dalla selezione";
+
+ /// As , when the video has a result the selection would skip: that result stays.
+ public const string TooSlowKept = "L'analisi richiede troppo tempo: resta l'esito di prima";
+
+ /// The file asked for is not in the database.
+ public const string NotFound = "File non trovato.";
+
+ /// The file asked for is a photo.
+ public const string NotAVideo = "Solo un video può essere un video fermo.";
+
+ /// The file is not on disk.
+ public const string FileMissing = "File non presente in libreria";
+
+ /// The bytes on disk are not the ones recorded (the same words as the copies).
+ public const string SourceChanged = "Il file della libreria non corrisponde a quello registrato.";
+
+ /// «Salva il fotogramma» of a video whose analysis is not «Fermo», or that was never analysed.
+ public const string NotStill = "Non è un video fermo, o non è stato analizzato";
+
+ /// A selection of «Cerca i video fermi» that names nothing.
+ public const string NoSelection = "Scegli quali video analizzare: dei file, degli elementi, i risultati del filtro o un account.";
+
+ /// The frame of a still video is saved from the viewer only (answer 46).
+ public const string FromViewerOnly = "Il fotogramma di un video fermo si salva dal visualizzatore, con «Salva il fotogramma».";
+
+ /// The job waits for the end of an engine session.
+ public const string InSession = "Il motore è in sessione: la ricerca dei video fermi riprende dopo";
+
+ /// The job waits for an import, a copy, a rebuild or a zip of frames.
+ public const string LongWork = "Un'importazione, una copia o una ricostruzione è al lavoro: la ricerca dei video fermi riprende dopo";
+
+ /// The job waits for an analysis asked from the viewer, which comes first.
+ public const string Viewer = "Un video si sta analizzando dal visualizzatore: la ricerca dei video fermi riprende subito dopo";
+
+ /// «28 video da analizzare · 12 già analizzati · le 5 foto si saltano · 1 video non presente in libreria».
+ public static string PlanSummary(StillVideoPlan plan)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ var parts = new List { $"{ItalianText.Number(plan.ToAnalyse)} video da analizzare" };
+ if (plan.AlreadyAnalysed > 0)
+ {
+ parts.Add(plan.AlreadyAnalysed == 1 ? "1 già analizzato" : $"{ItalianText.Number(plan.AlreadyAnalysed)} già analizzati");
+ }
+
+ if (plan.PhotosSkipped > 0)
+ {
+ parts.Add(plan.PhotosSkipped == 1 ? "la foto si salta" : $"le {ItalianText.Number(plan.PhotosSkipped)} foto si saltano");
+ }
+
+ if (plan.Missing > 0)
+ {
+ parts.Add($"{ItalianText.Number(plan.Missing)} video non {(plan.Missing == 1 ? "presente" : "presenti")} in libreria");
+ }
+
+ return string.Join(" · ", parts);
+ }
+
+ /// «Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile» (the toast at the end of a job).
+ public static string Summary(StillVideoProgress progress)
+ {
+ ArgumentNullException.ThrowIfNull(progress);
+ var analysed = progress.Still + progress.Moving + progress.NotAnalyzable;
+ var head = analysed == 1 ? "Analizzato 1 video" : $"Analizzati {ItalianText.Number(analysed)} video";
+ var parts = new List
+ {
+ progress.Still == 1 ? "1 fermo" : $"{ItalianText.Number(progress.Still)} fermi",
+ $"{ItalianText.Number(progress.Moving)} in movimento",
+ };
+ if (progress.NotAnalyzable > 0)
+ {
+ parts.Add(progress.NotAnalyzable == 1 ? "1 non analizzabile" : $"{ItalianText.Number(progress.NotAnalyzable)} non analizzabili");
+ }
+
+ if (progress.Skipped > 0)
+ {
+ parts.Add(progress.Skipped == 1 ? "1 saltato" : $"{ItalianText.Number(progress.Skipped)} saltati");
+ }
+
+ return head + ": " + string.Join(", ", parts);
+ }
+}
diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs
index 93e26e4..9fa04a1 100644
--- a/src/Febe.Core/Library/VideoFrameDecoder.cs
+++ b/src/Febe.Core/Library/VideoFrameDecoder.cs
@@ -45,33 +45,20 @@ public sealed record VideoImage(int Width, int Height, byte[] Rgb)
}
}
-///
-/// Whether a video only shows a still picture (a photo with music, for example): then one frame stands for the whole
-/// video. is the largest mean difference, on a 0–255 scale, between the first sampled frame and
-/// the others, measured on a coarse grid so that the noise of the compression does not count.
-///
-public sealed record VideoStillness(bool IsStill, int SampledFrames, double Difference);
-
///
/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover):
/// the container readers of and the H.264 and HEVC decoders written in house
/// (, ). Videos in other codecs (VP9, AV1, ...) give no frame: the
-/// interface shows the neutral tile.
+/// interface shows the neutral tile. Whether a video is still is told by .
///
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;
-
///
- /// The longest a frame or a stillness analysis may take: what the external extractor used before C3 was given. A damaged
- /// file never holds an import or a rebuild for longer.
+ /// The longest a frame may take: what the external extractor used before C3 was given. A damaged file never holds an
+ /// import or a rebuild for longer.
///
public static readonly TimeSpan DefaultBudget = TimeSpan.FromSeconds(30);
- private const int GridSize = 32;
- private const int SampledPositions = 6;
- private const int MaxSequentialSamples = 2000;
private const int DefaultMaxRun = 300;
/// How far back from a sample flagged as key the decoder looks for one it can really start from.
@@ -125,16 +112,6 @@ public sealed partial class VideoFrameDecoder
return Task.Run(() => WithinBudget(token => DecodeFrame(videoPath, at, maxLongSide, token), ct), ct);
}
- ///
- /// Whether the video shows a still picture, from frames spread over its whole length; null when it cannot be told
- /// (unreadable file, codec not decoded, or one long run without key frames in a long video).
- ///
- public Task AnalyseStillnessAsync(string videoPath, CancellationToken ct = default)
- {
- ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
- return Task.Run(() => WithinBudget(token => AnalyseStillness(videoPath, token), ct), ct);
- }
-
/// Runs for at most the budget: past it the result is null, as for an unreadable file.
private T? WithinBudget(Func work, CancellationToken ct)
where T : class
@@ -174,7 +151,7 @@ public sealed partial class VideoFrameDecoder
var target = SampleAt(video, at);
// Too far from where decoding can start: the frame there stands for it, so the work stays bounded.
- var start = decoding.RunStart(target);
+ var start = decoding.RunStart(target, ct);
if (target - start > maxRun)
{
target = start;
@@ -197,94 +174,6 @@ public sealed partial class VideoFrameDecoder
}
}
- private VideoStillness? AnalyseStillness(string path, CancellationToken ct)
- {
- try
- {
- ct.ThrowIfCancellationRequested();
- using var stream = ContainerReader.OpenRead(path);
- if (Open(stream) is not { } video)
- {
- return null;
- }
-
- var samples = video.Samples;
- if (samples.Count == 1)
- {
- return new VideoStillness(true, 1, 0);
- }
-
- // Positions spread over the presentation, from the first to the last frame.
- long first = long.MaxValue, last = long.MinValue;
- foreach (var s in samples)
- {
- first = Math.Min(first, s.PresentationTime);
- last = Math.Max(last, s.PresentationTime);
- }
-
- var decoding = new Decoding(stream, video, maxRun);
- var targets = new SortedSet();
- for (var i = 0; i < SampledPositions; i++)
- {
- ct.ThrowIfCancellationRequested();
- var time = first + ((last - first) * i / (SampledPositions - 1));
- var index = Closest(samples, time);
-
- // Far from where decoding can start in a long video: the frame there stands for it, so the work stays
- // bounded.
- var start = decoding.RunStart(index);
- if (index - start > maxRun && samples.Count > MaxSequentialSamples)
- {
- index = start;
- }
-
- targets.Add(index);
- }
-
- if (targets.Count < 2)
- {
- return null;
- }
-
- var frames = decoding.DecodeAll([.. targets], ct);
- if (frames.Count < 2)
- {
- return null;
- }
-
- double[]? reference = null;
- var difference = 0.0;
- foreach (var index in targets)
- {
- if (!frames.TryGetValue(index, out var frame))
- {
- continue;
- }
-
- var grid = Grid(frame);
- if (reference is null)
- {
- reference = grid;
- continue;
- }
-
- double sum = 0;
- for (var i = 0; i < grid.Length; i++)
- {
- sum += Math.Abs(grid[i] - reference[i]);
- }
-
- difference = Math.Max(difference, sum / grid.Length);
- }
-
- return new VideoStillness(difference <= StillThreshold, frames.Count, Math.Round(difference, 2));
- }
- catch (Exception ex) when (IsUnreadable(ex))
- {
- return null;
- }
- }
-
private static bool IsUnreadable(Exception ex) => ex is ContainerException or H264Exception or H265Exception or IOException
or EndOfStreamException or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException
or InvalidOperationException or OverflowException or InvalidDataException;
@@ -463,11 +352,11 @@ public sealed partial class VideoFrameDecoder
/// out exact); otherwise the nearest close one (an H.264 picture of I slices, an HEVC CRA picture: close, though
/// pictures after it may refer to earlier ones); otherwise the exact start further back, or the first sample.
///
- internal int RunStart(int index)
+ internal int RunStart(int index, CancellationToken ct)
{
if (exact)
{
- return ExactStart(index);
+ return ExactStart(index, ct);
}
var position = Array.BinarySearch(keys, index);
@@ -478,6 +367,7 @@ public sealed partial class VideoFrameDecoder
var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point))
{
+ ct.ThrowIfCancellationRequested(); // each one reads a whole sample
point = AccessPointOf(candidate);
accessPoints[candidate] = point;
}
@@ -506,7 +396,7 @@ public sealed partial class VideoFrameDecoder
/// 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)
+ private int ExactStart(int index, CancellationToken ct)
{
var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1);
@@ -516,6 +406,7 @@ public sealed partial class VideoFrameDecoder
var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point))
{
+ ct.ThrowIfCancellationRequested(); // each one reads a whole sample
point = AccessPointOf(candidate);
accessPoints[candidate] = point;
}
@@ -560,8 +451,8 @@ public sealed partial class VideoFrameDecoder
}
///
- /// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a
- /// stillness check asks for.
+ /// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail asks
+ /// for.
///
internal Dictionary DecodeAll(int[] targets, CancellationToken ct)
{
@@ -588,7 +479,7 @@ public sealed partial class VideoFrameDecoder
var next = 0;
foreach (var target in targets)
{
- var key = RunStart(target);
+ var key = RunStart(target, ct);
if (runner is null || next > target || key >= next)
{
runner = null;
@@ -648,65 +539,6 @@ public sealed partial class VideoFrameDecoder
}
}
- /// A coarse grid of mean luma and chroma values, to compare frames without their compression noise.
- private static double[] Grid(Frame frame) =>
- frame.Hevc is { } h ? Grid(Planes(h)) : frame.Avc!.BytesPerSample == 2 ? Grid(WidePlanes(frame.Avc)) : Grid(Planes(frame.Avc));
-
- ///
- /// The grid on an 8-bit scale: luma means in the first half, mean distances of the chroma from its middle in the
- /// second (zero for a monochrome picture).
- ///
- private static double[] Grid(in YuvPlanes frame)
- where T : unmanaged, IBinaryInteger
- {
- var grid = new double[GridSize * GridSize * 2];
- var counts = new int[GridSize * GridSize];
- var lumaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthY - 8));
- ReadOnlySpan luma = frame.Y;
- for (var y = 0; y < frame.Height; y++)
- {
- var gy = y * GridSize / frame.Height;
- var row = luma.Slice(y * frame.Width, frame.Width);
- for (var x = 0; x < row.Length; x++)
- {
- var cell = (gy * GridSize) + (x * GridSize / frame.Width);
- grid[cell] += int.CreateTruncating(row[x]) * lumaScale;
- counts[cell]++;
- }
- }
-
- var chromaCounts = new int[GridSize * GridSize];
- if (!frame.Monochrome)
- {
- var cw = frame.ChromaWidth;
- var ch = (frame.Height + (1 << frame.ChromaShiftY) - 1) >> frame.ChromaShiftY;
- var middle = 1 << (frame.BitDepthC - 1);
- var chromaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthC - 8)) / 2;
- ReadOnlySpan cb = frame.Cb, cr = frame.Cr;
- for (var y = 0; y < ch; y++)
- {
- var gy = y * GridSize / ch;
- for (var x = 0; x < cw; x++)
- {
- var cell = (gy * GridSize) + (x * GridSize / cw);
- var i = (y * cw) + x;
- grid[(GridSize * GridSize) + cell] +=
- (Math.Abs(int.CreateTruncating(cb[i]) - middle) + Math.Abs(int.CreateTruncating(cr[i]) - middle)) * chromaScale;
- chromaCounts[cell]++;
- }
- }
- }
-
- for (var i = 0; i < counts.Length; i++)
- {
- grid[i] = counts[i] > 0 ? grid[i] / counts[i] : 0;
- var c = (GridSize * GridSize) + i;
- grid[c] = chromaCounts[i] > 0 ? grid[c] / chromaCounts[i] : 0;
- }
-
- return grid;
- }
-
///
/// The planes of an H.264 frame of 8-bit samples, at any chroma sampling. A monochrome frame comes with grey 4:2:0
/// chroma planes (), which the conversion does not read.
@@ -719,7 +551,7 @@ public sealed partial class VideoFrameDecoder
///
/// The planes of an H.264 frame above 8 bits (two bytes a sample, little-endian), as 16-bit values: copied once,
- /// for the few frames a thumbnail or a stillness check decodes.
+ /// for the few frames a thumbnail or a frame copy decodes.
///
private static YuvPlanes WidePlanes(H264Frame frame)
{
diff --git a/src/Febe.Core/Library/VideoFrames.cs b/src/Febe.Core/Library/VideoFrames.cs
index f941390..32e9828 100644
--- a/src/Febe.Core/Library/VideoFrames.cs
+++ b/src/Febe.Core/Library/VideoFrames.cs
@@ -93,9 +93,10 @@ public sealed class VideoFrameReader : IDisposable
///
/// 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.
+ /// throws for a video it cannot read: is then not available, and the reader gives no frame. A
+ /// cancellation of while the container is read is thrown.
///
- public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info)
+ public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(seekable);
MediaContainer? container;
@@ -103,7 +104,7 @@ public sealed class VideoFrameReader : IDisposable
try
{
seekable.Position = 0;
- container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true);
+ container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true, ct);
video = container is null ? null : VideoFrameDecoder.FrameTrack(container);
}
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
@@ -164,6 +165,66 @@ public sealed class VideoFrameReader : IDisposable
return targets;
}
+ ///
+ /// Every picture the video shows, in shown order (edit lists applied): the still-video analysis chooses among them
+ /// (tappa E4). Empty when the video is not available.
+ ///
+ internal IReadOnlyList Shown()
+ {
+ var targets = new VideoFrameTarget[order.Length];
+ for (var i = 0; i < targets.Length; i++)
+ {
+ var at = ShownAt(order[i]);
+ targets[i] = new VideoFrameTarget(i, at, at, order[i]);
+ }
+
+ return targets;
+ }
+
+ ///
+ /// As , but each instant moves to the key sample (a sync sample: a frame decoding can start from)
+ /// shown nearest to it, when one is shown within of it (the earlier of two as near): a frame
+ /// that costs one decoding instead of a run from the key frame before it. Used where any frame near the instant
+ /// does, as the still-video analysis (tappa E4).
+ ///
+ public IReadOnlyList LocateNearKey(IReadOnlyList instants, TimeSpan reach)
+ {
+ ArgumentNullException.ThrowIfNull(instants);
+ var targets = Locate(instants);
+ if (targets.Count == 0 || reach <= TimeSpan.Zero)
+ {
+ return targets;
+ }
+
+ var timescale = (Int128)Math.Max(1, video!.Timescale);
+ var result = new VideoFrameTarget[targets.Count];
+ for (var i = 0; i < targets.Count; i++)
+ {
+ // Shown times compared in track units: the instant and the reach brought to them (rounded down).
+ var at = (Int128)instants[i].Ticks * timescale / TimeSpan.TicksPerSecond;
+ var span = (Int128)reach.Ticks * timescale / TimeSpan.TicksPerSecond;
+ var best = -1;
+ var distance = Int128.MaxValue;
+ foreach (var sample in order)
+ {
+ var gap = Int128.Abs(shown[sample] - at);
+ if (shown[sample] - at > span)
+ {
+ break; // in shown order: every later sample is further
+ }
+
+ if (gap <= span && video.Samples[sample].Key && gap < distance)
+ {
+ (best, distance) = (sample, gap);
+ }
+ }
+
+ result[i] = best < 0 ? targets[i] : new VideoFrameTarget(i, instants[i], ShownAt(best), best);
+ }
+
+ return result;
+ }
+
///
/// 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
diff --git a/src/Febe.Core/Storage/IVideoAnalysisStore.cs b/src/Febe.Core/Storage/IVideoAnalysisStore.cs
index 129ae4d..a8bb317 100644
--- a/src/Febe.Core/Storage/IVideoAnalysisStore.cs
+++ b/src/Febe.Core/Storage/IVideoAnalysisStore.cs
@@ -4,7 +4,8 @@ namespace Febe.Core.Storage;
///
/// Outcomes of «È un video fermo?» by SHA-256 of the video and number of the algorithm (spec §4.10, §8.3
-/// video_analysis). No link to the library: an outcome outlives deletion and re-import of the same file.
+/// video_analysis, columns frame_at_ms and note from migration 0005). No link to the library: an
+/// outcome outlives deletion and re-import of the same file.
///
public interface IVideoAnalysisStore
{
@@ -14,6 +15,11 @@ public interface IVideoAnalysisStore
/// The analysis with the highest algorithm number for each SHA-256 that has one, keyed by lower-case SHA-256.
Task> GetManyAsync(IReadOnlyCollection sha256s, CancellationToken ct = default);
- /// Stores (or replaces) the outcome of one algorithm for one SHA-256.
+ ///
+ /// Stores (or replaces) the outcome of one algorithm for one SHA-256, with the instant of its frame and its note.
+ /// Throws for a still video without an instant (or before the start), an instant on
+ /// another outcome, a note that is not codes separated by spaces, or a «Non analizzabile» without a note. The instant
+ /// is kept in whole milliseconds.
+ ///
Task SetAsync(VideoAnalysis analysis, CancellationToken ct = default);
}
diff --git a/src/Febe.Core/Storage/LibraryQueries.cs b/src/Febe.Core/Storage/LibraryQueries.cs
index f78171e..31737aa 100644
--- a/src/Febe.Core/Storage/LibraryQueries.cs
+++ b/src/Febe.Core/Storage/LibraryQueries.cs
@@ -28,6 +28,14 @@ public enum LibraryKindFilter
/// Posts of any media (the «Post» tab of an account).
Posts,
+
+ ///
+ /// «Video fermi» (tappa E4, answer 40 of Alberto, 29 November 2026; in the library only, not in the account tabs):
+ /// posts, stories, highlights and tagged posts with at least one video in the library whose latest analysis
+ /// (the highest algorithm in video_analysis) says «Fermo». A video never analysed is not in it: analysis is on
+ /// request only. In «Tutte le foto» only those videos.
+ ///
+ StillVideos,
}
///
diff --git a/src/Febe.Data/Migrations/0005_video_fermi.sql b/src/Febe.Data/Migrations/0005_video_fermi.sql
new file mode 100644
index 0000000..28b0b45
--- /dev/null
+++ b/src/Febe.Data/Migrations/0005_video_fermi.sql
@@ -0,0 +1,27 @@
+-- Febe, schema version 5: «Video fermi» (tappa E4 of 0.3.0, issue #58; spec §4.10, §8.3).
+-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner.
+-- Two columns and one index on video_analysis: no other table, column or index changes, and no data of another table.
+
+-- No version of Febe before tappa E4 wrote video_analysis, so the table is empty here. SQLite tests the CHECKs of a new
+-- column against the rows already there: should a row be there anyway (written by hand), a «Fermo» without the instant
+-- of its frame or a «Non analizzabile» without its reason cannot be kept, and it would stop the migration. Such a row
+-- goes, and «È un video fermo?» analyses that video again when asked; an «In movimento» stays as it is.
+DELETE FROM video_analysis WHERE outcome <> 'Moving';
+
+-- The instant of the frame «Salva il fotogramma» saves, in milliseconds of shown time (as export_copy.frame_at_ms):
+-- the sharpest frame the analysis looked at, never a dark one of a fade (answer 45 of Alberto, 29 November 2026).
+-- Set for a «Fermo» outcome and only for it.
+ALTER TABLE video_analysis ADD COLUMN frame_at_ms INTEGER
+ CHECK (frame_at_ms IS NULL OR frame_at_ms >= 0)
+ CHECK ((outcome = 'Still') = (frame_at_ms IS NOT NULL));
+
+-- Why the outcome is what it is: English codes separated by spaces, like export_item.note (FrameNotAvailable,
+-- DurationUnknown, Unreadable, TooSlow, AllDark, SingleColor). Always set for «Non analizzabile», so the viewer can
+-- say why; a video all black or all of one colour is «Non analizzabile» (answer 42 of Alberto, 29 November 2026).
+ALTER TABLE video_analysis ADD COLUMN note TEXT
+ CHECK (note IS NULL OR length(note) > 0)
+ CHECK (outcome <> 'NotAnalyzable' OR note IS NOT NULL);
+
+-- The «Video fermi» filter of the library reads the still outcomes and joins them to the files by SHA-256
+-- (ix_media_sha256_entry, migration 0004); the primary key (sha256, algorithm) is in the index too.
+CREATE INDEX ix_video_analysis_still ON video_analysis (sha256) WHERE outcome = 'Still';
diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs
index 76e92f9..51c3972 100644
--- a/src/Febe.Data/Stores/EntryStore.cs
+++ b/src/Febe.Data/Stores/EntryStore.cs
@@ -527,6 +527,10 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{
LibraryKindFilter.Photos => " AND m.kind = 'Photo'",
LibraryKindFilter.Videos => " AND m.kind = 'Video'",
+ // Over every file (bulk) SQLite goes from the still SHA-256 to their files on ix_media_sha256; for the files
+ // of a few entries the unary + keeps it on the key of the entry: on the SHA-256 index each entry would walk
+ // every still video (in a correlated count, 20 ms per entry with 10,000 of them).
+ LibraryKindFilter.StillVideos => $" AND m.kind = 'Video' AND {(bulk ? string.Empty : "+")}m.sha256 IN ({StillShas})",
_ => string.Empty,
} + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies, bulk) : string.Empty);
@@ -562,8 +566,38 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
/// the files already decides (a post without videos adds 0) and the EXISTS per post of the grouped filter would cost
/// a second over 200,000 entries.
///
- private static LibraryFilter EntriesOfFiles(LibraryFilter filter) =>
- filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter;
+ private static LibraryFilter EntriesOfFiles(LibraryFilter filter) => filter.Kind switch
+ {
+ LibraryKindFilter.Photos or LibraryKindFilter.Videos => filter with { Kind = LibraryKindFilter.Posts },
+ // «Video fermi» is of every kind of entry of «Tutto»: an entry without still videos adds 0 the same way.
+ LibraryKindFilter.StillVideos => filter with { Kind = LibraryKindFilter.All },
+ _ => filter,
+ };
+
+ ///
+ /// «Video fermi»: the SHA-256 of the videos whose latest analysis (the highest algorithm, D4 of tappa E4) says
+ /// «Fermo», read once on ix_video_analysis_still; an «In movimento» of a newer algorithm takes the video out. The
+ /// primary key (sha256, algorithm) answers the NOT EXISTS of each.
+ ///
+ private const string StillShas =
+ "SELECT vs.sha256 FROM video_analysis vs WHERE vs.outcome = 'Still' "
+ + "AND NOT EXISTS (SELECT 1 FROM video_analysis vn WHERE vn.sha256 = vs.sha256 AND vn.algorithm > vs.algorithm)";
+
+ ///
+ /// «Video fermi» on entry e: the entries with a still video in the library, one list read once per statement,
+ /// then each entry of the publication index tested by key against it. Analysis is on request, so the still videos
+ /// are few and the list is short; an EXISTS per entry would walk the whole index (each entry a lookup of its files and
+ /// their table rows, over a second) whenever the filter matches few entries.
+ /// The list goes from the still outcomes (ix_video_analysis_still) to their files (ix_media_sha256_entry) and checks
+ /// that the file is a video in the library on ix_media_entry_files, all on covering indexes: 44 ms for 10,000 still
+ /// videos, 55 ms reading the table row of each file. CROSS JOIN keeps that order (started from the files, SQLite
+ /// scans all of them on ix_media_state, 90 ms); the unary + on the key keeps the check on the covering index.
+ ///
+ private const string StillVideoEntries =
+ "SELECT ms.entry_id FROM video_analysis vs CROSS JOIN media ms ON ms.sha256 = vs.sha256 WHERE vs.outcome = 'Still' "
+ + "AND NOT EXISTS (SELECT 1 FROM video_analysis vn WHERE vn.sha256 = vs.sha256 AND vn.algorithm > vs.algorithm) "
+ + "AND EXISTS (SELECT 1 FROM media mf WHERE mf.entry_id = ms.entry_id AND mf.state IN ('Downloaded', 'Imported') "
+ + "AND mf.kind = 'Video' AND +mf.id = ms.id)";
/// A correlated count of the files of «Tutte le foto» of the entry e.
private static string FilesOfEntry(SqliteConnection c, LibraryFilter filter) =>
@@ -884,6 +918,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))",
LibraryKindFilter.Tagged => "e.kind = 'Tagged'",
LibraryKindFilter.ProfilePictures => "e.kind = 'ProfilePicture'",
+ // The unary + on the key, as for the list of «Foto» and «Video»: the entries stay in the order of the
+ // publication index (a window stops after its first rows), each tested against the list on its key.
+ LibraryKindFilter.StillVideos => $"+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged') AND +e.id IN ({StillVideoEntries})",
_ => throw new ArgumentOutOfRangeException(nameof(filter), filter.Kind, null),
});
diff --git a/src/Febe.Data/Stores/VideoAnalysisStore.cs b/src/Febe.Data/Stores/VideoAnalysisStore.cs
index f0d2858..5166c6d 100644
--- a/src/Febe.Data/Stores/VideoAnalysisStore.cs
+++ b/src/Febe.Data/Stores/VideoAnalysisStore.cs
@@ -8,8 +8,10 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore
{
private const int KeysPerQuery = 500;
+ private const string Columns = "sha256, algorithm, outcome, analyzed_at, frame_at_ms, note";
+
private static VideoAnalysis Read(SqliteDataReader r) =>
- new(r.GetString(0), r.GetInt32(1), r.GetEnum(2), r.GetTime(3));
+ new(r.GetString(0), r.GetInt32(1), r.GetEnum(2), r.GetTime(3), r.GetDurationOrNull(4), r.GetTextOrNull(5));
public Task GetAsync(string sha256, CancellationToken ct = default)
{
@@ -17,8 +19,8 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore
return db.ReadAsync(
c =>
{
- using var r = c.Command("""
- SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 = @h ORDER BY algorithm DESC LIMIT 1
+ using var r = c.Command($"""
+ SELECT {Columns} FROM video_analysis WHERE sha256 = @h ORDER BY algorithm DESC LIMIT 1
""").With("@h", sha).ExecuteReader();
return r.Read() ? Read(r) : null;
},
@@ -36,7 +38,7 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore
foreach (var chunk in keys.Chunk(KeysPerQuery))
{
using var command = c.Command(string.Empty);
- command.CommandText = $"SELECT sha256, algorithm, outcome, analyzed_at FROM video_analysis WHERE sha256 IN ({command.AddList("h", chunk)})";
+ command.CommandText = $"SELECT {Columns} FROM video_analysis WHERE sha256 IN ({command.AddList("h", chunk)})";
using var r = command.ExecuteReader();
while (r.Read())
{
@@ -58,12 +60,55 @@ internal sealed class VideoAnalysisStore(FebeDatabase db) : IVideoAnalysisStore
ArgumentNullException.ThrowIfNull(analysis);
var sha = ExportValues.Sha(analysis.Sha256, nameof(analysis));
ArgumentOutOfRangeException.ThrowIfLessThan(analysis.Algorithm, 1, nameof(analysis));
+ ValidateFrame(analysis.Outcome, analysis.FrameAt, nameof(analysis));
+ var note = Note(analysis.Outcome, analysis.Note, nameof(analysis));
return db.WriteAsync(
w => w.Command("""
- INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at) VALUES (@h, @alg, @o, @at)
- ON CONFLICT (sha256, algorithm) DO UPDATE SET outcome = excluded.outcome, analyzed_at = excluded.analyzed_at
+ INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note) VALUES (@h, @alg, @o, @at, @fr, @n)
+ ON CONFLICT (sha256, algorithm) DO UPDATE SET
+ outcome = excluded.outcome, analyzed_at = excluded.analyzed_at, frame_at_ms = excluded.frame_at_ms, note = excluded.note
""").With("@h", sha).With("@alg", (long)analysis.Algorithm).With("@o", Sql.Enum(analysis.Outcome)).With("@at", Sql.Time(analysis.AnalyzedAt))
+ .With("@fr", Sql.Duration(analysis.FrameAt)).With("@n", (object?)note ?? DBNull.Value)
.ExecuteNonQuery(),
ct);
}
+
+ /// A still video has the instant of its frame, at or after the start; no other outcome has one.
+ private static void ValidateFrame(VideoAnalysisOutcome outcome, TimeSpan? frameAt, string name)
+ {
+ if (outcome == VideoAnalysisOutcome.Still)
+ {
+ if (frameAt is not { } f || f < TimeSpan.Zero)
+ {
+ throw new ArgumentException("Un video fermo ha l'istante del suo fotogramma, dall'inizio in poi.", name);
+ }
+ }
+ else if (frameAt is not null)
+ {
+ throw new ArgumentException("Solo un video fermo ha l'istante di un fotogramma.", name);
+ }
+ }
+
+ ///
+ /// The note as stored: codes of ASCII letters and digits starting upper case (a «Code:Arg» too) separated by single
+ /// spaces, null for none. Never free text, so no path or message can end up in it; «Non analizzabile» always says why.
+ ///
+ private static string? Note(VideoAnalysisOutcome outcome, string? note, string name)
+ {
+ var codes = (note ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
+ foreach (var code in codes)
+ {
+ if (!char.IsAsciiLetterUpper(code[0]) || !code.All(c => char.IsAsciiLetterOrDigit(c) || c == ':'))
+ {
+ throw new ArgumentException("La nota di un'analisi è fatta di codici separati da spazi.", name);
+ }
+ }
+
+ if (codes.Length == 0 && outcome == VideoAnalysisOutcome.NotAnalyzable)
+ {
+ throw new ArgumentException("Un video non analizzabile dice perché nella nota.", name);
+ }
+
+ return codes.Length == 0 ? null : string.Join(' ', codes);
+ }
}
diff --git a/src/Febe.Web/Api/ApiMapping.cs b/src/Febe.Web/Api/ApiMapping.cs
index 854375b..25df9d8 100644
--- a/src/Febe.Web/Api/ApiMapping.cs
+++ b/src/Febe.Web/Api/ApiMapping.cs
@@ -172,7 +172,7 @@ public static class ApiMapping
///
/// The library filter from the query string: kind (all, photos, videos, stories, highlights, tagged, posts,
- /// profile), accounts (comma-separated keys), from/to (local days, inclusive),
+ /// profile, stillvideos), accounts (comma-separated keys), from/to (local days, inclusive),
/// provenance (downloaded, imported), q (account name or caption).
///
public static LibraryFilter Filter(IQueryCollection query, TimeZoneInfo zone)
@@ -189,6 +189,7 @@ public static class ApiMapping
"tagged" => LibraryKindFilter.Tagged,
"posts" => LibraryKindFilter.Posts,
"profile" => LibraryKindFilter.ProfilePictures,
+ "stillvideos" => LibraryKindFilter.StillVideos,
_ => throw new BadRequestException("Tipo di contenuto sconosciuto."),
};
diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs
index 301d2bf..37368e1 100644
--- a/src/Febe.Web/Api/Dtos.cs
+++ b/src/Febe.Web/Api/Dtos.cs
@@ -94,7 +94,8 @@ public sealed record MediaDto(
bool Damaged = false,
IReadOnlyList? Copies = null,
bool? FramesAvailable = null,
- IReadOnlyList? Conversions = null);
+ IReadOnlyList? Conversions = null,
+ StillVideoDto? Still = null);
/// Everything the viewer shows of an entry.
public sealed record EntryDto(
diff --git a/src/Febe.Web/Api/EngineApi.cs b/src/Febe.Web/Api/EngineApi.cs
index 89eab65..efe7eaa 100644
--- a/src/Febe.Web/Api/EngineApi.cs
+++ b/src/Febe.Web/Api/EngineApi.cs
@@ -131,8 +131,8 @@ public static class EngineApi
///
/// /api/eventi: server-sent events. motore carries the engine (at once, at every change, at least every
- /// minute); libreria says the library changed (at most every second and a half); a comment line keeps the
- /// stream open. Never contains captions, bodies or addresses.
+ /// minute); libreria says the library changed (at most every second and a half, one event for each reason
+ /// there was); a comment line keeps the stream open. Never contains captions, bodies or addresses.
///
public static async Task StreamAsync(
HttpContext context,
@@ -151,6 +151,7 @@ public static class EngineApi
var ct = context.RequestAborted;
var signals = Channel.CreateBounded(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest });
+ var changes = new PendingLibraryChanges();
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
var engineTask = Task.Run(
async () =>
@@ -166,7 +167,8 @@ public static class EngineApi
{
await foreach (var change in library.SubscribeAsync(stop.Token).ConfigureAwait(false))
{
- signals.Writer.TryWrite("libreria:" + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange));
+ changes.Add(change);
+ signals.Writer.TryWrite("libreria");
}
},
CancellationToken.None);
@@ -178,7 +180,6 @@ public static class EngineApi
var libraryGap = TimeSpan.FromMilliseconds(1500);
var lastEngine = DateTimeOffset.UtcNow;
var lastLibrary = DateTimeOffset.MinValue;
- string? pendingLibrary = null;
var enginePending = false;
while (!ct.IsCancellationRequested)
@@ -190,7 +191,7 @@ public static class EngineApi
wait = lastEngine + Refresh - now;
}
- if (pendingLibrary is not null && lastLibrary + libraryGap - now < wait)
+ if (changes.Any && lastLibrary + libraryGap - now < wait)
{
wait = lastLibrary + libraryGap - now;
}
@@ -202,14 +203,7 @@ public static class EngineApi
await Task.Delay(TimeSpan.FromMilliseconds(300), ct).ConfigureAwait(false);
while (signals.Reader.TryRead(out var signal))
{
- if (signal == "motore")
- {
- enginePending = true;
- }
- else
- {
- pendingLibrary = signal["libreria:".Length..];
- }
+ enginePending |= signal == "motore";
}
}
@@ -223,10 +217,13 @@ public static class EngineApi
sent = true;
}
- if (pendingLibrary is not null && now - lastLibrary >= libraryGap)
+ if (changes.Any && now - lastLibrary >= libraryGap)
{
- await WriteAsync(response, "event: libreria\ndata: " + pendingLibrary + "\n\n", ct).ConfigureAwait(false);
- pendingLibrary = null;
+ foreach (var change in changes.Take())
+ {
+ await WriteAsync(response, "event: libreria\ndata: " + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange) + "\n\n", ct).ConfigureAwait(false);
+ }
+
lastLibrary = now;
sent = true;
}
diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs
index c1c4f83..ae3047b 100644
--- a/src/Febe.Web/Api/ExportApi.cs
+++ b/src/Febe.Web/Api/ExportApi.cs
@@ -3,6 +3,7 @@ using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
+using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Web.Export;
using Febe.Web.Library;
@@ -309,7 +310,8 @@ public static class ExportApi
.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 exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt);
+ var still = copy.Variant == ExportVariant.Frame && sha == copy.SourceSha256 && ExportFrames.IsSingleName(copy.RelativePath);
+ var exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt, still);
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);
});
@@ -582,7 +584,8 @@ public static class ExportApi
plan.PhotosSkipped,
plan.Frames,
plan.OverCap,
- PlanSummary(plan, frames));
+ PlanSummary(plan, frames),
+ plan.NotStill);
}
///
@@ -605,6 +608,11 @@ public static class ExportApi
{
parts.Add(ExportFrames.OverCapMessage);
}
+
+ if (plan.NotStill > 0)
+ {
+ parts.Add(StillVideoText.NotStill);
+ }
}
else
{
@@ -764,8 +772,15 @@ public static class ExportApi
"istante" or "at" => FrameMode.At,
"ogni" or "every" => FrameMode.Every,
"numero" or "count" => FrameMode.Count,
+ "fermo" or "still" => FrameMode.Still,
_ => throw new BadRequestException("Modo dei fotogrammi sconosciuto: «Questo istante», «Uno ogni k secondi» o «N in tutto»."),
};
+ if (mode == FrameMode.Still && (body.AtMs is not null || body.EveryMs is not null || body.Count is not null))
+ {
+ // The instant is the analysis' own (tappa E4): one asked by the page would be another frame.
+ throw new BadRequestException("«Salva il fotogramma» prende il fotogramma scelto dall'analisi: niente istante, intervallo o numero.");
+ }
+
return new ExportFramesRequest(
mode,
mode == FrameMode.At ? TimeSpan.FromMilliseconds(Math.Max(0, body.AtMs ?? 0)) : null,
@@ -1029,7 +1044,9 @@ public static class ExportApi
[.. start.Runs.Select(r => r.Id)],
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."
+ ? start.Plan.NotStill > 0 && start.Plan.Files == 0
+ ? StillVideoText.NotStill + ": niente da copiare."
+ : "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.");
private static ExportRunDto Run(ExportRun run, ExportRunSummary summary, IReadOnlyDictionary labels, IClock clock, bool running)
diff --git a/src/Febe.Web/Api/ExportDtos.cs b/src/Febe.Web/Api/ExportDtos.cs
index 75c2119..6571d9e 100644
--- a/src/Febe.Web/Api/ExportDtos.cs
+++ b/src/Febe.Web/Api/ExportDtos.cs
@@ -158,7 +158,8 @@ public sealed record CopyJobRequestDto(
///
/// 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.
+/// 1.000), or fermo («Salva il fotogramma» of one still video, tappa E4: the instant of its analysis, nothing
+/// else); jpg, png (the default) or webplossless.
///
public sealed record FramesRequestDto(string? Mode, long? AtMs = null, long? EveryMs = null, int? Count = null, string? Format = null);
@@ -186,7 +187,8 @@ public sealed record ExportPlanDestinationDto(
/// 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»).
+/// circa 3 HEIC copiati come sono · circa 4,2 GB · con perdita»). Tappa E4, «Salva il fotogramma»:
+/// videos that are not «Fermo» or were never analysed (skipped).
///
public sealed record ExportPlanDto(
int Files,
@@ -204,7 +206,8 @@ public sealed record ExportPlanDto(
int PhotosSkipped = 0,
int Frames = 0,
int OverCap = 0,
- string? Summary = null);
+ string? Summary = null,
+ int NotStill = 0);
/// 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);
@@ -356,3 +359,53 @@ public sealed record ConversionActionRequest(long ConversionId);
/// 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);
+
+// ---------------------------------------------------------------------------------------------- still videos (tappa E4)
+
+///
+/// The analysis of a video («È un video fermo?», spec §4.10, tappa E4), on and as the answer
+/// of POST /api/media/{id}/still; a video never analysed has none. : still,
+/// moving or notAnalyzable; : made by the algorithm of this Febe (otherwise
+/// «Analizza di nuovo»); and («0:01,125»): the frame
+/// «Salva il fotogramma» saves, only on still; : English codes separated by spaces
+/// (FrameNotAvailable, DurationUnknown, Unreadable, TooSlow, AllDark,
+/// SingleColor, SmallMotion); : the local day of the analysis (yyyy-MM-dd).
+///
+public sealed record StillVideoDto(string Outcome, bool Current, long? FrameAtMs, string? FrameLabel, string? Note, string Day);
+
+///
+/// The selection of «Cerca i video fermi»: exactly one of ,
+/// (every video of those entries), with , or .
+///
+public sealed record StillVideosSelectionRequest(IReadOnlyList? MediaIds, IReadOnlyList? EntryIds, string? Query, string? Mode, long? AccountId = null);
+
+///
+/// POST /api/still-videos/plan: the confirmation of «Cerca i video fermi», by file (two entries of one video count
+/// once). = + (skipped) +
+/// (not in the library); : photos of the selection;
+/// : «28 video da analizzare · 12 già analizzati · le 5 foto si saltano»;
+/// : why the job would wait now (an engine session, an import, copies or a rebuild), or null.
+///
+public sealed record StillVideosPlanDto(int Videos, int ToAnalyse, int AlreadyAnalysed, int PhotosSkipped, int Missing, string Summary, string? Waiting);
+
+///
+/// The job «Cerca i video fermi» (GET /api/still-videos/progress, and the answer of start and stop):
+/// of settled as , ,
+/// or (file gone or changed); :
+/// ended by «Interrompi»; : why it waits now; : the file analysed
+/// now; : «Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile»;
+/// : in the answer of start, the videos it added to the job (0 when all were queued already).
+///
+public sealed record StillVideosProgressDto(
+ bool Running,
+ int Total,
+ int Done,
+ int Still,
+ int Moving,
+ int NotAnalyzable,
+ int Skipped,
+ bool Stopped,
+ string? Waiting,
+ long? CurrentMediaId,
+ string Summary,
+ int Added);
diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs
index 8049afc..6ee50f6 100644
--- a/src/Febe.Web/Api/FebeJsonContext.cs
+++ b/src/Febe.Web/Api/FebeJsonContext.cs
@@ -115,4 +115,8 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(FramesTokenDto))]
[JsonSerializable(typeof(ConversionActionRequest))]
[JsonSerializable(typeof(EntryDeletionPreviewDto))]
+[JsonSerializable(typeof(StillVideoDto))]
+[JsonSerializable(typeof(StillVideosSelectionRequest))]
+[JsonSerializable(typeof(StillVideosPlanDto))]
+[JsonSerializable(typeof(StillVideosProgressDto))]
public sealed partial class FebeJsonContext : JsonSerializerContext;
diff --git a/src/Febe.Web/Api/FramesApi.cs b/src/Febe.Web/Api/FramesApi.cs
index ccd47aa..6ccfa50 100644
--- a/src/Febe.Web/Api/FramesApi.cs
+++ b/src/Febe.Web/Api/FramesApi.cs
@@ -4,6 +4,7 @@ using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
+using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Web.Export;
using Febe.Web.Library;
@@ -63,6 +64,11 @@ public static class FramesApi
{
var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
var request = ExportApi.Frames(new FramesRequestDto(mode ?? "numero", at, every, count, "png"));
+ if (request.Mode == FrameMode.Still)
+ {
+ throw new BadRequestException(StillVideoText.FromViewerOnly);
+ }
+
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;
@@ -231,6 +237,12 @@ public static class FramesApi
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.");
+ if (request.Mode == FrameMode.Still)
+ {
+ // «Scarica» of «Salva il fotogramma» is /api/media/{id}/still/frame (StillVideosApi).
+ throw new BadRequestException(StillVideoText.FromViewerOnly);
+ }
+
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);
@@ -387,10 +399,10 @@ public static class FramesApi
// ---------------------------------------------------------------------------------------------- helpers
- private sealed record VideoFile(Account Account, Media Media, string Path);
+ internal 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)
+ internal 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)
@@ -404,7 +416,7 @@ public static class FramesApi
return new VideoFile(account, media, path);
}
- private static string Stem(Media media) =>
+ internal 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.
diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs
index 30afcda..5d1dde3 100644
--- a/src/Febe.Web/Api/LibraryApi.cs
+++ b/src/Febe.Web/Api/LibraryApi.cs
@@ -274,6 +274,9 @@ public static class LibraryApi
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);
+ // «È un video fermo?» (tappa E4): the analyses of the entry's videos, in one read, by SHA-256 of the file.
+ var videoShas = stored.Media.Where(m => m.Kind == MediaKind.Video && m.Sha256 is { Length: 64 }).Select(m => m.Sha256!.ToLowerInvariant()).Distinct(StringComparer.Ordinal).ToList();
+ var analyses = videoShas.Count == 0 ? null : await storage.VideoAnalyses.GetManyAsync(videoShas, ct).ConfigureAwait(false);
var media = new List(stored.Media.Count);
foreach (var m in stored.Media)
{
@@ -303,7 +306,10 @@ public static class LibraryApi
damaged,
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))));
+ conversions is null ? null : FramesApi.Conversions(conversions, account, converted.Where(c => c.MediaId == m.Id)),
+ m.Kind == MediaKind.Video && m.Sha256 is { Length: 64 } sha && analyses is not null && analyses.TryGetValue(sha.ToLowerInvariant(), out var analysis)
+ ? StillVideosApi.Dto(analysis, clock)
+ : null));
}
return new EntryDto(
diff --git a/src/Febe.Web/Api/StillVideosApi.cs b/src/Febe.Web/Api/StillVideosApi.cs
new file mode 100644
index 0000000..50cf2fd
--- /dev/null
+++ b/src/Febe.Web/Api/StillVideosApi.cs
@@ -0,0 +1,143 @@
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Core.Library.StillVideos;
+using Febe.Core.Storage;
+using Febe.Web.Export;
+using Febe.Web.Library;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+
+namespace Febe.Web.Api;
+
+///
+/// Still videos (spec §4.10, tappa E4), only on request, never in the background: «È un video fermo?» of one video
+/// from the viewer (also during an engine session, within 30 s, answer 43), the frame of «Salva il fotogramma» for
+/// «Scarica» (…_fotogramma.png, the sharpest frame the analysis looked at, answer 45), and the job «Cerca i video
+/// fermi» of a selection with its confirmation, progress and «Interrompi» (answer 41). «Salva il fotogramma» to the
+/// folder of the copies goes through /api/export/plan and /start with frames: { mode: "fermo" }.
+/// Every command passes the Origin check of the security middleware like any other. Nothing here writes a file.
+///
+public static class StillVideosApi
+{
+ public static void Map(IEndpointRouteBuilder endpoints)
+ {
+ ArgumentNullException.ThrowIfNull(endpoints);
+
+ endpoints.MapPost("/api/media/{id:long}/still", async (long id, StillVideoService stills, IClock clock, CancellationToken ct) =>
+ {
+ var answer = await stills.AnalyseNowAsync(id, ct).ConfigureAwait(false);
+ return answer.Kind switch
+ {
+ StillVideoAnswerKind.Analysed => ApiHttp.Json(Dto(answer.Analysis!, clock), FebeJsonContext.Default.StillVideoDto),
+ StillVideoAnswerKind.NotAVideo => throw new BadRequestException(answer.Message!),
+ StillVideoAnswerKind.SourceChanged => throw new ApiStatusException(409, answer.Message!),
+ StillVideoAnswerKind.TooSlow or StillVideoAnswerKind.TooSlowKept => throw new ApiStatusException(503, answer.Message!),
+ _ => throw new NotFoundException(answer.Message ?? StillVideoText.NotFound),
+ };
+ });
+
+ endpoints.MapGet("/api/media/{id:long}/still/frame", async (long id, string? format, int? max, string? download, HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
+ {
+ var video = await FramesApi.VideoAsync(storage, files, id, ct).ConfigureAwait(false);
+ var analysis = video.Media.Sha256 is { Length: 64 } sha ? await storage.VideoAnalyses.GetAsync(sha.ToLowerInvariant(), ct).ConfigureAwait(false) : null;
+ if (analysis is not { Outcome: VideoAnalysisOutcome.Still, FrameAt: { } at })
+ {
+ throw new ApiStatusException(409, StillVideoText.NotStill + ".");
+ }
+
+ 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 frame = await frames.FrameAsync(video.Path, video.Media.Sha256, at, chosen, side, ct).ConfigureAwait(false);
+
+ // A new analysis can choose another frame at the same address: never kept by the browser.
+ context.Response.Headers.CacheControl = "private, no-cache";
+ if (download is "1" or "true")
+ {
+ var name = FrameService.FileName(FramesApi.Stem(video.Media), FrameMode.Still, frame.Actual, 0, 1, chosen);
+ return Results.File(frame.Data, frame.ContentType, name);
+ }
+
+ return Results.File(frame.Data, frame.ContentType);
+ });
+
+ endpoints.MapPost("/api/still-videos/plan", async (HttpContext context, StillVideoService stills, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.StillVideosSelectionRequest).ConfigureAwait(false);
+ var selection = Selection(body, clock);
+ var plan = await ExportApi.GuardAsync(() => stills.PlanAsync(selection, ct)).ConfigureAwait(false);
+ return ApiHttp.Json(
+ new StillVideosPlanDto(plan.Videos, plan.ToAnalyse, plan.AlreadyAnalysed, plan.PhotosSkipped, plan.Missing, StillVideoText.PlanSummary(plan), Waiting(gate, session)),
+ FebeJsonContext.Default.StillVideosPlanDto);
+ });
+
+ endpoints.MapPost("/api/still-videos/start", async (HttpContext context, StillVideoService stills, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.StillVideosSelectionRequest).ConfigureAwait(false);
+ var selection = Selection(body, clock);
+ var progress = await ExportApi.GuardAsync(() => stills.StartAsync(selection, ct)).ConfigureAwait(false);
+ return ApiHttp.Json(Progress(progress), FebeJsonContext.Default.StillVideosProgressDto);
+ });
+
+ endpoints.MapGet("/api/still-videos/progress", (StillVideoService stills) =>
+ ApiHttp.Json(Progress(stills.Progress), FebeJsonContext.Default.StillVideosProgressDto));
+
+ endpoints.MapPost("/api/still-videos/stop", (StillVideoService stills) =>
+ ApiHttp.Json(Progress(stills.Stop()), FebeJsonContext.Default.StillVideosProgressDto));
+ }
+
+ /// The analysis of a video as the viewer shows it.
+ public static StillVideoDto Dto(VideoAnalysis analysis, IClock clock)
+ {
+ ArgumentNullException.ThrowIfNull(analysis);
+ ArgumentNullException.ThrowIfNull(clock);
+ var still = analysis.Outcome == VideoAnalysisOutcome.Still ? analysis.FrameAt : null;
+ return new StillVideoDto(
+ Outcome(analysis.Outcome),
+ analysis.Algorithm >= StillVideoAnalyzer.Algorithm,
+ still is { } at ? ExportFrames.ActualMs(at) : null,
+ still is { } shown ? ExportFrames.Label(shown) : null,
+ analysis.Note,
+ ApiMapping.Day(DateOnly.FromDateTime(LocalCalendar.ToLocal(analysis.AnalyzedAt, clock.LocalZone))));
+ }
+
+ /// The wire name of an outcome: still, moving, notAnalyzable.
+ public static string Outcome(VideoAnalysisOutcome outcome) => outcome switch
+ {
+ VideoAnalysisOutcome.Still => "still",
+ VideoAnalysisOutcome.Moving => "moving",
+ _ => "notAnalyzable",
+ };
+
+ private static StillVideosProgressDto Progress(StillVideoProgress p) => new(
+ p.Running,
+ p.Total,
+ p.Done,
+ p.Still,
+ p.Moving,
+ p.NotAnalyzable,
+ p.Skipped,
+ p.Stopped,
+ p.Waiting,
+ p.CurrentMediaId,
+ StillVideoText.Summary(p),
+ p.Added);
+
+ /// Exactly one selection, as «Copia in…» and «Fotogrammi…» take it.
+ private static ExportSelection Selection(StillVideosSelectionRequest body, IClock clock)
+ {
+ var chosen = (body.MediaIds is { Count: > 0 } ? 1 : 0) + (body.EntryIds is { Count: > 0 } ? 1 : 0) + (body.Query is not null ? 1 : 0) + (body.AccountId is not null ? 1 : 0);
+ if (chosen != 1)
+ {
+ throw new BadRequestException(StillVideoText.NoSelection);
+ }
+
+ return ExportApi.Request(new CopyJobRequestDto(body.MediaIds, body.EntryIds, body.Query, body.Mode, body.AccountId), clock).Selection;
+ }
+
+ /// Why the job would wait now (the dialog says it), or null.
+ private static string? Waiting(LongWorkGate gate, IEngineSessionState session) =>
+ session.InSession ? StillVideoText.InSession : gate.Busy is not null ? StillVideoText.LongWork : null;
+}
diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs
index 1bb9b53..05301f2 100644
--- a/src/Febe.Web/Demo/DemoEngine.cs
+++ b/src/Febe.Web/Demo/DemoEngine.cs
@@ -390,7 +390,10 @@ 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, and one short video for every video (tappa E3).
+///
+/// Files of the demo: the shared sample pictures, the still videos by their SHA-256 (tappa E4), and one short moving
+/// video for every other video (tappa E3).
+///
public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
{
public string? Resolve(Account account, Media media)
@@ -399,6 +402,7 @@ public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
return media.Kind switch
{
MediaKind.Photo => media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null,
+ MediaKind.Video when media.Sha256 is { } sha && world.StillVideoFiles.TryGetValue(sha, out var still) => File.Exists(still) ? still : null,
MediaKind.Video => world.VideoFile is { } video && File.Exists(video) ? video : null,
_ => null,
};
diff --git a/src/Febe.Web/Demo/DemoHost.cs b/src/Febe.Web/Demo/DemoHost.cs
index 16cafe7..ca6249b 100644
--- a/src/Febe.Web/Demo/DemoHost.cs
+++ b/src/Febe.Web/Demo/DemoHost.cs
@@ -3,6 +3,7 @@ using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
+using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Web.Connection;
@@ -73,6 +74,7 @@ public sealed class DemoHost : IAsyncDisposable
var world = await DemoSeeder.SeedAsync(database, data, layout, clock, ct).ConfigureAwait(false);
import = await DemoImport.PrepareAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false);
await DemoExport.SeedAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false);
+ await DemoStillVideos.SeedAsync(database, world, data, clock, ct).ConfigureAwait(false);
var exportRoot = DemoExport.Root(root);
var demoImport = import;
var library = new FebeLibrary(database, data, layout, clock);
@@ -136,6 +138,11 @@ public sealed class DemoHost : IAsyncDisposable
try
{
await App.StopAsync().ConfigureAwait(false);
+
+ // «Cerca i video fermi» at work gives its video up and ends before the database closes, as in Febe itself.
+ var stills = App.Services.GetRequiredService();
+ stills.Dispose();
+ await stills.Job.ConfigureAwait(false);
}
finally
{
diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs
index 4615f41..350ce00 100644
--- a/src/Febe.Web/Demo/DemoSeeder.cs
+++ b/src/Febe.Web/Demo/DemoSeeder.cs
@@ -68,11 +68,18 @@ public sealed class DemoWorld
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).
+ /// The demo's one moving video file (H.264, 2 s, tappa E3), served for every video of the demo that is not in
+ /// , 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 still videos of the demo (tappa E4), by SHA-256: each is its cover picture alone for two seconds, and its
+ /// videos are recorded with that file's own SHA-256 (written by ).
+ ///
+ public ConcurrentDictionary StillVideoFiles { get; } = new(StringComparer.Ordinal);
+
/// The files of the seeded conversions of the library, by row id (written by ).
public ConcurrentDictionary ConversionFiles { get; } = new();
}
diff --git a/src/Febe.Web/Demo/DemoStillVideos.cs b/src/Febe.Web/Demo/DemoStillVideos.cs
new file mode 100644
index 0000000..8de63ea
--- /dev/null
+++ b/src/Febe.Web/Demo/DemoStillVideos.cs
@@ -0,0 +1,183 @@
+using System.Security.Cryptography;
+using Febe.Core.Abstractions;
+using Febe.Core.Codecs.H264;
+using Febe.Core.Codecs.Images;
+using Febe.Core.Domain;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+using Febe.Data;
+
+namespace Febe.Web.Demo;
+
+///
+/// The still videos of the demo (spec §4.10 «Video fermi», tappa E4): two videos (the newest of @marta.demo on a picture
+/// no copy uses, and the newest such story video of another account, on another picture: which ones depends on the day and
+/// the hour, they can be stories or months old) become their cover picture alone for two seconds, each in its own file
+/// recorded with its own SHA-256 (so «Salva il fotogramma» works both with «Scarica» and «Nella cartella delle copie»),
+/// with a «Fermo» analysis that the real analyser gave on that file. The next two videos of @marta.demo chosen the same way
+/// have an «In movimento» analysis (of the demo's moving file) and a «Non analizzabile» because it took too long («Analizza
+/// di nuovo»); other videos on the same pictures have the same outcome. The rest is never analysed, so «È un video fermo?»
+/// and «Cerca i video fermi» work live. Analyses are only on request in Febe: these rows stand for requests made in the days
+/// before. Every scene of the demo sees them.
+///
+public static class DemoStillVideos
+{
+ /// The account whose newest video on a picture without copies is still (the next two are «In movimento» and «Non analizzabile»).
+ public const string StillAccount = DemoExport.CopiedAccount;
+
+ /// The file name of the still video of position (1 or 2).
+ public static string FileName(int n) => $"video-fermo-dimostrativo-{n}.mp4";
+
+ /// Writes the files, records them and seeds the analyses. Without videos to use, nothing.
+ public static async Task SeedAsync(FebeDatabase database, DemoWorld world, DataFolderLayout data, IClock clock, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(database);
+ ArgumentNullException.ThrowIfNull(world);
+ ArgumentNullException.ThrowIfNull(data);
+ ArgumentNullException.ThrowIfNull(clock);
+ if (world.VideoFile is not { } movingFile || !File.Exists(movingFile)
+ || (await database.Accounts.ListAsync(ct).ConfigureAwait(false)).FirstOrDefault(a => a.Username == StillAccount) is not { } marta)
+ {
+ return;
+ }
+
+ var now = clock.Now;
+ var folder = Path.GetDirectoryName(movingFile)!;
+ var own = await VideosAsync(database, world, new LibraryFilter { AccountIds = [marta.Id] }, 3, null, [], ct).ConfigureAwait(false);
+ var story = await VideosAsync(
+ database, world, new LibraryFilter { Kind = LibraryKindFilter.Stories }, 1, marta.Id, [.. own.Select(m => m.Sha256!)], ct).ConfigureAwait(false);
+ var stills = own.Take(1).Concat(story).ToList();
+ var thumbnails = new ThumbnailStore(data.Thumbnails);
+ var n = 0;
+ foreach (var media in stills)
+ {
+ n++;
+ var cover = world.Pictures[media.Sha256!];
+ var bytes = await Task.Run(() => StillVideo(cover), ct).ConfigureAwait(false);
+ StillVideoResult result;
+ using (var stream = new MemoryStream(bytes, writable: false))
+ {
+ result = StillVideoAnalyzer.Analyse(stream, ct);
+ }
+
+ // Never a row the analyser did not give: a video that would not be «Fermo» stays a moving one of the demo.
+ if (result.Outcome != VideoAnalysisOutcome.Still)
+ {
+ continue;
+ }
+
+ var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
+ var file = Path.Combine(folder, FileName(n));
+ await File.WriteAllBytesAsync(file, bytes, ct).ConfigureAwait(false);
+ thumbnails.CreateFromFile(sha, cover);
+ await database.Media.UpdateAsync(
+ media with
+ {
+ Sha256 = sha,
+ Bytes = bytes.Length,
+ Width = H264PcmWriter.DemoWidth,
+ Height = H264PcmWriter.DemoHeight,
+ Duration = TimeSpan.FromSeconds((double)H264PcmWriter.DemoPictures / H264PcmWriter.DemoFps),
+ },
+ ct).ConfigureAwait(false);
+ world.StillVideoFiles[sha] = file;
+ await database.VideoAnalyses.SetAsync(result.ToAnalysis(sha, now.AddDays(-2 - n)), ct).ConfigureAwait(false);
+ }
+
+ // «In movimento» for the next video of the account (the demo's moving file, as «È un video fermo?» would find it),
+ // «Non analizzabile» (too slow) for the one after, on a different picture.
+ if (own.Skip(1).FirstOrDefault() is { Sha256: { } movingSha })
+ {
+ StillVideoResult moving;
+ await using (var stream = File.OpenRead(movingFile))
+ {
+ moving = StillVideoAnalyzer.Analyse(stream, ct);
+ }
+
+ await database.VideoAnalyses.SetAsync(moving.ToAnalysis(movingSha, now.AddDays(-1)), ct).ConfigureAwait(false);
+ if (own.Skip(2).FirstOrDefault() is { Sha256: { } slowSha } && !string.Equals(slowSha, movingSha, StringComparison.Ordinal))
+ {
+ await database.VideoAnalyses.SetAsync(
+ new VideoAnalysis(slowSha, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.NotAnalyzable, now.AddHours(-20), Note: VideoAnalysisNotes.TooSlow),
+ ct).ConfigureAwait(false);
+ }
+ }
+ }
+
+ ///
+ /// The still video of a cover picture: the middle of the picture in the proportions of the demo video, reduced to
+ /// its size, after a short fade from black ().
+ ///
+ public static byte[] StillVideo(string coverPath)
+ {
+ using var decoded = ImageDecoder.Decode(File.ReadAllBytes(coverPath));
+ const int Width = H264PcmWriter.DemoWidth;
+ const int Height = H264PcmWriter.DemoHeight;
+ var (w, h) = decoded.Width * Height > decoded.Height * Width
+ ? (decoded.Height * Width / Height, decoded.Height)
+ : (decoded.Width, decoded.Width * Height / Width);
+ using var cropped = new RgbaImage(w, h);
+ var left = (decoded.Width - w) / 2;
+ var top = (decoded.Height - h) / 2;
+ for (var y = 0; y < h; y++)
+ {
+ decoded.GetRow(top + y).Slice(left * RgbaImage.BytesPerPixel, w * RgbaImage.BytesPerPixel).CopyTo(cropped.GetRow(y));
+ }
+
+ using var small = ImageResampler.Resize(cropped, Width, Height);
+ return H264PcmWriter.DemoStillVideo(H264PcmWriter.FromRgba(small));
+ }
+
+ ///
+ /// Up to present videos of the filter, newest first, each on its own cover picture, not of
+ /// and not on a picture of (the accounts share pictures,
+ /// and one picture gives one still file). First the pictures that no copy uses (the copies of the demo keep the SHA-256
+ /// they were made from); how many there are depends on the day and the hour the demo is built, so when they are not
+ /// enough the pictures of copied photos follow, never the video of a copy.
+ ///
+ private static async Task> VideosAsync(FebeDatabase database, DemoWorld world, LibraryFilter filter, int count, long? exceptAccount, IReadOnlyList exceptShas, CancellationToken ct)
+ {
+ var found = new List();
+ var spare = new List();
+ var shas = new HashSet(exceptShas, StringComparer.Ordinal);
+ LibraryCursor? cursor = null;
+ do
+ {
+ var page = await database.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 }, ct).ConfigureAwait(false);
+ foreach (var tile in page.Tiles)
+ {
+ if (tile.CoverKind != MediaKind.Video || tile.CoverMediaId is not { } id || tile.AccountId == exceptAccount
+ || await database.Media.GetAsync(id, ct).ConfigureAwait(false) is not { Sha256: { } sha, RelativePath: not null } media
+ || !EntryStateRules.IsPresent(media.State) || !world.Pictures.ContainsKey(sha) || shas.Contains(sha))
+ {
+ continue;
+ }
+
+ var copies = await database.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false);
+ if (copies.Any(c => c.MediaId == media.Id || c.Variant == ExportVariant.Frame))
+ {
+ continue;
+ }
+
+ shas.Add(sha);
+ if (copies.Count > 0)
+ {
+ spare.Add(media);
+ continue;
+ }
+
+ found.Add(media);
+ if (found.Count == count)
+ {
+ return found;
+ }
+ }
+
+ cursor = page.Older;
+ }
+ while (cursor is not null);
+
+ found.AddRange(spare.Take(count - found.Count));
+ return found;
+ }
+}
diff --git a/src/Febe.Web/FebeWeb.cs b/src/Febe.Web/FebeWeb.cs
index 8b6a397..de07c29 100644
--- a/src/Febe.Web/FebeWeb.cs
+++ b/src/Febe.Web/FebeWeb.cs
@@ -4,7 +4,9 @@ using Febe.Core.Alerts;
using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import;
+using Febe.Core.Library;
using Febe.Core.Library.Conversion;
+using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Web.Api;
using Febe.Web.Connection;
@@ -105,6 +107,28 @@ public static class FebeWeb
// Frames of videos (tappa E3): previews, single frames, «Scarica» of several in a zip.
services.TryAddSingleton();
services.TryAddSingleton();
+ // «È un video fermo?» and «Cerca i video fermi» (tappa E4): only on request, one video at a time.
+ services.TryAddSingleton(sp =>
+ {
+ var clock = sp.GetRequiredService();
+ var changes = sp.GetRequiredService();
+ var files = sp.GetRequiredService();
+ // Italian text and exception type names only (never paths), to the log of the composition (Febe's in FebeApp).
+ var logger = sp.GetService()?.CreateLogger("Febe.VideoFermi");
+ return new StillVideoService(new StillVideoEnvironment
+ {
+ Storage = sp.GetRequiredService(),
+ Resolve = files.Resolve,
+ Clock = clock,
+ Gate = sp.GetRequiredService(),
+ Session = sp.GetRequiredService(),
+ // The demo serves one moving file for the videos it has no still file for: their SHA-256 is never that file's.
+ VerifySource = !options.Demo,
+ Analyser = sp.GetService>(), // tests only
+ Changed = accountId => changes.Publish(new LibraryChange(clock.Now, accountId, "fermi")),
+ Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
+ });
+ });
services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{
@@ -168,6 +192,7 @@ public static class FebeWeb
ImportApi.Map(endpoints);
ExportApi.Map(endpoints);
FramesApi.Map(endpoints);
+ StillVideosApi.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 18383b8..658725d 100644
--- a/src/Febe.Web/LEGGIMI.md
+++ b/src/Febe.Web/LEGGIMI.md
@@ -76,6 +76,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri
| `ExportRootOptions` (Core, copie esterne §4.10) | Docker: `/esporta` **non dichiarata** (nulla si scrive); desktop: qualsiasi cartella | Server: `--esporta`/`FEBE_ESPORTA` (attiva solo se c'è un montaggio su `/esporta` o sotto); dimostrazione: la sua `esporta`, mostrata come `/esporta` (`ShownAs`) |
| `IExportDisk` (Core) | `SystemExportDisk` (spazio libero delle lettere di unità, FAT32 dal tipo del file system) | Desktop: `WindowsExportDisk` (anche le condivisioni di rete come `\\nas\foto`); prove e dimostrazione: misure fisse |
| `IEngineSessionState` (Core) | `NoEngineSession`: le copie non aspettano mai | `Febe.App`: `RuntimeSessionState` sul motore (fra una sessione e l'altra, D10) |
+| `StillVideoService` (Core, tappa E4) | Uno solo sull'archivio, sui file della libreria (`IMediaFileResolver`), su `LongWorkGate` e `IEngineSessionState`, con lo SHA-256 controllato prima di ogni analisi; il registro riceve solo testo italiano e nomi di eccezioni | Nessuno: nella dimostrazione FebeWeb lo registra con `VerifySource = false` (i suoi SHA-256 non sono quelli dei file); le prove, budget diversi. `Febe.App` usa il ripiego e lo chiude all'arresto prima dell'archivio, aspettando al più 5 s il video al lavoro |
| `ExportHub` (`Export/`) | Costruisce l'unico `ExportService` al primo uso (e segna «interrotto» ciò che l'arresto ha fermato, `Recovered`); a lavoro finito pubblica `LibraryChange` con motivo `export` | Nessuno |
- `ImportHub.LibrarySettingsChanged()` va chiamato quando cambiano cartella o schema dei nomi (lo fa già
@@ -111,9 +112,9 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| `GET/PUT /api/preferences` | Tema (`chiaro`, `scuro`, `sistema`) |
| `GET /api/engine`, `POST /api/engine/pause`, `/resume` | Istantanea del motore, collegamento, `canResume` |
| `POST /api/browser/show`, `/api/browser/used` | «Apri il browser» (desktop), uso del browser |
-| `GET /api/eventi` | SSE: `motore` (istantanea, al massimo ogni 300 ms, comunque ogni 60 s), `libreria` (al massimo ogni 1,5 s), commento ogni 25 s |
+| `GET /api/eventi` | SSE: `motore` (istantanea, al massimo ogni 300 ms, comunque ogni 60 s), `libreria` (al massimo ogni 1,5 s, un evento per ogni motivo che c'è stato: nessuno ne copre un altro; `accountId` solo se è lo stesso per tutti quelli di quel motivo), commento ogni 25 s |
| `GET /api/library/days?mode=grouped\|files` | Totali (sempre elementi: `entries`, `accounts`) e giorni con conteggio e cursore (per la finestra del mosaico); con `mode=files` («Tutte le foto») i giorni contano i file presenti in libreria e `files` è la loro somma (altrimenti `null`). Un altro valore di `mode` dà 400. Stessi filtri di `/api/library` |
-| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`, `copies=notCopied\|copied\|removedOrSuperseded` (solo i file dovuti; un altro valore 400). Con una cartella delle copie in uso le tessere hanno `copies` (`copied`, `partly` con `copiesDone`/`copiesDue`) e `/days` ha `hasDestinations`; il visualizzatore dà le copie di ogni file (`copies`, al più 6) e `canCopy`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 |
+| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind` (con `kind=stillvideos`, «Video fermi» della tappa E4: gli elementi con un video in libreria la cui ultima analisi dice «Fermo», e con `mode=files` solo quei video), `accounts`, `from`, `to`, `provenance`, `q`, `copies=notCopied\|copied\|removedOrSuperseded` (solo i file dovuti; un altro valore 400). Con una cartella delle copie in uso le tessere hanno `copies` (`copied`, `partly` con `copiesDone`/`copiesDue`) e `/days` ha `hasDestinations`; il visualizzatore dà le copie di ogni file (`copies`, al più 6) e `canCopy`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 |
| `GET /api/library/tiles?ids=` | Tessere per chiave |
| `GET /api/thumbnails/{chiave}`, `GET /api/media/{id}/file[?download=1]` | Miniature (immutabili) e file (con range) |
| `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) |
@@ -143,8 +144,10 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| `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`; `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 |
+| `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. `mode: "fermo"` (tappa E4) è «Salva il fotogramma» → «Nella cartella delle copie»: un solo file (`mediaIds` di uno), solo `format`, l'istante è quello dell'analisi, nome `…_fotogramma.`; un video non «Fermo» o mai analizzato si salta (`notStill`, «Non è un video fermo, o non è stato analizzato») |
| `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/media/{id}/still`, `GET /api/media/{id}/still/frame?format=&max=&download=1` | Video fermi (`Api/StillVideosApi.cs`, `StillVideoService` di Core, tappa E4), solo a richiesta: «È un video fermo?» analizza subito un video (anche durante una sessione del motore, una analisi alla volta, 30 s al più: 503 «L'analisi richiede troppo tempo: avviala dalla selezione», o «…: resta l'esito di prima» se il video ha un esito che la selezione salterebbe, niente salvato; 400 una foto, 404 file assente o che non si legge, 409 file cambiato) e risponde con `still` (`outcome` `still`\|`moving`\|`notAnalyzable`, `current`, `frameAtMs`, `frameLabel`, `note` in codici inglesi, `day`), lo stesso che ha ogni video del visualizzatore in `media[].still` (null se mai analizzato). Il fotogramma di «Salva il fotogramma» → «Scarica»: quello scelto dall'analisi (il più nitido, mai uno scuro), PNG se non si sceglie, nome `…_fotogramma.`, `max` per l'anteprima (JPG); 409 se il video non è «Fermo». Mai in cache |
+| `POST /api/still-videos/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId }`, uno solo), `GET /api/still-videos/progress`, `POST /api/still-videos/stop` | «Cerca i video fermi»: conteggi della conferma per file (`toAnalyse`, `alreadyAnalysed`, `photosSkipped`, `missing`, `summary`, `waiting` se ora aspetterebbe); un lavoro in memoria, un video alla volta, mai durante una sessione del motore né con importazione, copie, ricostruzione o uno zip di fotogrammi (aspetta, `waiting` dice perché), 2 minuti per video (oltre «Non analizzabile»); avanzamento con `summary` («Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile»); «Interrompi» non salva il video in corso. Non riprende da solo alla riapertura; i già analizzati si saltano, non quelli con la nota `TooSlow`. La risposta di `/start` dice in `added` quanti ne ha aggiunti (0: erano già in coda). Ogni esito salvato pubblica `LibraryChange` con motivo `fermi` |
| `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) |
@@ -275,6 +278,15 @@ scrive mai nella libreria vera e non usa la rete.
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.
+- Video fermi (tappa E4, `Demo/DemoStillVideos.cs`): il video più recente di @marta.demo su un'immagine senza copie
+ (quale, dipende dal giorno e dall'ora: anche una storia, o vecchio di mesi) e la storia video più recente di un altro
+ account (su un'altra immagine) sono la loro copertina ferma per 2 secondi dopo una breve dissolvenza dal nero (`campioni/video-fermo-dimostrativo-1.mp4` e `-2.mp4`, da `H264PcmWriter.DemoStillVideo`), ciascuno registrato con
+ l'impronta del suo file: «Salva il fotogramma» funziona anche «Nella cartella delle copie». Hanno un'analisi «Fermo»
+ data dall'analizzatore vero (il filtro «Video fermi» li mostra); i due successivi di @marta.demo, scelti allo stesso modo,
+ sono uno «In movimento» e uno «Non analizzabile» (troppo lento, «Analizza di nuovo»; altri video con la stessa immagine
+ hanno lo stesso esito); gli altri non sono mai stati analizzati, così «È un video fermo?» e «Cerca i video fermi»
+ lavorano davvero (sul video dimostrativo che si muove). Nella dimostrazione il
+ servizio non controlla l'impronta dei file prima di analizzarli (`VerifySource = false`).
- 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 7898b4d..6556df4 100644
--- a/src/Febe.Web/Library/FebeLibrary.cs
+++ b/src/Febe.Web/Library/FebeLibrary.cs
@@ -120,9 +120,50 @@ public sealed class LibraryConversionFileResolver(FebeLibrary library) : IConver
/// Something changed in the library: the open pages reload what they show.
/// When.
/// The account concerned, when there is only one.
-/// Short machine reason: "stored", "deleted", "account", "import".
+/// Short machine reason: "stored", "deleted", "account", "import", "export", "fermi".
public sealed record LibraryChange(DateTimeOffset At, long? AccountId, string Reason);
+///
+/// The changes a page has not been told yet, one per reason: pages skip some reasons («fermi»), so one must not take the
+/// place of another. Two of one reason are told together, with the account only if it is the same.
+///
+internal sealed class PendingLibraryChanges
+{
+ private readonly Dictionary _pending = new(StringComparer.Ordinal);
+
+ public bool Any
+ {
+ get
+ {
+ lock (_pending)
+ {
+ return _pending.Count > 0;
+ }
+ }
+ }
+
+ public void Add(LibraryChange change)
+ {
+ lock (_pending)
+ {
+ _pending[change.Reason] = _pending.TryGetValue(change.Reason, out var before) && before.AccountId != change.AccountId
+ ? change with { AccountId = null }
+ : change;
+ }
+ }
+
+ /// The changes to tell, in the order they came in; none is left.
+ public IReadOnlyList Take()
+ {
+ lock (_pending)
+ {
+ LibraryChange[] taken = [.. _pending.Values.OrderBy(c => c.At)];
+ _pending.Clear();
+ return taken;
+ }
+ }
+}
+
///
/// Library notifications for the server-sent events (/api/eventi, event libreria). Publishers: the web
/// layer itself (deletions, account changes), the download queue () and the import (M7).
diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css
index b39c594..cddfaba 100644
--- a/src/Febe.Web/wwwroot/css/febe.css
+++ b/src/Febe.Web/wwwroot/css/febe.css
@@ -341,7 +341,8 @@ input[type=range].cursore:focus-visible{outline:2px solid var(--accento);outline
/* Libreria: when the tools do not fit in one row (a duplicates link, a narrow screen above 1000 px) the group on
the right goes to a second row instead of squeezing the kind chips into a column. */
@media (min-width:1001px){
- .strumenti:has(> div > .filtri){flex-wrap:wrap;row-gap:10px}
+ .strumenti:has(> div > .filtri){flex-wrap:wrap;row-gap:10px;padding-left:22px}
+ .strumenti:has(> div > .filtri) .filtri{margin-left:6px}
.strumenti .filtri{flex-wrap:nowrap;flex-shrink:0}
}
@@ -1258,6 +1259,24 @@ input[type=range].cursore.scorri-fotogramma{width:100%}
.scheda-conversione .riga-conteggi{margin-top:0}
.scheda-conversione .avviso{margin:10px 0 0}
+/* ---------- video fermi (§4.10, tappa E4) ---------- */
+.dialogo.cerca-fermi{width:560px}
+.riepilogo-fermi{margin-bottom:12px}
+.riepilogo-fermi .avviso{margin-top:8px}
+.vis .scheda dd.riga-fermo .analizza-di-nuovo{flex:none}
+.dialogo.fotogrammi .modo-fotogrammi > .istante-mostrato{margin:0}
+@media (max-width:560px){
+ /* On the phone the panel of the viewer is short: the actions two by two leave room for the file's rows */
+ .vis .scheda .basso{display:grid;grid-template-columns:repeat(2,minmax(0,1fr))}
+ .vis .scheda .basso .btn{padding:0 6px;font-size:13px}
+ .vis .scheda .basso .nota-fotogramma,.vis .scheda .basso .btn:last-child:nth-child(odd){grid-column:1/-1}
+ .strumenti .destra{flex-wrap:wrap;justify-content:flex-end}
+ .esportazione-dashboard .elenco-attivita.largo li{flex-wrap:wrap;row-gap:6px}
+ .esportazione-dashboard .elenco-attivita.largo .quando{width:100%}
+ .esportazione-dashboard .elenco-attivita.largo .chi-cosa{flex-basis:100%}
+ .esportazione-dashboard .elenco-attivita.largo .btn{margin-left:auto}
+}
+
/* ---------- 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/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js
index 7f5c357..19866a6 100644
--- a/src/Febe.Web/wwwroot/js/core/shell.js
+++ b/src/Febe.Web/wwwroot/js/core/shell.js
@@ -356,6 +356,7 @@ async function render() {
if (current) {
current.frame.destroy();
current = null;
+ document.dispatchEvent(new Event('febe:pagina')); // what lies over the page (the viewer, a dialog) goes with it
}
for (const [key, link] of Object.entries(navLinks)) {
const here = route && route.nav === key;
diff --git a/src/Febe.Web/wwwroot/js/core/ui.js b/src/Febe.Web/wwwroot/js/core/ui.js
index 18d9a24..ffc0b4a 100644
--- a/src/Febe.Web/wwwroot/js/core/ui.js
+++ b/src/Febe.Web/wwwroot/js/core/ui.js
@@ -37,7 +37,8 @@ const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:n
* Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value)
* resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored.
* build may also return onEscape (called first on Esc: returning true means the dialog handled it, say by closing a
- * list of suggestions, and stays open) and onClose (called once, however the dialog closes).
+ * list of suggestions, and stays open) and onClose (called once, however the dialog closes). A change of the page under
+ * it (a link of a short notice, Back) takes it away as dismissed: its buttons are for what is no longer shown.
*/
export function dialog({ title, className = '', build, labelledBy, dismissable = true }) {
return new Promise((resolve) => {
@@ -49,6 +50,7 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
closed = true;
veil.remove();
document.removeEventListener('keydown', onKey, true);
+ document.removeEventListener('febe:pagina', onPage);
if (parts && typeof parts.onClose === 'function') {
try {
parts.onClose();
@@ -94,7 +96,9 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
}
}
};
+ const onPage = () => close(undefined);
document.addEventListener('keydown', onKey, true);
+ document.addEventListener('febe:pagina', onPage);
document.body.append(veil);
const autofocus = box.querySelector('[autofocus]') || box.querySelector('.contenuto ' + FOCUSABLE) || box.querySelector(FOCUSABLE);
if (autofocus) autofocus.focus();
diff --git a/src/Febe.Web/wwwroot/js/pages/account.js b/src/Febe.Web/wwwroot/js/pages/account.js
index 90ddfdc..0a477ee 100644
--- a/src/Febe.Web/wwwroot/js/pages/account.js
+++ b/src/Febe.Web/wwwroot/js/pages/account.js
@@ -21,6 +21,7 @@ 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';
+import { stillVideosDialog } from './still-videos.js';
const KINDS = [
{ key: 'post', api: 'posts', stat: 'posts', label: 'scheda.tipi.posts' },
@@ -217,6 +218,7 @@ async function contentsTab(page, route, detail) {
selection: mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids },
hasDestination,
}),
+ stillSelected: () => stillVideosDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }),
deleteSelected: async () => {
const { ids, files } = mosaic.selectedEntries();
const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null);
@@ -276,6 +278,8 @@ async function contentsTab(page, route, detail) {
const onChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 500);
const onMarks = later(() => mosaic && mosaic.refreshMarks().catch(() => {}), 600);
page.onLibrary((change) => {
+ // An analysis (tappa E4) changes nothing here: the filter «Video fermi» is of the Libreria only.
+ if (change.reason === 'fermi') return;
if (!change.accountId || change.accountId === detail.account.id) {
onChange();
if (change.reason === 'export') onMarks();
diff --git a/src/Febe.Web/wwwroot/js/pages/accounts.js b/src/Febe.Web/wwwroot/js/pages/accounts.js
index 39859aa..c34cee7 100644
--- a/src/Febe.Web/wwwroot/js/pages/accounts.js
+++ b/src/Febe.Web/wwwroot/js/pages/accounts.js
@@ -325,7 +325,9 @@ export default {
}, 150);
search.addEventListener('input', onSearch);
const onChange = later(reload, 600);
- page.onLibrary(onChange);
+ page.onLibrary((change) => {
+ if (change.reason !== 'fermi') onChange(); // an analysis («Cerca i video fermi») changes nothing here
+ });
page.onLeave(() => {
onSearch.cancel();
onChange.cancel();
diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js
index 4045da6..ec212bd 100644
--- a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js
+++ b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js
@@ -4,11 +4,14 @@
// 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).
+// Tappa E4: the card «Video fermi» while «Cerca i video fermi» works (progress, why it waits, «Interrompi») and, until
+// Febe closes, what the last one found.
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';
+import { STILL_LIBRARY, endText, readStillVideos, stopStillVideos } from './still-videos.js';
const STATE_LOOK = {
running: ['accento', 'play'],
@@ -26,12 +29,15 @@ export async function mountExport(page) {
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 stills = h('section.blocco.ricerca-fermi', { hidden: true });
const recent = h('section.blocco');
- fill(page.body, h('div.attivita.esportazione-dashboard', current, pending, conversion, recent));
+ fill(page.body, h('div.attivita.esportazione-dashboard', current, pending, stills, conversion, recent));
let overview = null;
let runs = [];
let progress = null;
+ let stillJob = null;
+ let drawnStills = '';
let wasRunning = null;
let timer = 0;
let ticks = 0;
@@ -79,7 +85,7 @@ export async function mountExport(page) {
poll();
return;
}
- timer = setTimeout(poll, progress && progress.running ? 1000 : 5000);
+ timer = setTimeout(poll, (progress && progress.running) || (stillJob && stillJob.running) ? 1000 : 5000);
}
async function read() {
@@ -89,11 +95,19 @@ export async function mountExport(page) {
if (error.name === 'AbortError') return;
progress = null;
}
+ try {
+ stillJob = await readStillVideos({ signal: page.signal });
+ } catch (error) {
+ if (error.name === 'AbortError') return;
+ stillJob = null;
+ }
drawCurrent();
+ drawStills();
const running = Boolean(progress && progress.running);
ticks += 1;
// The jobs and the folders follow the copy: when it starts or ends, and every few seconds while it works.
- if (running !== wasRunning || !running || ticks % 5 === 0) await loadSide();
+ const quick = running || Boolean(stillJob && stillJob.running);
+ if (running !== wasRunning || !quick || ticks % 5 === 0) await loadSide();
wasRunning = running;
}
@@ -216,6 +230,52 @@ export async function mountExport(page) {
again();
}
+ // ------------------------------------------------------------------------------------------- video fermi
+ function drawStills() {
+ const job = stillJob;
+ stills.hidden = !job || !(job.running || job.total);
+ // A job that is over stays as it is drawn: read again every few seconds, its link keeps the focus of the keyboard.
+ const drawn = stills.hidden || job.running ? '' : JSON.stringify(job);
+ if (drawn && drawn === drawnStills) return;
+ drawnStills = drawn;
+ if (stills.hidden) {
+ stills.replaceChildren();
+ return;
+ }
+ const head = h('div.testa-blocco', h('h2', t('esportazione.fermi.dashboard.titolo')));
+ if (!job.running) {
+ fill(stills, head, h('div.pannello.scheda-conversione', h('div.riga-conteggi',
+ h('span', endText(job)),
+ job.still ? h('a.btn.nudo.piccolo', { href: withCarried(STILL_LIBRARY) }, t('esportazione.fermi.mostra')) : null)));
+ return;
+ }
+ // Redrawn every second: the button keeps the focus of the keyboard.
+ const focused = stills.contains(document.activeElement);
+ const percent = job.total ? Math.round((job.done / job.total) * 100) : 0;
+ const count = [t('esportazione.fermi.dashboard.avanzamento', { fatti: job.done, n: job.total })];
+ if (job.still) count.push(t('esportazione.fermi.dashboard.fermi', { n: job.still }));
+ fill(stills, head, h('div.pannello.avanzamento-import.avanzamento-copia.avanzamento-fermi',
+ h('h2.sez', t('esportazione.fermi.dashboard.barra')),
+ h('div.misura.grande-misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(percent), 'aria-label': t('esportazione.fermi.dashboard.barra') },
+ h('i', { style: { width: `${percent}%` } })),
+ h('p.conteggio.dati', count.join(' · ')),
+ job.waiting ? h('p.avviso.ambra.fase-copia', icon('hourglass', 's'), h('span', job.waiting)) : null,
+ h('p.aiuto.piccolo.file-corrente', !job.waiting && job.currentMediaId != null ? t('esportazione.fermi.dashboard.analizzo') : ''),
+ h('div.riga-azione', h('button.btn', { type: 'button', disabled: job.stopped, onclick: interruptStills }, icon('x', 's'), t('esportazione.fermi.dashboard.interrompi')))));
+ const button = focused && stills.querySelector('button:not([disabled])');
+ if (button) button.focus();
+ }
+
+ async function interruptStills(e) {
+ e.currentTarget.disabled = true;
+ try {
+ await stopStillVideos();
+ } catch (error) {
+ showError(error);
+ }
+ again();
+ }
+
// ------------------------------------------------------------------------------------------- library conversion
function drawConversion() {
const c = overview && overview.libraryConversion;
diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard.js b/src/Febe.Web/wwwroot/js/pages/dashboard.js
index 5e333e7..0be5ec6 100644
--- a/src/Febe.Web/wwwroot/js/pages/dashboard.js
+++ b/src/Febe.Web/wwwroot/js/pages/dashboard.js
@@ -90,7 +90,9 @@ export default {
}
await loadSide();
if (page.signal.aborted) return;
- page.onLibrary(() => loadSide());
+ page.onLibrary((change) => {
+ if (change.reason !== 'fermi') loadSide(); // an analysis («Cerca i video fermi») changes nothing here
+ });
const timer = setInterval(() => {
if (latest && document.visibilityState === 'visible') loadSide();
}, 60000);
diff --git a/src/Febe.Web/wwwroot/js/pages/frames.js b/src/Febe.Web/wwwroot/js/pages/frames.js
index 1c93f2b..1aa2ae7 100644
--- a/src/Febe.Web/wwwroot/js/pages/frames.js
+++ b/src/Febe.Web/wwwroot/js/pages/frames.js
@@ -5,8 +5,10 @@
// 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.
+// Tappa E4: «Salva il fotogramma» of a still video is this dialog without the three ways (the analysis has chosen the
+// frame: the sharpest it looked at).
-import { api, withCarried } from '../core/api.js';
+import { api, download, 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';
@@ -54,13 +56,15 @@ function parseSeconds(text) {
/**
* 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.
+ * the copies exists for the files, so «Nella cartella delle copie» can be chosen. still: { label } with mediaId opens
+ * «Salva il fotogramma» of a still video (tappa E4): the frame at the label, chosen by the analysis. Resolves when the
+ * dialog closes.
*/
-export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDestination = false }) {
+export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDestination = false, still = null }) {
const single = mediaId != null;
const chosen = single ? { mediaIds: [mediaId] } : selection;
const state = {
- mode: 'istante',
+ mode: still ? 'fermo' : 'istante',
atMs: Math.max(0, Math.round(atMs || 0)),
every: '2',
count: '6',
@@ -70,7 +74,7 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
};
return dialog({
- title: t(single ? 'esportazione.fotogrammi.titolo' : 'esportazione.fotogrammi.titoloSelezione'),
+ title: still ? t('esportazione.fermi.salva') : t(single ? 'esportazione.fotogrammi.titolo' : 'esportazione.fotogrammi.titoloSelezione'),
className: 'fotogrammi',
build: (close) => {
const body = h('div.contenuto', h('p.aiuto', t('esportazione.fotogrammi.apro')));
@@ -175,13 +179,16 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
/** 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 (still) return base;
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') {
+ if (still) {
+ fill(modeBox, preview, h('p.aiuto.istante-mostrato', t('esportazione.fermi.salvaQuale', { istante: still.label })));
+ } else if (state.mode === 'istante') {
fill(modeBox,
single ? preview : null,
single ? scrubber : null,
@@ -214,8 +221,24 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
return withCarried(`/api/media/${mediaId}/frame?at=${Math.max(0, Math.round(ms))}&max=${max}`);
}
+ /** «Salva il fotogramma»: one picture, the frame that will be saved. An image tells no reason, a question does. */
+ function drawStillPreview() {
+ const url = withCarried(`/api/media/${mediaId}/still/frame?max=480`);
+ const img = h('img', { src: url, alt: t('esportazione.fermi.salvaAnteprima') });
+ img.addEventListener('error', async () => {
+ let message = t('esportazione.fotogrammi.nonDisponibile');
+ try {
+ await api(url, { raw: true });
+ } catch (error) {
+ message = error.message;
+ }
+ if (!closed) fill(preview, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', message)));
+ });
+ fill(preview, img);
+ }
+
async function drawPreviews() {
- if (!single) return;
+ if (!single || still) return;
const wanted = request();
const mine = ++stripToken;
if (!wanted) return;
@@ -275,11 +298,11 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
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'))) }),
+ radio({ name: outputName, value: 'scarica', checked: true, onchange: pickOutput, labelNode: h('span', h('b', t('esportazione.fotogrammi.scarica')), h('small', t(still ? 'esportazione.fermi.salvaScaricaAiuto' : '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'))),
+ labelNode: h('span', h('b', t('esportazione.fotogrammi.cartella')), h('small', t(!hasDestination ? 'esportazione.fotogrammi.nessunaCartella' : still ? 'esportazione.fermi.salvaCartellaAiuto' : 'esportazione.fotogrammi.cartellaAiuto'))),
});
if (!hasDestination) {
r.input.disabled = true;
@@ -299,6 +322,13 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
summary.replaceChildren();
return;
}
+ if (still && state.output === 'scarica') {
+ // One frame, always the one shown: nothing to count.
+ plan = { kind: 'scarica', frames: 1, summary: t('esportazione.fermi.salvaRiepilogo') };
+ drawSummary();
+ drawStart();
+ return;
+ }
fill(summary, h('p.aiuto', t('esportazione.fotogrammi.conto')));
try {
const result = state.output === 'cartella'
@@ -334,7 +364,7 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
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);
+ !p.frames && !p.overCap ? h('p.aiuto', t(p.hasDestination === false ? 'esportazione.copia.nessunaCartella' : still ? 'esportazione.fermi.salvaNiente' : 'esportazione.fotogrammi.nienteCartella')) : null);
} else {
fill(summary,
h('p.riepilogo-copia', h('b', p.summary)),
@@ -372,6 +402,10 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
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 if (still) {
+ await download(`/api/media/${mediaId}/still/frame?format=${state.format}&download=1`, null, 'fotogramma.png');
+ toast(t('esportazione.fotogrammi.scaricati', { n: 1 }));
+ close(frames);
} else {
const ready = await api('/api/frames/download-token', { method: 'POST', body: { ...chosen, frames } });
const a = h('a', { href: withCarried(ready.url), download: '' });
@@ -393,8 +427,8 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
function drawAll() {
fill(body,
h('section.parte-dialogo',
- h('h3', t('esportazione.fotogrammi.quali')),
- modes, modeBox),
+ h('h3', t(still ? 'esportazione.fermi.salvaAnteprima' : 'esportazione.fotogrammi.quali')),
+ still ? null : modes, modeBox),
h('section.parte-dialogo',
h('h3', t('esportazione.fotogrammi.formato')),
formats, lossyNote,
@@ -404,10 +438,11 @@ export function framesDialog({ mediaId = null, atMs = 0, selection = null, hasDe
outputs, summary));
drawMode();
changed();
+ if (still) drawStillPreview();
}
async function begin() {
- if (!single) {
+ if (!single || still) {
drawAll();
return;
}
diff --git a/src/Febe.Web/wwwroot/js/pages/library.js b/src/Febe.Web/wwwroot/js/pages/library.js
index faaae67..44a7815 100644
--- a/src/Febe.Web/wwwroot/js/pages/library.js
+++ b/src/Febe.Web/wwwroot/js/pages/library.js
@@ -7,6 +7,8 @@
// 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.
+// Tappa E4: the chip «Video fermi» after «Video», and «Cerca i video fermi» in the selection bar (one video at a time,
+// on request only; the progress and «Interrompi» are in Dashboard → Esportazione).
import { api, download, withCarried } from '../core/api.js';
import { caps } from '../core/context.js';
@@ -20,11 +22,14 @@ 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';
+import { stillVideosDialog } from './still-videos.js';
const KINDS = [
{ key: 'tutto', api: 'all', label: 'libreria.tipi.all' },
{ key: 'foto', api: 'photos', label: 'libreria.tipi.photos' },
{ key: 'video', api: 'videos', label: 'libreria.tipi.videos' },
+ // Tappa E4 (§16 domanda 40): the entries with a video analysed as «Fermo»; Libreria only, not the account tabs.
+ { key: 'fermi', api: 'stillvideos', label: 'libreria.tipi.stillVideos' },
{ key: 'storie', api: 'stories', label: 'libreria.tipi.stories' },
{ key: 'evidenza', api: 'highlights', label: 'libreria.tipi.highlights' },
{ key: 'taggati', api: 'tagged', label: 'libreria.tipi.tagged' },
@@ -306,7 +311,7 @@ export default {
page.saveBar(null);
return;
}
- page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected, copySelected: hasDestinations ? copySelected : null, framesSelected }));
+ page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected, copySelected: hasDestinations ? copySelected : null, framesSelected, stillSelected }));
}
function setSelecting(on) {
@@ -333,6 +338,10 @@ export default {
return framesDialog({ selection: mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }, hasDestination: hasDestinations });
}
+ function stillSelected() {
+ return stillVideosDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids });
+ }
+
async function exportSelected() {
try {
await download('/api/entries/export', { ids: mosaic.selectedEntries().ids }, 'febe-elementi.csv');
@@ -438,6 +447,8 @@ export default {
// Copies done or a folder changed: the counts may stay the same, the marks of the tiles do not.
const onExportChange = later(() => mosaic && mosaic.refreshMarks().catch(() => {}), 600);
page.onLibrary((change) => {
+ // An analysis (tappa E4) changes only what «Video fermi» shows.
+ if (change && change.reason === 'fermi' && state.tipo !== 'fermi') return;
onLibraryChange();
if (change && change.reason === 'export') onExportChange();
});
@@ -454,11 +465,12 @@ 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), «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.
+ * with copySelected, when a folder of the copies exists), «Fotogrammi…» (with framesSelected), «Cerca i video fermi»
+ * (with stillSelected, tappa E4) 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…», «Fotogrammi…» and «Cerca i video fermi» on the
+ * chosen files.
*/
-export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected, copySelected = null, framesSelected = null }) {
+export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected, copySelected = null, framesSelected = null, stillSelected = null }) {
const n = selected.size;
const entries = mosaic.selectedEntries().ids.length;
let note = t('selezione.nessuno');
@@ -471,6 +483,7 @@ export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteS
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,
+ stillSelected ? h('button.btn.fermi-selezione', { type: 'button', disabled: !n, onclick: stillSelected }, icon('search'), t('esportazione.selezione.fermi')) : null,
h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: deleteSelected }, icon('trash-2'), t('selezione.elimina', { n: entries }))));
}
diff --git a/src/Febe.Web/wwwroot/js/pages/still-videos.js b/src/Febe.Web/wwwroot/js/pages/still-videos.js
new file mode 100644
index 0000000..f837515
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/still-videos.js
@@ -0,0 +1,157 @@
+// Video fermi (spec §4.10, §10.3, tappa E4): what the viewer says of an analysed video, the confirmation of «Cerca i
+// video fermi» of a selection (from the dialogs of mockup 13) and the following of its job. The analysis is only ever
+// asked for: «È un video fermo?» in the viewer, or «Cerca i video fermi» for a selection. The job works on the server, one
+// video at a time, never during an engine session; its progress and «Interrompi» are in Dashboard → Esportazione, and
+// the page that started it says when it ends.
+
+import { api } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { t } from '../core/text.js';
+import { dialog, showError, toast } from '../core/ui.js';
+
+/** How often a job is asked how far it is (milliseconds). */
+const FOLLOW = 1500;
+
+/** Where the progress of the job is. */
+const PROGRESS_PAGE = '/dashboard/esportazione';
+
+/** The library filtered by «Video fermi» (§16 domanda 40). */
+export const STILL_LIBRARY = '/libreria?tipo=fermi';
+
+/** A video that can be analysed: in the library, readable, and with frames Febe can take. */
+export function canAnalyse(media) {
+ return Boolean(media && media.kind === 'video' && media.available && !media.damaged && media.framesAvailable !== false);
+}
+
+/** The words of an analysis in the panel «File» of the viewer. */
+export function stillText(still) {
+ const codes = String(still.note || '').split(' ').map((code) => code.split(':')[0]).filter(Boolean);
+ if (still.outcome === 'still') {
+ return t('esportazione.fermi.fermo')
+ + (codes.includes('SmallMotion') ? t('esportazione.fermi.piccolaParte') : '')
+ + (still.frameLabel ? t('esportazione.fermi.istante', { istante: still.frameLabel }) : '');
+ }
+ if (still.outcome === 'moving') return t('esportazione.fermi.inMovimento');
+ const reasons = t('esportazione.fermi.motivi');
+ const reason = codes.map((code) => reasons[code]).find(Boolean);
+ return reason ? t('esportazione.fermi.nonAnalizzabilePerche', { motivo: reason }) : t('esportazione.fermi.nonAnalizzabile');
+}
+
+// ------------------------------------------------------------------------------------------------- the job
+
+let following = 0;
+let atWork = false;
+
+/**
+ * Reads the job «Cerca i video fermi». While it works it is followed wherever the page goes, and its end is said once
+ * («Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile»).
+ */
+export async function readStillVideos(options = {}) {
+ const job = await api('/api/still-videos/progress', options);
+ noteJob(job);
+ return job;
+}
+
+function noteJob(job) {
+ const ended = atWork && !job.running;
+ atWork = job.running;
+ clearTimeout(following);
+ if (job.running) following = setTimeout(follow, FOLLOW);
+ if (ended && job.total) sayEnd(job);
+}
+
+async function follow() {
+ try {
+ await readStillVideos();
+ } catch {
+ // Febe does not answer for a moment: asked again, at a slower pace.
+ following = setTimeout(follow, FOLLOW * 4);
+ }
+}
+
+/** What a job that is over found. */
+export function endText(job) {
+ if (!job.stopped) return `${job.summary}.`;
+ return job.done ? t('esportazione.fermi.interrotta', { riepilogo: job.summary }) : t('esportazione.fermi.interrottaSubito');
+}
+
+function sayEnd(job) {
+ toast(endText(job), '', job.still ? { label: t('esportazione.fermi.mostra'), href: STILL_LIBRARY } : null);
+}
+
+/** «Interrompi»: the video at work is left, the outcomes already found stay. */
+export async function stopStillVideos() {
+ const job = await api('/api/still-videos/stop', { method: 'POST' });
+ noteJob(job);
+ return job;
+}
+
+// ------------------------------------------------------------------------------------------------- the confirmation
+
+/**
+ * «Cerca i video fermi» of a selection ({ mediaIds } or { entryIds }): how many videos there are to analyse, how many
+ * are already, the photos that are skipped, and the button that starts the job. Resolves when the dialog closes.
+ */
+export function stillVideosDialog(selection) {
+ return dialog({
+ title: t('esportazione.fermi.cercaTitolo'),
+ className: 'cerca-fermi',
+ build: (close) => {
+ const summary = h('div.riepilogo-fermi', { 'aria-live': 'polite' }, h('p.aiuto', t('esportazione.fermi.conto')));
+ const start = h('button.btn.primo', { type: 'button', disabled: true, onclick: () => go() });
+ const cancel = h('button.btn.nudo', { type: 'button', autofocus: true, onclick: () => close(undefined) }, t('comune.annulla'));
+ let plan = null;
+ let closed = false;
+ let busy = false;
+
+ function draw() {
+ fill(start, icon('search'), t('esportazione.fermi.analizza', { n: plan ? plan.toAnalyse : 0 }));
+ start.disabled = busy || !plan || !plan.toAnalyse;
+ }
+
+ async function go() {
+ if (busy || !plan) return;
+ busy = true;
+ draw();
+ try {
+ const job = await api('/api/still-videos/start', { method: 'POST', body: selection });
+ const follow = { label: t('esportazione.copia.vediAvanzamento'), href: PROGRESS_PAGE };
+ if (job.added) toast(t('esportazione.fermi.avviata', { n: job.added }), '', follow);
+ else if (job.running) toast(t('esportazione.fermi.giaInCoda'), '', follow); // all of them were queued already
+ else toast(t('esportazione.fermi.niente'));
+ noteJob(job);
+ close(job);
+ } catch (error) {
+ busy = false;
+ draw();
+ showError(error);
+ }
+ }
+
+ async function count() {
+ try {
+ plan = await api('/api/still-videos/plan', { method: 'POST', body: selection });
+ } catch (error) {
+ if (!closed) fill(summary, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message)));
+ return;
+ }
+ if (closed) return;
+ fill(summary,
+ h('p.riepilogo-copia', h('b', plan.summary)),
+ plan.toAnalyse ? null : h('p.aiuto', t(plan.videos ? 'esportazione.fermi.niente' : 'esportazione.fermi.nienteVideo')),
+ plan.toAnalyse && plan.waiting ? h('div.avviso.ambra', icon('hourglass', 's'), h('span', plan.waiting)) : null);
+ draw();
+ }
+
+ draw();
+ count();
+ return {
+ body: h('div.contenuto', summary, h('p.aiuto', t('esportazione.fermi.cercaAiuto')), h('p.aiuto', t('esportazione.fermi.cercaRiapertura'))),
+ footer: h('footer', h('div.destra', cancel, start)),
+ onClose: () => {
+ closed = true;
+ },
+ };
+ },
+ });
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/viewer.js b/src/Febe.Web/wwwroot/js/pages/viewer.js
index b66946f..dbdc2fc 100644
--- a/src/Febe.Web/wwwroot/js/pages/viewer.js
+++ b/src/Febe.Web/wwwroot/js/pages/viewer.js
@@ -4,6 +4,8 @@
// 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»).
+// Tappa E4: «È un video fermo?» on a video never analysed, the chip and the row «Video fermo» of one that is, and «Salva
+// il fotogramma» of a still video (here only, §16 domanda 46).
import { api, withCarried } from '../core/api.js';
import { caps, serverNow } from '../core/context.js';
@@ -14,6 +16,7 @@ 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';
+import { canAnalyse, stillText } from './still-videos.js';
const KIND_ICON = { post: 'image', story: 'circle-dashed', highlight: 'star', tagged: 'square-user', profile: 'circle-user' };
@@ -32,6 +35,11 @@ export function openViewer({ tile, source, origin, onDeleted }) {
let token = 0;
// The copies whose «Copia di nuovo» started a job: their button stays «In copia…» until the job ends (spec §4.10).
const copying = new Set();
+ // The videos being analysed («È un video fermo?», tappa E4): the answer may come once another file is on screen.
+ const analysing = new Set();
+ // Only the last reading of the analyses counts.
+ let analysesToken = 0;
+ let closed = false;
const where = h('span.dove');
const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x'));
@@ -82,13 +90,7 @@ export function openViewer({ tile, source, origin, onDeleted }) {
}
function close() {
- document.removeEventListener('keydown', onKey, true);
- stopWatching();
- onCopiesChanged.cancel();
- for (const v of box.querySelectorAll('video')) v.pause();
- if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
- box.remove();
- document.body.style.overflow = '';
+ dismiss();
if (entry && source && source.reveal) {
const key = keyAt(0);
if (key != null) source.reveal(key);
@@ -96,6 +98,20 @@ export function openViewer({ tile, source, origin, onDeleted }) {
if (opener && document.contains(opener)) opener.focus();
}
+ /** Takes the viewer away, also when the page under it changes (a link of a toast, Back): nothing under it is left. */
+ function dismiss() {
+ closed = true;
+ document.removeEventListener('keydown', onKey, true);
+ document.removeEventListener('febe:pagina', dismiss);
+ stopWatching();
+ onCopiesChanged.cancel();
+ onAnalysed.cancel();
+ for (const v of box.querySelectorAll('video')) v.pause();
+ if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
+ box.remove();
+ document.body.style.overflow = '';
+ }
+
function setZoom(on) {
zoomed = on;
stage.classList.toggle('ingrandita', on);
@@ -245,7 +261,8 @@ export function openViewer({ tile, source, origin, onDeleted }) {
fill(panelTop,
h('div.chi-vis', avatar(a.username, 'm', a.avatar), h('div', h('b', `@${a.username}`), a.displayName ? h('span', a.displayName) : null),
a.isFollowed ? label(t('vis.seguito'), 'accento', 'user-check') : null),
- h('div.etichette', label(typeLabel, '', KIND_ICON[entry.kind] || 'image'), a.isPrivate ? label(t('vis.privato'), '', 'lock') : null),
+ h('div.etichette', label(typeLabel, '', KIND_ICON[entry.kind] || 'image'), a.isPrivate ? label(t('vis.privato'), '', 'lock') : null,
+ isStill(media) ? label(t('esportazione.fermi.etichetta'), 'accento', 'image') : null),
h('div.quando', h('b', published), h('span', t('vis.pubblicato', { quando: ago(entry.publishedAt, serverNow(), today, entry.publishedDay) }))),
h('section', h('h3', t('vis.didascalia')), entry.caption ? h('p.didascalia', entry.caption) : h('p.didascalia.muto', t('vis.senzaDidascalia'))),
h('section', h('h3', t('vis.file')), h('dl',
@@ -253,6 +270,7 @@ export function openViewer({ tile, source, origin, onDeleted }) {
media && media.width && media.height ? row(t('vis.dimensioni'), t('vis.pixel', { l: number(media.width), a: number(media.height) })) : null,
media && media.bytes ? row(t('vis.peso'), bytes(media.bytes)) : null,
media && media.duration ? row(t('vis.durata'), duration(media.duration)) : null,
+ media ? stillRow(media) : null,
media ? row(t('vis.cartella'), media.folder) : null,
row(t('vis.codice'), entry.code || entry.instagramId),
entry.author ? row(t('vis.autore'), `@${entry.author}`) : null,
@@ -288,6 +306,16 @@ export function openViewer({ tile, source, origin, onDeleted }) {
actions.push(h('button.btn.azione-fotogramma', { type: 'button', onclick: () => openFrames(media) }, icon('image'), t('esportazione.vis.fotogrammaAzione')));
}
}
+ // Tappa E4: «È un video fermo?» on request only, then «Salva il fotogramma» of a video that is.
+ if (canAnalyse(media)) {
+ if (isStill(media)) {
+ actions.push(h('button.btn.azione-salva-fotogramma', { type: 'button', onclick: () => openStillFrame(media) }, icon('image'), t('esportazione.fermi.salva')));
+ } else if (!media.still) {
+ const busy = analysing.has(media.id);
+ actions.push(h('button.btn.azione-video-fermo', { type: 'button', disabled: busy, onclick: () => analyse(media) },
+ icon(busy ? 'hourglass' : 'search'), t(busy ? 'esportazione.fermi.inCorso' : 'esportazione.fermi.chiedi')));
+ }
+ }
if (entry.state !== 'deleted') {
actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina')));
}
@@ -348,6 +376,87 @@ export function openViewer({ tile, source, origin, onDeleted }) {
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)];
}
+ // ------------------------------------------------------------------------------------------- video fermi (tappa E4)
+ function isStill(media) {
+ return Boolean(media && media.still && media.still.outcome === 'still');
+ }
+
+ /**
+ * What the analysis said of the video: «Un'immagine sola per tutto il video: basta un fotogramma», «No: l'immagine
+ * cambia» or «Non analizzabile» and why. «Analizza di nuovo» where another answer is possible.
+ */
+ function stillRow(media) {
+ const still = media.still;
+ if (media.kind !== 'video' || !still) return null;
+ const busy = analysing.has(media.id);
+ const again = canAnalyse(media) && (still.outcome === 'notAnalyzable' || !still.current)
+ ? h('button.btn.nudo.piccolo.analizza-di-nuovo', { type: 'button', disabled: busy, onclick: () => analyse(media) },
+ icon('rotate-cw', 's'), t(busy ? 'esportazione.fermi.inCorso' : 'esportazione.fermi.analizzaDiNuovo'))
+ : null;
+ return [h('dt', t('esportazione.fermi.riga')), h('dd.riga-copia.riga-fermo', h('span', stillText(still)), again,
+ still.current ? null : h('span.nota-copia', t('esportazione.fermi.vecchia')))];
+ }
+
+ /** «È un video fermo?»: at most 30 seconds, also during an engine session; the video on screen goes on playing. */
+ async function analyse(media) {
+ if (analysing.has(media.id)) return;
+ analysing.add(media.id);
+ drawPanel();
+ let still = null;
+ let problem = null;
+ try {
+ still = await api(`/api/media/${media.id}/still`, { method: 'POST' });
+ } catch (error) {
+ problem = error;
+ }
+ analysing.delete(media.id);
+ if (closed) return;
+ if (still) {
+ analysesToken++;
+ setStill(media.id, still);
+ }
+ const current = entry.media[fileIndex];
+ if (!current || current.id !== media.id) return;
+ const lostFocus = document.activeElement === document.body;
+ drawPanel();
+ // The button that asked is gone: the keyboard goes on from what took its place.
+ const following = lostFocus && box.querySelector('.azione-salva-fotogramma, .azione-video-fermo, .analizza-di-nuovo, .azione-fotogramma');
+ if (following) following.focus();
+ if (problem) showError(problem);
+ else toast(t(`esportazione.fermi.risposte.${still.outcome}`));
+ }
+
+ function setStill(mediaId, still) {
+ const media = entry.media.find((m) => m.id === mediaId);
+ if (media) media.still = still;
+ }
+
+ /** «Salva il fotogramma»: the sharpest frame the analysis looked at; the video waits while the dialog is open. */
+ function openStillFrame(media) {
+ const video = stage.querySelector('video');
+ if (video) video.pause();
+ framesDialog({ mediaId: media.id, still: { label: media.still.frameLabel || '' }, hasDestination: Boolean(entry.canCopy) });
+ }
+
+ /** Analyses made elsewhere (a selection, another window): only the panel follows, never the video on screen. */
+ async function readAnalyses() {
+ if (!entry) return;
+ const id = entry.id;
+ const mine = ++analysesToken;
+ let fresh;
+ try {
+ fresh = await api(`/api/entries/${id}`);
+ } catch {
+ return;
+ }
+ // Asked again since, or answered by «È un video fermo?»: an older answer must not bring back what was before.
+ if (closed || !entry || entry.id !== id || mine !== analysesToken) return;
+ const stills = (media) => JSON.stringify(media.map((m) => [m.id, m.still || null]));
+ if (stills(fresh.media) === stills(entry.media)) return;
+ for (const m of fresh.media) setStill(m.id, m.still || null);
+ drawPanel();
+ }
+
async function showConversion(conversionId) {
try {
const result = await api('/api/conversions/show-in-folder', { method: 'POST', body: { conversionId } });
@@ -402,11 +511,15 @@ export function openViewer({ tile, source, origin, onDeleted }) {
const current = entry.media[fileIndex];
load(entry.id, fileIndex, current ? current.id : null);
}, 400);
+ const onAnalysed = later(readAnalyses, 400);
const stopWatching = onLibrary((change) => {
if (change.reason === 'export') onCopiesChanged();
+ // An outcome belongs to the file: the same video may be here under another account than the one analysed.
+ if (change.reason === 'fermi' && entry && entry.media.some((m) => m.kind === 'video')) onAnalysed();
});
document.addEventListener('keydown', onKey, true);
+ document.addEventListener('febe:pagina', dismiss);
document.body.append(box);
closeButton.focus();
load(tile.id, 0, files && tile.cover ? tile.cover.mediaId : null);
diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json
index 9a06c5f..4c71a84 100644
--- a/src/Febe.Web/wwwroot/testi/it.json
+++ b/src/Febe.Web/wwwroot/testi/it.json
@@ -90,6 +90,7 @@
"all": "Tutto",
"photos": "Foto",
"videos": "Video",
+ "stillVideos": "Video fermi",
"stories": "Storie",
"highlights": "In evidenza",
"tagged": "Taggati"
@@ -1288,7 +1289,62 @@
},
"selezione": {
"copia": "Copia in…",
- "fotogrammi": "Fotogrammi…"
+ "fotogrammi": "Fotogrammi…",
+ "fermi": "Cerca i video fermi"
+ },
+ "fermi": {
+ "etichetta": "Video fermo",
+ "riga": "Video fermo",
+ "fermo": "Un'immagine sola per tutto il video: basta un fotogramma",
+ "istante": " · fotogramma a {istante}",
+ "piccolaParte": " · una piccola parte si muove",
+ "inMovimento": "No: l'immagine cambia",
+ "nonAnalizzabile": "Non analizzabile",
+ "nonAnalizzabilePerche": "Non analizzabile: {motivo}",
+ "motivi": {
+ "FrameNotAvailable": "fotogramma non disponibile per questo video",
+ "DurationUnknown": "la durata del video non si conosce",
+ "Unreadable": "il video non si legge",
+ "TooSlow": "l'analisi richiedeva troppo tempo",
+ "AllDark": "il video è tutto nero",
+ "SingleColor": "il video è tutto di un solo colore"
+ },
+ "vecchia": "analizzato da una versione di Febe di prima",
+ "analizzaDiNuovo": "Analizza di nuovo",
+ "chiedi": "È un video fermo?",
+ "inCorso": "Analisi in corso…",
+ "risposte": {
+ "still": "Video fermo: basta un fotogramma.",
+ "moving": "Non è un video fermo: l'immagine cambia.",
+ "notAnalyzable": "Video non analizzabile."
+ },
+ "salva": "Salva il fotogramma",
+ "salvaAnteprima": "Il fotogramma che si salva",
+ "salvaQuale": "Il fotogramma più nitido fra quelli guardati dall'analisi, a {istante}.",
+ "salvaScaricaAiuto": "Il fotogramma si scarica com'è, con «_fotogramma» nel nome.",
+ "salvaCartellaAiuto": "Nella cartella delle copie dell'account, accanto alle copie, con «_fotogramma» nel nome. Il video intero si copia comunque con «Copia in…».",
+ "salvaRiepilogo": "1 fotogramma",
+ "salvaNiente": "Niente da copiare: l'account non si esporta, o il video non è fermo per l'ultima analisi.",
+ "cercaTitolo": "Cerca i video fermi",
+ "conto": "Conto i video…",
+ "cercaAiuto": "Un video alla volta, mai durante una sessione del motore né mentre lavorano importazione, copie o ricostruzione. L'avanzamento è nella Dashboard, scheda Esportazione, con «Interrompi».",
+ "cercaRiapertura": "Se chiudi Febe a metà, la ricerca non riprende da sola: rilanciala, e i video già analizzati si saltano.",
+ "analizza": "Analizza 1 video|Analizza {n} video",
+ "niente": "Niente da analizzare: i video scelti sono già analizzati o non sono in libreria.",
+ "nienteVideo": "Niente da analizzare: fra gli elementi scelti non ci sono video.",
+ "avviata": "Ricerca dei video fermi avviata: 1 video da analizzare.|Ricerca dei video fermi avviata: {n} video da analizzare.",
+ "giaInCoda": "I video scelti sono già in coda.",
+ "mostra": "Mostra i video fermi",
+ "interrotta": "Ricerca interrotta. {riepilogo}.",
+ "interrottaSubito": "Ricerca interrotta: nessun video analizzato.",
+ "dashboard": {
+ "titolo": "Video fermi",
+ "barra": "Ricerca dei video fermi",
+ "avanzamento": "{fatti} di 1 video analizzato|{fatti} di {n} video analizzati",
+ "fermi": "1 fermo|{n} fermi",
+ "analizzo": "Analizzo un video…",
+ "interrompi": "Interrompi"
+ }
},
"fotogrammi": {
"titolo": "Fotogrammi",
diff --git a/tests/Febe.Tests/Data/ExportConstraintTests.cs b/tests/Febe.Tests/Data/ExportConstraintTests.cs
index 9ee2ea1..116a860 100644
--- a/tests/Febe.Tests/Data/ExportConstraintTests.cs
+++ b/tests/Febe.Tests/Data/ExportConstraintTests.cs
@@ -57,7 +57,7 @@ public sealed class ExportConstraintTests
await RejectedAsync(db, "export_item", w.ItemRow(run, ("state", "Done"), ("media_id", w.LucaMedia)), "stato del file");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("variant", "Intero"), ("media_id", w.LucaMedia)), "variante del file");
await RejectedAsync(db, "export_item", w.ItemRow(run, ("format", "Gif"), ("variant", "Converted"), ("media_id", w.LucaMedia)), "formato del file");
- await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Fermo"), ("sha256", Make.Sha(6))), "esito");
+ await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Fermo"), ("frame_at_ms", null), ("sha256", Make.Sha(6))), "esito");
await RejectedAsync(db, "video_analysis", AnalysisRow(("algorithm", 0L), ("sha256", Make.Sha(6))), "algoritmo 0");
await RejectedAsync(db, "media_conversion", w.ConversionRow(("format", "Original"), ("media_id", w.LucaMedia)), "un convertito ha un altro formato");
await RejectedAsync(
@@ -188,6 +188,31 @@ public sealed class ExportConstraintTests
await InsertAsync(db, "media_conversion", Converted(w, "Jpg", Make.Sha(2), ("bytes", 0L)));
}
+ ///
+ /// The columns of migration 0005 (tappa E4): a still video has the instant of its frame, no other outcome has one, and
+ /// a «Non analizzabile» says why. Each row breaks that CHECK alone (the same row with a valid value is accepted).
+ ///
+ [TestMethod]
+ public async Task VideoAnalysisFrameAndNoteGoWithTheOutcome()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+
+ await RejectedAsync(db, "video_analysis", AnalysisRow(("frame_at_ms", null)), "fermo senza istante");
+ await RejectedAsync(db, "video_analysis", AnalysisRow(("frame_at_ms", -1L)), "istante negativo");
+ await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Moving")), "in movimento con un istante");
+ await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "NotAnalyzable"), ("frame_at_ms", null)), "non analizzabile senza nota");
+ await RejectedAsync(db, "video_analysis", AnalysisRow(("outcome", "Moving"), ("frame_at_ms", null), ("note", "")), "nota vuota");
+ await SchemaDeclaresAsync(db, "video_analysis", "CHECK ((outcome = 'Still') = (frame_at_ms IS NOT NULL))");
+ await SchemaDeclaresAsync(db, "video_analysis", "CHECK (outcome <> 'NotAnalyzable' OR note IS NOT NULL)");
+
+ await InsertAsync(db, "video_analysis", AnalysisRow());
+ await InsertAsync(db, "video_analysis", AnalysisRow(("sha256", Make.Sha(6)), ("frame_at_ms", 1125L), ("note", "Prova")));
+ await InsertAsync(db, "video_analysis", AnalysisRow(("sha256", Make.Sha(7)), ("outcome", "Moving"), ("frame_at_ms", null)));
+ await InsertAsync(db, "video_analysis", AnalysisRow(("sha256", Make.Sha(8)), ("outcome", "NotAnalyzable"), ("frame_at_ms", null), ("note", "TooSlow")));
+ Assert.AreEqual(4L, await ScalarAsync(db, "SELECT COUNT(*) FROM video_analysis"));
+ }
+
/// The removed account kept on a copy: only on a row without account, never empty, and both may be unknown.
[TestMethod]
public async Task TheRemovedAccountIsKeptOnlyOnOrphanCopies()
diff --git a/tests/Febe.Tests/Data/ExportStoreTests.cs b/tests/Febe.Tests/Data/ExportStoreTests.cs
index 55508c8..1eb0e20 100644
--- a/tests/Febe.Tests/Data/ExportStoreTests.cs
+++ b/tests/Febe.Tests/Data/ExportStoreTests.cs
@@ -791,20 +791,22 @@ public sealed class ExportStoreTests
await using var db = await TestDatabase.OpenAsync(temp);
Assert.IsNull(await db.VideoAnalyses.GetAsync(Make.Sha(1)));
- await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1).ToUpperInvariant(), 1, VideoAnalysisOutcome.Still, Make.T0));
- Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0), await db.VideoAnalyses.GetAsync(Make.Sha(1)));
+ await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1).ToUpperInvariant(), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(1125)));
+ Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(1125)), await db.VideoAnalyses.GetAsync(Make.Sha(1)));
await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Moving, Make.T0.AddDays(1)));
Assert.AreEqual(2, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Algorithm, "vale l'algoritmo più alto");
- await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0.AddDays(2)));
+ await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0.AddDays(2), Note: VideoAnalysisNotes.TooSlow));
Assert.AreEqual(VideoAnalysisOutcome.Moving, (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Outcome);
- await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3)));
- Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3)), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo si sostituisce");
+ await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3), TimeSpan.Zero));
+ Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 2, VideoAnalysisOutcome.Still, Make.T0.AddDays(3), TimeSpan.Zero), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo si sostituisce");
Assert.AreEqual(2L, await ScalarAsync(db, "SELECT COUNT(*) FROM video_analysis"));
for (var i = 10; i < 710; i++)
{
- await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(i), 1, i % 2 == 0 ? VideoAnalysisOutcome.Still : VideoAnalysisOutcome.Moving, Make.T0));
+ await db.VideoAnalyses.SetAsync(i % 2 == 0
+ ? new VideoAnalysis(Make.Sha(i), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(i))
+ : new VideoAnalysis(Make.Sha(i), 1, VideoAnalysisOutcome.Moving, Make.T0));
}
var keys = Enumerable.Range(0, 800).Select(Make.Sha).ToList();
@@ -812,7 +814,54 @@ public sealed class ExportStoreTests
Assert.HasCount(701, many);
Assert.AreEqual(2, many[Make.Sha(1)].Algorithm);
Assert.AreEqual(VideoAnalysisOutcome.Moving, many[Make.Sha(709)].Outcome);
- await Assert.ThrowsExactlyAsync(() => db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 0, VideoAnalysisOutcome.Still, Make.T0)));
+ Assert.AreEqual(TimeSpan.FromMilliseconds(708), many[Make.Sha(708)].FrameAt, "GetManyAsync legge anche l'istante");
+ await Assert.ThrowsExactlyAsync(() => db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 0, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.Zero)));
+ }
+
+ ///
+ /// The instant of the frame and the note of migration 0005 (tappa E4) round-trip; the store keeps a still video with
+ /// its instant and only it, and a «Non analizzabile» with the reason, so the viewer can always say why.
+ ///
+ [TestMethod]
+ public async Task VideoAnalysesKeepTheFrameAndTheNote()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+
+ foreach (var code in VideoAnalysisNotes.All)
+ {
+ var sha = Make.Sha(100 + VideoAnalysisNotes.All.ToList().IndexOf(code));
+ await db.VideoAnalyses.SetAsync(new VideoAnalysis(sha, 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: code));
+ Assert.AreEqual(new VideoAnalysis(sha, 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, null, code), await db.VideoAnalyses.GetAsync(sha), code);
+ }
+
+ await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: " TooSlow Unreadable "));
+ Assert.AreEqual("TooSlow Unreadable", (await db.VideoAnalyses.GetAsync(Make.Sha(1)))!.Note, "codici separati da uno spazio");
+ await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(2500.7), " "));
+ var still = await db.VideoAnalyses.GetAsync(Make.Sha(1));
+ Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(2500), null), still, "millisecondi interi, nessuna nota vuota");
+ await db.VideoAnalyses.SetAsync(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Moving, Make.T0));
+ Assert.AreEqual(new VideoAnalysis(Make.Sha(1), 1, VideoAnalysisOutcome.Moving, Make.T0), await db.VideoAnalyses.GetAsync(Make.Sha(1)), "lo stesso algoritmo toglie istante e nota");
+ Assert.AreEqual(1L, await ScalarAsync(db, $"SELECT COUNT(*) FROM video_analysis WHERE sha256 = '{Make.Sha(1)}'"));
+
+ var refused = new[]
+ {
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Still, Make.T0),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(-1)),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Moving, Make.T0, TimeSpan.Zero),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, TimeSpan.Zero, VideoAnalysisNotes.TooSlow),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: " "),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: "C:/video/a.mp4"),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, Note: "Il video non si legge"),
+ new VideoAnalysis(Make.Sha(2), 1, VideoAnalysisOutcome.Moving, Make.T0, Note: "1Code"),
+ };
+ foreach (var analysis in refused)
+ {
+ await Assert.ThrowsExactlyAsync(() => db.VideoAnalyses.SetAsync(analysis), analysis.ToString());
+ }
+
+ Assert.IsNull(await db.VideoAnalyses.GetAsync(Make.Sha(2)), "nulla di rifiutato si scrive");
}
[TestMethod]
diff --git a/tests/Febe.Tests/Data/ExportWorld.cs b/tests/Febe.Tests/Data/ExportWorld.cs
index 4387e13..ceafe70 100644
--- a/tests/Febe.Tests/Data/ExportWorld.cs
+++ b/tests/Febe.Tests/Data/ExportWorld.cs
@@ -104,7 +104,7 @@ internal sealed record ExportWorld(long Marta, long Luca, long MartaEntry, long
changes);
public static Dictionary AnalysisRow(params (string Column, object? Value)[] changes) => Row(
- new() { ["sha256"] = Make.Sha(5), ["algorithm"] = 1L, ["outcome"] = "Still", ["analyzed_at"] = 0L },
+ new() { ["sha256"] = Make.Sha(5), ["algorithm"] = 1L, ["outcome"] = "Still", ["analyzed_at"] = 0L, ["frame_at_ms"] = 0L },
changes);
public Dictionary ConversionRow(params (string Column, object? Value)[] changes) => Row(
diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs
index 621b7e7..e3f8b0e 100644
--- a/tests/Febe.Tests/Data/LibraryScaleTests.cs
+++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs
@@ -81,17 +81,20 @@ public sealed class LibraryScaleTests
}
var copies = await FillCopiesAsync(db, temp, accountIds, ct);
+ var still = await FillStillVideosAsync(db, 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");
+ TestContext.WriteLine($"Video fermi: {still.Analyses:N0} analisi, {still.Still:N0} «Fermo» (di cui {still.Overruled:N0} superati da un algoritmo più nuovo), {still.Entries:N0} elementi e {still.Files:N0} file nel filtro");
Assert.IsGreaterThan(0, copies.Converted, "converted copies in the fill");
Assert.IsGreaterThan(0, copies.Frames, "frames in the fill");
+ Assert.IsGreaterThan(0, still.Overruled, "still videos overruled by a newer algorithm in the fill");
// Plans differ with and without ANALYZE statistics: both must be fast.
// The fill stays outside the timings.
- await MeasureAll(db, accountIds, copies, "senza statistiche", ct);
+ await MeasureAll(db, accountIds, copies, still, "senza statistiche", ct);
await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct);
- await MeasureAll(db, accountIds, copies, "con ANALYZE", ct);
+ await MeasureAll(db, accountIds, copies, still, "con ANALYZE", ct);
}
///
@@ -103,8 +106,6 @@ public sealed class LibraryScaleTests
///
private static async Task FillCopiesAsync(FebeDatabase db, TempFolder temp, List accountIds, CancellationToken ct)
{
- const string Hash = "((m.id * 2654435761) % 1000003)";
- const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)";
var general = await db.Exports.AddDestinationAsync(
new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct);
var own = await db.Exports.AddDestinationAsync(
@@ -148,6 +149,55 @@ public sealed class LibraryScaleTests
ct);
}
+ // A hash of the media id that mixes the ids (see FillCopiesAsync).
+ private const string Hash = "((m.id * 2654435761) % 1000003)";
+ private const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)";
+
+ ///
+ /// Tappa E4, the filter «Video fermi»: seven videos in ten analysed (about 20,000 of the 28,600 videos), half of them
+ /// «Fermo» (about 10,000, frame at 1 s) and half «In movimento»; one «Fermo» in ten has a newer algorithm that says
+ /// «In movimento», so it is out of the filter. The expected entries and files are counted here with a join on the
+ /// highest algorithm, another form than the filter's own.
+ ///
+ private static Task FillStillVideosAsync(FebeDatabase db, List accountIds, CancellationToken ct) =>
+ db.WriteAsync(
+ w =>
+ {
+ var videos = $"FROM media m WHERE m.kind = 'Video' AND m.sha256 IS NOT NULL AND {Spread} % 10 < 7";
+ var analyses = w.Command($"""
+ INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note)
+ SELECT m.sha256, 1, CASE WHEN {Spread} % 2 = 0 THEN 'Still' ELSE 'Moving' END, 1767225600000,
+ CASE WHEN {Spread} % 2 = 0 THEN 1000 END, NULL
+ {videos}
+ """).ExecuteNonQuery();
+ var overruled = w.Command($"""
+ INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note)
+ SELECT m.sha256, 2, 'Moving', 1767225600000, NULL, NULL
+ {videos} AND {Spread} % 2 = 0 AND {Spread} % 20 < 2
+ """).ExecuteNonQuery();
+ var still = (int)w.Command("SELECT COUNT(*) FROM video_analysis WHERE outcome = 'Still'").ScalarInt64();
+ const string Latest = """
+ FROM media m JOIN video_analysis va ON va.sha256 = m.sha256
+ WHERE m.kind = 'Video' AND m.state IN ('Downloaded', 'Imported') AND va.outcome = 'Still'
+ AND va.algorithm = (SELECT MAX(x.algorithm) FROM video_analysis x WHERE x.sha256 = va.sha256)
+ """;
+ var entries = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest}").ScalarInt64();
+ var files = (int)w.Command($"SELECT COUNT(*) {Latest}").ScalarInt64();
+ var account = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)")
+ .With("@a", accountIds[3]).ScalarInt64();
+ var accountFiles = (int)w.Command($"SELECT COUNT(*) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)")
+ .With("@a", accountIds[3]).ScalarInt64();
+ return new StillWorld(analyses + overruled, still, overruled, entries, files, account, accountFiles);
+ },
+ ct);
+
+ ///
+ /// What the fill of the analyses wrote: rows, «Fermo» rows, those overruled by a newer algorithm, and the entries
+ /// and files the filter must find ( and : those of
+ /// account 3).
+ ///
+ private sealed record StillWorld(int Analyses, int Still, int Overruled, int Entries, int Files, int AccountEntries, int AccountFiles);
+
/// 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)
{
@@ -162,7 +212,7 @@ public sealed class LibraryScaleTests
_ => 1 + (n % 5 == 0 ? 1 : 0),
});
- private async Task MeasureAll(FebeDatabase db, List accountIds, CopiesWorld copies, string label, CancellationToken ct)
+ private async Task MeasureAll(FebeDatabase db, List accountIds, CopiesWorld copies, StillWorld still, string label, CancellationToken ct)
{
var times = new List<(string Name, double Bound, Timing